I have the following 2 classes:
public class Parent
{
public static Parent operator +(Parent l, Parent r)
{
return new Parent(); //do something meaningful
}
}
public class Child: Parent
{
public static Child operator +(Child l, Parent r)
{
return new Child(); //do something meaningful, child related
}
}
Then I have a wrapper class that uses implicit conversion to return the wrapped value:
public class Wrapper<T>
{
private T value;
public T Value => value;
public static implicit operator T(Wrapper<T> wrapper)
{
return wrapper.value;
}
}
Then I am combining the 2 as follows:
public class Usage
{
private Parent someField;
private Wrapper<Child> wrappedValue;
public void UseOperatorWithImplicitConversion()
{
//Child sum1 = wrappedValue + someField; //<-- compilation error
Parent sum2 = wrappedValue + someField;
Child temp = wrappedValue; //works but defeats the purpose of reduced verbosity
Child sum3 = temp + someField;
}
}
I was expecting the sum1 line to work. I had a look in the generated IL and it seems that the types are there:
IL_0001: ldarg.0 // this
IL_0002: ldfld class Example.Wrapper`1<class Example.Child> Example.Usage::wrappedValue
IL_0007: call !0/*class Example.Child*/ class Example.Wrapper`1<class Example.Child>::op_Implicit(class Example.Wrapper`1<!0/*class Example.Child*/>)
IL_000c: ldarg.0 // this
IL_000d: ldfld class Example.Parent Example.Usage::someField
IL_0012: call class Example.Parent Example.Parent::op_Addition(class Example.Parent, class Example.Parent)
IL_0017: stloc.0 // sum2
Though the IL_0012 is a call to op_Addition of the Parent and not the Child.
Is there something that I'm missing here?
I am using .NET Framework 4.6.1 C# 7.2