C# Error CS0826 – No best type found for implicitly-typed array

C# Error

CS0826 – No best type found for implicitly-typed array

Reason for the Error & Solution

No best type found for implicitly typed array.

Array elements must all be the same type or implicitly convertible to the same type according to the type inference rules used by the compiler. The best type must be one of the types present in the array expression. Elements will not be converted to a new type such as object. For an implicitly typed array, the compiler must infer the array type based on the type of elements assigned to it.

To correct this error

  • Give the array an explicit type.

  • Give all array elements the same type.

  • Provide explicit casts on those elements that might be causing the problem.

Example

The following code generates CS0826 because the array elements are not all the same type, and the compiler’s type inference logic does not find a single best type:

// cs0826.cs  
public class C  
{  
    public static int Main()  
    {  
        var x = new[] { 1, "str" }; // CS0826  
  
        char c = 'c';  
        short s1 = 0;  
        short s2 = -0;  
        short s3 = 1;  
        short s4 = -1;  
  
        var array1 = new[] { s1, s2, s3, s4, c, '1' }; // CS0826  
        return 1;  
    }  
}  

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

This C# program calculates and displays an upper triangular matrix based on user input. Problem Statement: The program takes the...
This C# program serves as a demonstration of bitwise operators, which are fundamental operators used for manipulating individual bits in...
This C# program is designed to interchange or swap the columns of a matrix. A matrix is a two-dimensional array...