Home > Mobile >  Explicitly convert S[] to ILIst<T> in C#
Explicitly convert S[] to ILIst<T> in C#

Time:10-20

The C# 6 Language Specification (ECMA-334 6th ed.) section 6.2.3 states:

If there is an explicit reference conversion from S to T then there is an explicit reference conversion from S[ ] to IList<T> and its base interfaces...

However, the following doesn't compile for C# 10.x in VS 2022 (17.3.6) for .NET 6.0:

private const int LENGTH = 4;

public class Source { }
public class Target { public static explicit operator Target(Source _) => new Target(); }


static void Main()
{
    _ = (Target)new Source();               // Ok

    _ = (IList<Target>)new Source[LENGTH];  // Error, can't convert Source[] to IList<Target>
}

The compiler emits:

error CS0030: Cannot convert type 'stack_overflow.Program.Source[]' to 'System.Collections.Generic.IList<stack_overflow.Program.Target>'

CodePudding user response:

The conversion operator is a user-defined conversion, not a reference conversion.

CodePudding user response:

That's because what you have is an explicit user-defined conversion operator. A user-defined explicit conversion from a type S to a type T exists if a user-defined explicit conversion exists from a variable of type S to T.

For more info about user-defined explicit conversion, check here (§10.5.5).

Reference conversions on the other hand are conversions between reference types that require run-time checks to ensure that they are correct. Reference conversions are described here (§10.3.5).

  • Related