Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implicit array casting in C#

I have the following classes with an implicit cast operator defined:

class A
{
    ...
}
class B
{
    private A m_a;

    public B(A a)
    {
        this.m_a = a;
    }

    public static implicit operator B(A a)
    {
        return new B(a);
    }
}

Now, I can implicitly cast A to B.

But why can't I implicitly cast A[] to B[] ?

static void Main(string[] args)
{
    // compiles
    A a = new A();
    B b = a;

    // doesn't compile
    A[] arrA = new A[] {new A(), new A()};
    B[] arrB = arrA;
}

Thanks, Malki.

like image 672
Malki Avatar asked Jun 15 '10 18:06

Malki


People also ask

What is implicit casting in C?

Implicit type casting means conversion of data types without losing its original meaning. This type of typecasting is essential when you want to change data types without changing the significance of the values stored inside the variable.

What is implicit type casting explain with example?

In implicit typecasting, the conversion involves a smaller data type to the larger type size. For example, the byte datatype implicitly typecast into short, char, int, long, float, and double. The process of converting the lower data type to that of a higher data type is referred to as Widening.

What are the two types of casting in C?

The two types of type casting in C are: Implicit Typecasting. Explicit Typecasting.

Is casting done implicitly by compiler?

The explicit type conversion is also called type casting in other languages. It is done by the programmer, unlike implicit type conversion which is done by the compiler. The explicit type conversion is possible because of the cast operator and it temporarily converts the variable's datatype into a different datatype.


2 Answers

As Mehrdad Afshari mentioned, you're out of luck doing this implicitly. You'll have to get explicit, and it'll involve an array copy. Thankfully, you can probably do it with a one-liner:

arrB = arrA.Cast<B>().ToArray();

Although if you only want to iterate arrB in a foreach statement, you can avoid the copy by omitting ToArray()

like image 166
Randolpho Avatar answered Oct 08 '22 04:10

Randolpho


Array covariance only works for reference types and in the inheritance hierarchy (note that it's not a representation-changing conversion: just a set of pointers with identical size interpreted differently.) It will not work for value types and user defined conversions.

like image 27
mmx Avatar answered Oct 08 '22 06:10

mmx