CDZ
CDZ

Reputation: 853

Generic class: conditional method based on type

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

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

For the specific MyType<void>, I wish to "delete" the "getValue" method. Does something like this exists?

Upvotes: 3

Views: 1650

Answers (2)

MakePeaceGreatAgain
MakePeaceGreatAgain

Reputation: 37123

The purpose of using generics is to have a generic type-declaration that works for all types, not just a few ones.

I suppose you want an operation only for numbers. You could add a generic constraint on your class as follows:

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

However this will also allow types which have the generic argument void to have the GetValue-method, as void is also a struct. However this won´t hurt as you can´t construct a type MyType<void> as Lee also mentioned.

Furthermore there´s no common interface that all numeric types implement and that can be used as generic constraint. The only workaround is to have a method for every type, so GetDouble, GetInt, and so on

Upvotes: 0

Rune FS
Rune FS

Reputation: 21752

Nope but you can probably accomplish 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'd then need to declare the variables as IMyType and only use MyType<T> when you know that it is of that type

Upvotes: 4

Related Questions