#596 – Implicitly-Typed Arrays and Best Type Inference

When you declare and initialize an implicitly-typed array, the C# compiler tries to find a single type that best fits all of the values that you provide.  Constant values can be of different types, as long as they are all implicitly convertible to a single common type.

// Becomes int[]
var numbers = new[] { 1, 2, 3 };

// Becomes double[]
var moreNums = new[] { 1.1, 2.2, 3.3 };

// Also double[], int values convertible to double
var evenMore = new[] { 1, 2, 3.3 };

Note that the compiler will not implicitly convert everything to object, if System.Object is the only common type found.

// Compile-time error: No best type found for implicitly-typed array
var stuff = new[] { 1, 2, "dog" };

If you did want an array of objects, you could use an explicit cast.

            // Becomes object[]
            var stuffFixed = new[] { (object)1, (object)2, (object)"dog" };
Advertisements

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: