I have a class such as:
public MyClass
{
public myEnumType Status {get;set;}
public DataTable Result{get;set;}
}
Because DataTables suck I want to implement an object orientated approach. However I have existing code such as:
public interface IData
{
MyClass AddData(int i);
MyClass GetData(string Tablename);
}
I would like to use this interface but instead of returning a DataTable I want to return an object of some sort eg/Person class.
I did think of creating a new class that inherited MyClass like so:
public MyInheritedClass<T> : MyClass
{
public new T Result{get;set;}
}
However whenever you get data from a class that implements the interface you will have to cast the result of the methods from MyClass to MyInheritedClass. So I was wondering if there was a way of using the existing MyClass to put a constructor in that passes a generic type so I end up with something like
public MyClass
{
public MyClass(T MyObjectOrientatedClass)
{
MyOOClass = MyObjectOrientatedClass;
}
public myEnumType Status {get;set;}
public DataTable Result{get;set;}
public T MyOOClass {get;set;}
}
In C#, the types of expressions are determined by the types of their constituent pieces at compile time. This means something like your last example (where the type of the property is unknowable just by knowing the type of the class) can’t work.
Imagine if that class definition compiled. Then you have this problem:
Sure you could use
object, but then you wouldn’t know anything about the property value, so you’d have to cast before you could do anything with it anyway.Addressing your original issue, it is possible (with a few rough edges) to extend your existing types in a compatible fashion by deriving a new generic interface from your existing
IDatainterface: