What is Local Type Inference in C# 3.0?

C# 3.0 has new feature called "Local Type Inference". Type Inference lets compiler decide the data type of variable/object. Variable initializing data value helps compiler to decide the data type. C# 3.0 introduces new keywaord "var" to declare such variables. No explicit type declaration is required.

Local Type Inference has type inference only for local variables. One cannot declare class-/struct-level fields with keyword "var". "var" cannot act as return type for function and cannot appear in function parameter i.e. no "var" should be used in function signature.


using System;

namespace TypeInference
{
class Program
{
static void Main(string[] args)
{
var i = 5;
var intArray = new int[] { 1, 2, 3, 4, 5 };
//Variables declared with var cannot be assigned to null if no type has been inferred.
var str = default(string);
Console.WriteLine("Data Type Of i:"+i.GetType().Name);
Console.WriteLine("Data Type of intArray:" + intArray.GetType().Name);
//Console.WriteLine("Data Type of str:" + str.GetType().Name); -->Null Reference Exception
str = "";
Console.WriteLine("Data Type of str:" + str.GetType().Name);
}
}
}

No comments:

Post a Comment