I have seen similar questions asked and answered but I’m still struggling with my simple implementation. I want to be able to return a class property with a different return type. I then want to be able to use them all interchangeably in a collection.
public ClassInt
{
public int Id { get; set; }
public string MyValue { get; set; }
}
public ClassString
{
public int Id { get; set; }
public int MyValue { get; set; }
}
So the classes are the same with the exception of the return type on MyValue. This is what I got to so far:
public interface IBaseClass
{
int Id { get; set; }
object Value { get; set; }
}
public abstract class BaseClass <T> : IBaseClass
{
public int Id { get; set; }
public abstract T Value { get; set; }
}
public class ClassInt : BaseClass<int>
{
private int _value;
public override int Value
{
get
{
return _value;
}
set
{
_value = value;
}
}
}
public class ClaseString : BaseClass<string>
{
private string _value;
public override string Value
{
get
{
return String.Format(“Hello: {0}”, _value);
}
set
{
_value = value;
}
}
}
To display the values:
List<IBaseClass> MyObjects = new List<IBaseClass>();
MyObjects.Add(new ClassString() { Id = 1, Name = "value 1", Value = "F1 String 1" });
MyObjects.Add(new ClassInt() { Id = 2, Name = "value 2", Value = 500 });
IBaseClass f0 = MyObjects[0];
IBaseClass f1 = MyObjects[1];
The issue now is that f0 and f1 do not have the Value property exposed.
Any suggestions or comments appreciated.
Thanks