What Is New in C# 3.0 - Part 4 (Type Inference and Anonymous Types)

  Welcome to part 4 of the "What Is New in C# 3.0" series. Lets present two of the features that can make your code shorter and are essential to LINQ.

  You can often read about a feature of C# 3.0 called "the var keyword". That is pure bullshit and the feature is actually called "type inference" or "implicit typing". This means that the compiler will guess (infer) the type of your variables and there is no need for you to specify it. It is written like this:

var mariable = "mring";

this is 100% equivalent to:

string mariable = "mring";

The type of variables declared with the var keyword is the type of the right-hand side expression. If you try

var mariable = "mring";

The output will be System.String. Also

var mariable = "mring";
mariable = 1;

will result in compile time error because you are trying to assign int to a string variable. It is very important not to mistake implicit typing with weak typing used in scripting languages like JavaScript.

How is this feature useful? Well imagine that you have to declare Dictionary<string, Dictionary<int, List<LongClassName>>> . Sometimes declarations can require a lot of typing and typing it twice like:

Dictionary<string, Dictionary<int, List<LongClassName>>> list = new Dictionary<string, Dictionary<int, List<LongClassName>>>();

makes things worse. Sometimes just the class name can be annoyingly long. Sometimes the type that the method returns may be in a different namespace. In that case you have to either add the namespace with “using” or type the namespace name. Normally you do not wish to add namespaces just for one variable and with the var keyword you could avoid typing the namespace name. The example above would look like this:

var list = new Dictionary<string, Dictionary<int, List<LongClassName>>>();

It looks almost 50% better. Full intellisense support is also present.

  This is not a big deal but the next feature would be impossible without the var keyword. Anonymous types are types declared when creating an instance. The syntax looks like this:

var mariable = new { Mext = "mext", Mumber = 3};

The compiler will create a class behind the curtain with two get/set properties. Notice that the type of the properties will be inferred using type inference and Mext will be of type string and Mumber will be of type int.

You can use mariable like any other instance of a class:


output of the first two lines will be "mext" and "3". The third line will return the internal name of the anonymous type that looks like this:


If you declare two variables with the same property names and property types they will use the same anonymous type. The anonymous types can also copy the names of the properties when they are created from other classes instances like this:

class Mlass
   string Mring { get; set;}
   int Mint { get; set; }


Mlass misntance = new Mlass { Mring = "mring", Mint = 3 };
var clone = new { minstance.Mring, minstance.Mint };


  The "clone" variable will be of anonymous type. Notice how anonymous types use two of the new features of C# 3.0 - type inference and object initializers. Pieces are starting to form a bigger picture.

  Remember when I told you that collection initializers are one exception of the rule that a new feature should be useful in LINQ context and out of LINQ context? Collection initializers are not useful in LINQ context as far as I know. The anonymous types seem to be another exception. I cannot find any example in which they make sense out of LINQ context. If you can find any non-LINQ uses of anonymous types please let me know.

Cya and stay tuned for part 5.
Tags:   english programming 
Posted by:   Stilgar
01:57 15.02.2008


First Previous 1 Next Last 

Posted by   anonymous (Unregistered)   on   02:44 15.02.2008

Как така ще да няам смисъл извън LINQ контекста?

Posted by   Stilgar Worshiper (Unregistered)   on   03:21 15.02.2008

Go Stilgar GO!!!

Posted by   Stilgar   on   04:07 15.02.2008

Ami dai primer za polezna upotreba na anonimni tipove bez da namesvash LINQ

Posted by   anonymous (Unregistered)   on   12:59 15.02.2008

Като 1 виден анонимен тип мога да поствам анонимно по блогове :)

Posted by   AdolfPresley   on   16:55 15.02.2008

Само не разбрах каква е поуката от тази статия? Какво е посланието към читателите? C# е известен с ниската обществена ангажираност, която предоставя.

Posted by   Guest (Unregistered)   on   04:37 16.02.2008

Че то това с "var" отдавна си го има във VB:
Dim x As Integer

Posted by   Guest (Unregistered)   on   04:38 16.02.2008

И що не пишеш на български бе, хаймана ? :D

Posted by   Stilgar   on   06:06 16.02.2008

a ima li
Dim x As 5?
shtoto sme dlujni na Google za tva ne pisha na bulgarski
osven tva ne obicham bulgarski

Posted by   Guest (Unregistered)   on   18:39 16.02.2008

VB е от преди повече от 10 години. Не ми се пъчи че нямало "Dim x As 5" :)

Ти наистина ли смяташ, че Google ще ти посети сайта, някой после ще се обърка и ще напише за търсене "mring" вместо "string" или "mroperty" вместо "property" и ще попадне тук ? :)

Posted by   Stilgar   on   21:31 16.02.2008

Vchera gledah imah hits za "instantiate objects in C#"

Posted by   Guest (Unregistered)   on   18:32 17.02.2008

Днес вече няма hits :D

Posted by   Stilgar   on   21:38 17.02.2008

Vse niakoga shte ima. V kraina smetka ne riadko sum namiral kvoto mi triabva na niakvi blogove v toia stil. 1 da hitne e dalavera che e bilo na angliiski.

Posted by   .NET junky (Unregistered)   on   14:48 22.02.2008


First Previous 1 Next Last 

Post as:

Post a comment: