I'm looking for a way to treat ALL .Net datatypes consistently so I can create the pattern below where any type implementing IGetValue<out T>
will cast to IGetValue<object>
. For some reason, if T is a struct
, it doesn't work and I don't understand why. Is there a way I can implement the following pattern??
public interface IGetValue<out T>
{
T Value
{
get;
}
}
public class GetValue<T> : IGetValue<T>
{
public GetValue(T value)
{
_value = value;
}
private T _value;
public T Value
{
get { return _value; }
}
}
class Program
{
static void Main(string[] args)
{
IGetValue<string> GetString = new GetValue<string>("Hello");
IGetValue<int> GetInt = new GetValue<int>(21);
//This works!!!
if (GetString is IGetValue<object>)
{
Console.WriteLine("GetValue<string> is an IGetValue<object>");
}
else
{
Console.WriteLine("GetValue<string> is not an IGetValue<object>");
}
//This doesn't work!!! Why????
if (GetInt is IGetValue<object>)
{
Console.WriteLine("GetValue<int> is an IGetValue<object>");
}
else
{
Console.WriteLine("GetValue<int> is not an IGetValue<object>");
}
Console.ReadKey();
}
}
Edit:
I realize what I'm trying to accomplish here seems vague, but this is part of a larger design whose explanation would be too verbose. What I need is to have all of my IGetValue<T>
s to share a common type or interface with a property named "Value" that returns an object
. Why is the verbose part.