.NET 3.5: Implicitly Typed Local Variables

Damir Dobric Posts

Next talks:

 

    

Follow me on Twitter: #ddobric



 

 

Archives

In this post I will show very short example which introduces the powerful feature of .NET 3.5 called Implicitly Typed Local Variables. Sometimes there are types in the framework which are generated on demand during runtime. They are used in always in the local scope and have no name. To illustrate this, take a look on the following code:

var DaenetDouble = 7.7;


This code defines a type with DaenetDouble which is implicitly reflected as double. The word var can be used in local function's scope only and it is not legal as
field or parameter. Note that the new variable is strongly typed. For example following code will con compile at all:

var DaenetDouble = 7.7;
DaenetDouble = "hello";


Such types are very important for LINQ features, but they can be used to simplify some other complex types.
Following example shows how to simplify some complex dictionary:

var SimpleType = new Dictionary<Dictionary<string, int>,
Dictionary<string, Dictionary<string, double>>>();

var thirdDictionary = new Dictionary<string,double>();
thirdDictionary.Add("key31", 3.1);
thirdDictionary.Add("key32", 3.2);

// This will not compile.
//var secondDictionary = new Dictionary<string, thirdDictionary>();

// This compiles.
var secondDictionary = new Dictionary<string, Dictionary<string, double>>();

secondDictionary.Add("key21", thirdDictionary);
var firstDictionary = new Dictionary<string, int>();

firstDictionary.Add("key11", 1);
firstDictionary.Add("key12", 2);

SimpleType.Add(firstDictionary, secondDictionary);

Related example: Type Initializers.


Posted May 28 2007, 11:56 PM by Damir Dobric
Filed under:
developers.de is a .Net Community Blog powered by daenet GmbH.