Type Inference

Type inference allows a variable to infer the type being assigned to it. No more should a variable be strongly typed. C# offers the varkeyword for type inference.

var myInt = 10;
var myDouble = 5.67;
var myString = "Hello";

The three variables above are implicitly typed, meaning that they will automatically change their types depending on the values assigned to them. You simply use the var keyword as the type of the variable. You can even store objects in a var variable.

var sample = new SampleClass();

It can even hold arrays.

var myArray = new int [] { 1, 2, 3 };

//OR

var myArray = new [] { 1, 2, 3 };

Notice that you can omit the type since the type will be inferred depending on the values given.

Since the type of the variable is determined by the value being assigned to it, you cannot simply declare a variable having a var type. The following code will not compile because it cannot determine the type to be assigned to the variable since no value was supplied.

var someVariable;

One final note about the var used as type. You cannot use it as return types or as types of parameters of a method.

Written by compitionpoint

Leave a Comment

Your email address will not be published. Required fields are marked *