Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic class: conditional method based on type

Tags:

c#

generics

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?

like image 307
CDZ Avatar asked Dec 05 '25 10:12

CDZ


1 Answers

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

like image 150
Rune FS Avatar answered Dec 08 '25 00:12

Rune FS



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!