Saturday, July 10, 2010

Implicitly Typed Array C#

C# 4.0 in a Nutshell: The Definitive Reference
Implicitly typed array is a feature introduced with C# 3.0

that allows compiler to deduce the type of array.

private void Window_Loaded(object sender, RoutedEventArgs e)
//1. An implicitly typed array of string
var friends = new[] { "Praseed", "Biju" };

//2.  An implicitly typed array
var points = new[] { 90, 95, 966 };
MessageBox.Show (points.GetType().ToString());

//3. An array of doubles
var price = new[] { 10.40, 10, 60 };
MessageBox.Show (price.GetType().ToString());

In this example instead of I giving a type to the arrays

I am expecting the compiler to deduce the type. Compiler no doubt is a smarter guy than me.

The first two examples are self explanatory in nature.

The first example will produce an output of System.String[].

Second example will produce and output of System.Int32[].

In the third case where I am providing multiple types, the compiler will deduce the type that all other given types can be conveted to. In this case it will be producing an array of double.

No comments:

Post a Comment