I have a class:
public class ClassA<T>
{
public T Value {get; set;}
public string Description {get; set;}
}
ClassA can have a value of any type, however: I need to be able to set other properties of anything that is ClassA regardless of the type value. So I have a method:
public void DoWork(ClassA<object> source, ClassA<object> destination)
{
destination.Description = source.Description;
}
However when I try to do this I get a runtime error saying that:
cannot convert from ClassA<DateTime> to ClassA<object>
I thought that anything could be passed as an object… I’ve looked all over the web for something similar, maybe I’m just not getting the keywords right.
Anyone have any suggestions?
Thanks
You won’t be able to do that.
If you could pass a
ClassA<int>into a method accepting aClassA<object> wrapperthen that method would be able to callwrapper.Value = "not an integer";. What should happen then? You’ve just set a string to an object that can only hold integers. Since the compiler knows it can’t enforce what you could put it, it just doesn’t let you pass the object in the first place.As for the actual solution, two come to mind.
You could make your method generic, if that’s an option:
Or you could make a covariant interface:
For your
DoWorkmethod you don’t even actually use theValue, so you could make the interface non-generic, non-covariant, and just removeValue. The advantage here is that you could use that interface to access the value properties of any number ofClassAobjects that have a common base type.