Chitika

Saturday, October 6, 2012

return var in c#


return var type is required when we are generic types. var in c# is most common type used in most of the scenarios, some times we need to return var type from the functions . First see the small but important points about var.

var is strongly typed. So the moment you initialize the var type, It becomes that type. That means, if you write something like this
var stringType="Now var is string type."
stringType becomes a string type. So it is strongly typed. You can not assign a different type to this variable now like.
stringType=28;// will give compilation error

Another thing is, you can not define var as a property type.

So, to return var from C# functions we use IEnumerable .
Let see the example

One of the uses of IEnumerable is to return var in a function, see the sample below.

// QueryMethhod1 returns a query as its value.
public static IEnumerable<string> QueryMethod1(refint[] ints)
{
  var intsToStrings = from i in ints
                      where i > 4
                      select i.ToString();
  return intsToStrings;
}


So, now what ever is returning from the  QueryMethod1 will be of type var.
enjoy coding,,, :-)

No comments:

Post a Comment