Understanding Types in .Net Part 1: var keyword

It’s surprising to me how many developers don’t understand the .Net type system. So I decided to write a series of posts on of some of the misconceptions.

The “var” keyword, introduced in C# 3 is implicit typing. For all intents and purposes, this is the same as strong typing. It is strongly typed at runtime. Implicit typing means that at compile time, the type of the variable is determined based on what is originally assigned to it. You can sort of think of it like a text macro in C. In that metaphor, the token var is replaced with the appropriate type. If the compiler determines that variable is a string, then you can not later assign an int to variable, the same as if you had declared it a string in the first place.

The intent was to make typing easier with some of the linq types and generics. See the following lines of code that do the same thing:

List<ICustomer<Retail>> Customers = new List<Customer<Retail>>();

// add customer here

// old way
IQueryable<ICustomer<Retail>> lateCustomers = 
                              Customers.Where(c => c.Bills.UpToDate == true);

// new way using var, 
//   c is still typed as IQueryable<ICustomer<Retail>>
var c = Customers.Where(c => c.Bills.UpToDate == true);

Here are some unit tests demonstrating that var is still strongly typed.

using System;
using System.Collections.Generic;
using NUnit.Framework;

namespace Tests
{
    [TestFixture]
    class TempTest
    {
        [Test]
        public void VarTypeIsStatic()
        {
            var v = "foo";
            string s = v;
            // v = 3; //This would be illegal
            Assert.AreSame(v.GetType(), s.GetType());
            Assert.AreSame(v,s);
        }
    }
}

Hopefully, this becomes more clear to developers in .Net 4. After all, why would the dynamic keyword be added if var was weakly typed?


Posted

in

by

Tags: