Generic class: type-based conditional method
No, but you can probably achieve something similar with interfaces
interface IMyType
{
//...what ever method/properties are shared for all
}
public class MyType<T> : IMyType
{
public T getValue() { return value; }
//...shared methods
}
public class MyTypeOtherSide : IMyType
{
//...shared methods
}
you would need to declare the variables as IMyType and MyType<T>
only use it when you know it is of that type
source to share
The goal of using generics is to have a common type declaration that works for all types, not just a few.
I am assuming you want a numbers-only operation. You can add a generic constraint for your class like this:
public class MyType<T> where T: struct
{
public T getValue() { return value; }
}
However, this will also allow types that share a common argument void
to have a method GetValue
, since they are void
also struct
. It doesn't hurt, however, since you can't build the type MyType<void>
that Lee also mentioned.
In addition, there is no common interface that is implemented by all numeric types and that can be used as a general constraint. The only workaround is a method for each type, so GetDouble, GetInt, etc.
source to share