C# compiler and implicit keyword: can be better

Imagine the following code:


class A

{

    public static implicit operator B(A a)

    {

        return new B(a);

    }

}

class B

{

    public B(A a)

    {

    }

}


This code compile without error and it’s normal.


Now imagine the following one:


class A

{

    public static implicit operator B(A a)

    {

        return new A();

    }

}


The compiler generates no error with this code but it should!


Less annoying, the compiler generates an error with this code (Cannot implicitly convert type ‘A’ to ‘C’) even though it would be able to use B to convert A to C:


class Program

{

    static void Main(string[] args)

    {

        C c = new A();

    }

}

 

class A

{

    public static implicit operator B(A a)

    {

        return new B(a);

    }

}

class B

{

    public B(A a)

    {

    }

 

    public static implicit operator C(B b)

    {

        return new C(b);

    }

}

 

class C

{

    public C(B b)

    {

    }

}

This entry was posted in 7671, 7672, 7806. Bookmark the permalink.

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>