Is it possible to override generics constraints for abstract methods implementation?
Let me explain... normally I would do something like:
public abstract class A
{
public abstract class IData {}
public abstract void DoSomething(IData data);
}
public class B : A
{
public DataB : IData
{
public int ciao;
}
public override void DoSomething(IData data)
{
DataB d = data as DataB;
if (d == null)
{
// print error or whatever...
return;
}
int miao = d.ciao * 2;
// do whatever with miao or d.ciao...
}
}
public class C : A
{
public DataC : IData
{
public float arrivederci;
}
public override void DoSomething(IData data)
{
DataC d = data as DataC;
if (d == null)
{
// print error or whatever...
return;
}
int bau = d.arrivederci * 2f;
// do whatever with bau or d.arrivederci...
}
}
What I don't like is that I can pass to the DoSomething function an invalid parameter type.
I would want to be able to do something like
public class B : A
{
public DataB : IData
{
public int ciao;
}
public override void DoSomething(DataB data)
{
int miao = d.ciao * 2;
// do whatever with miao or d.ciao...
}
}
public class C : A
{
public DataC : IData
{
public float arrivederci;
}
public override void DoSomething(DataC data)
{
int bau = d.arrivederci * 2f;
// do whatever with bau or d.arrivederci...
}
}
which of course is not possible.
For this reason I ended up doing something like:
public abstract class A
{
public abstract class IData {}
public abstract void DoSomething<T>(T data) where T : IData;
}
The next step would be to make something like
public class B : A
{
public DataB : IData
{
public int ciao;
}
public override void DoSomething<T>(T data) where T : DataB
{
int miao = d.ciao * 2;
// do whatever with miao or d.ciao...
}
}
public class C : A
{
public DataC : IData
{
public float arrivederci;
}
public override void DoSomething<T>(T data) where T : DataC
{
int bau = d.arrivederci * 2f;
// do whatever with bau or d.arrivederci...
}
}
So, basically, override the generic constraint I did set in the parent's abstract generic method. Is there a way to achieve this?
Please note: I don't want to create a generic class but only a generic method that is able to get the right type of data per each different implementation of the base class.
DoSomethingwill accept anyIDatainA. You can't go and change your mind inBorCto only accept more derived types, even if constraints where variant in any way (which they're not). Consider carefully what kind of type safety (if any) you're really trying to achieve, here. Typically, this kind of design often means that you're setting up an inheritance hierarchy you actually don't want, but is better done through extension methods, concrete classes or (if really necessary)newmethods and explicit downlevel casts in derived classes.Aclass instead of on theDoSomethingmethodpublic abstract class A()the()is invalid. Can you correct the code to make it valid C#?