Behind the scene of var in .Net

There are lots of discussion going on about var. Should we use var to declare a type or not. After reading lots of article I decided to disassemble code used var by .Net Reflector.

So I wrote a simple library named ImplicitCodeLibrary with two simple types VarDeclarationTester and TestClass.

  • VarDeclarationTester - will instantiate two types DateTime and TestClass using Implicit way such as var and another one explicit way.
  • TestClass - it is just a test class use to instantiate a custom type.

namespace ImplicitCodeLibrary
    using System;
    public class VarDeclarationTester
        public void ImplicitTypeTest()
            var dateTimeImplicit = new DateTime(2011, 3, 21);
            var testClassImplicit = new TestClass();
            DateTime dateTimeExplicit = new DateTime(2011, 1, 11);
            TestClass testClassExplicit = new TestClass();
    public class TestClass
        public TestClass() { }
        public void GetAmount()

After compiling the code, I open the generated DLL via .Net Reflector. The result I found is as follow,

So the lines,

var dateTimeImplicit and var testClassImplicit have been replaced by code DateTime dateTimeImplicit and TestClass testClassImplicit on compile time.

So, what we can see in here, on Compile time Type has been given by Compiler.


No comments:

Post a Comment