Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute implicit cast at runtime

So I have a Generic class (it's mostly a container class) with implicit casting, like this:

public class Container<T>  
{  
        public T Value { get; set; }

        public static implicit operator T(Container<T> t)
        {
            return t.Value;
        }

        public static implicit operator Container<T>(T t)
        {
            return new Container<T>() { Value = t };
        }
} 

So in runtime I would like to cast an instance of Container<int> to int using reflection but cannot seem to find a way, I've tried the "Cast" method invoking mentioned in a couple of places but I'm getting an Specified cast is not valid. exception.

Any help will be appreciated.

like image 284
Adriaan Davel Avatar asked Aug 15 '11 13:08

Adriaan Davel


1 Answers

There's almost never a good reason to do this unless the type in question is internal to an assembly that you cannot modify.

But if it came to that, I would personally prefer the much cleaner-looking dynamic solution (as mentioned by jbtule) to reflection.

But since you asked for a solution with reflection (perhaps you are on .NET 3.5 or earlier?), you can do:

object obj = new Container<int>();

var type = obj.GetType();
var conversionMethod = type.GetMethod("op_Implicit", new[] { type });
int value = (int)conversionMethod.Invoke(null, new[] { obj });
like image 133
Ani Avatar answered Oct 13 '22 18:10

Ani