Sunday, August 29, 2010

Var Keyword - Scenarios to remember

Multiple types for a single var

The following example will not work in var case

var SetConditionally = condition ? 500 : "badger" -> compiler cannot infer the type of setconditionnaly

Type inference understands subtyping

class Parent
{
}
class Child : Parent
{
}

The following implementation will compile and execute sucessfully . (Same works well if you would have replaced var with Parent in 2.0 but replacing var with child will not work)

var Condition = true;
var SetConditionally = Condition ? new Parent() : new Child();
//Remember GetType() is checked in runtime and not compile time.
Console.WriteLine("SetConditionally is of type " + SetConditionally.GetType().Name);



Implicit typing is necessary to insert the interface.

interface IVehicle
{
}
class Car: IVehicle
{
}
class Bike : IVehicle
{
}

The following implementation will throw compiler error.

var Condition = true;
var Vehicle = Condition ? new Car() : new Bike();
Console.WriteLine("Vehicle is of type " + Vehicle.GetType().Name);

Solve this by implicitily typing the interface

var Condition = true;
var Vehicle = Condition ? new (IVehicle)Car() : new (IVehicle)Bike();
Console.WriteLine("Vehicle is of type " + Vehicle.GetType().Name);


Elements of different type in Array

You will get a compile time error when elements of different type will be in array, following samples will throw compile time error.

var NullableInt = new [] { 1, 10, null, 42 };
var MultipleElements = new [] { "String", 100, "new", 20, 30.5 };

No comments: