SquareJAO
SquareJAO

Reputation: 87

How to hint to C# that an implicit conversion exists?

I have a sequence of classes and interfaces as follows:

interface IA
{ }

class A : IA
{
    public static implicit operator A(int v) => new A(v);

    public A(int v)
    { ... }
}

class B
{
    public static void Foo(IA a)
    { ... }
}

And I want to be able to call B.Foo(int).

B.Foo(1) does not compile, but B.Foo((A)1) does. I am able to call B.Foo(1) if the method signature is instead Foo(A a), as C# is able to figure out the chain of implicit casting, so I know that I can modify the code in the following way:

class B
{
    public static void Foo(A a) => Foo((IA)a)
    public static void Foo(IA a)
    { ... }
}

However, this seems like a waste of code and time as I would have to do this for every method which accepts IA. It would become even more inefficient if a method such as Bar(IA p1, IA p2, ...) exists, as I would need n! copies of the signature with all of the different permutations of A and IA.

What is the best way to hint to C# that any method which accepts IA can also accept int?

Upvotes: 0

Views: 76

Answers (1)

Sweeper
Sweeper

Reputation: 271625

For a call like B.Foo(1), the compiler would have to search through every type that implements IA to find a type T such that there is an implicit conversion from int to T and then perform the following conversion,

int -> T -> IA

The "finding T" step could be a lot of work, so the compiler is designed to not do it.

You seem to want to find a way to tell it that there is one specific implementation of IA, namely A, that does have have an implicit conversion from int. Well, you have actually already said it in the question:

B.Foo((A)1)

This tells the compiler to convert the int to an A first. Notice how this is as if you have found the type T, doing the hard work for the compiler.

Upvotes: 1

Related Questions