Monday, December 8, 2008

Type Inference in C# (Implicitly Typed Local Variable)

Type inference is a new feature in C# 3.0. With Type Inference you allow compiler to determine the type of a local variable at compile time.

private void Form1_Load(object sender, EventArgs e)
{
var strName = "Shalvin";
MessageBox.Show(strName.GetType().ToString());

var intPoints = 67;
MessageBox.Show(intPoints.GetType().ToString());

var dblBalance = 110.50;
MessageBox.Show(dblBalance.GetType().ToString());
var cBool = true; Console.WriteLine(cBool.GetType()); var cDate = DateTime.Now; Console.WriteLine(cDate.GetType()); }


The first batch of statements creates a memory variable of type System.String.
The Second batch of statements (intPoints) creates a memory variable of type System.Int32.
The third batch of statments (dblBalance) creates a memory variable of type System.Double.
The statement var cBool = true; creates a memory variable of type System.Boolen.
The state var vDate = DateTime.Now; creates a memory variable of type System.DateTime.

Related Blog
Generics and Collection Initializer in .Net

No comments:

Post a Comment