Question

Could someone explain why a casted to object fails to use an implicit conversion operator? The implicit cast operator seems to be used before it's boxed but once it's boxed it fails.

class Program
{
    static void Main(string[] args)
    {
        var ms = new MemoryStream();
        var wrapper = new GenericWrapper<MemoryStream> { Item = ms };

        object obj = wrapper; 
        object objMs = ms;

        MemoryStream passingImplicitCast = (MemoryStream)wrapper;

        MemoryStream passingCast = (MemoryStream)objMs;
        MemoryStream failingCast = (MemoryStream)obj; //Throws Unable to cast object 
    }
}

class GenericWrapper<T>
{
    public T Item { get; set; }

    public static implicit operator T(GenericWrapper<T> value)
    {
        return value.Item;
    }
}

No correct solution

OTHER TIPS

You can't surpass type-casting obj to GenericWrapper<MemoryStream>, because :

  1. object doesn't know how to convert it self to MemoryStream
  2. obj is originally a GenericWrapper<MemoryStream>

your only option is to cast obj to GenericWrapper<MemoryStream> :

MemoryStream failingCast = (MemoryStream)(GenericWrapper<MemoryStream>)obj;

and having it type-casted to GenericWrapper<MemoryStream>, it now know how to convert it self implicitly to type MemoryStream because GenericWrapper<MemoryStream> has implicit operator definition.

Well, test with this line:

MemoryStream failingCast = (GenericWrapper<MemoryStream>)obj;

In the end, "failingCast" is a System.IO.MemoryStream.

enter image description here

Since obj is a object you need to be more specific, and set GenericWrapper<MemoryStream>. you need to return the value T:

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top