#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" };

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

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 )

Connecting to %s

%d bloggers like this: