Generic class: type-based conditional method

I have an existing generic C # class and want to add or remove a method based on the type used, I explain

public class MyType<T>
{
    public T getValue() { return value; }
}

      

For a specific one, MyType<void>

I want to "remove" the getValue method. Does something like this exist?

+3


source to share


2 answers


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

+4


source


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.

0


source







All Articles