In C++ templates, one can specify that a certain type parameter is a default. I.e. unless explicitly specified, it will use type T.
Can this be done or approximated in C#?
I'm looking for something like:
public class MyTemplate<T1, T2=string> {}
So that an instance of the type that doesn't explicitly specify T2
:
MyTemplate<int> t = new MyTemplate<int>();
Would be essentially:
MyTemplate<int, string> t = new MyTemplate<int, string>();
Ultimately I am looking at a case wherein there is a template that is fairly widely used, but I am considering expanding with an additional type parameter. I could subclass, I guess, but I was curious if there were other options in this vein.
Yes. :-) But not in a way you would expect. Unfortunately, C doesn't allow you to overload methods so you'd end up with two different functions. Still, by calling f2, you'd actually be calling f1 with a default value.
We can provide a default value to a particular argument in the middle of an argument list.
By default, C uses call by value to pass arguments. In general, it means the code within a function cannot alter the arguments used to call the function.
No. There is no option for default types on generic types in C#.
Subclassing is the best option.
I would subclass your main generic class:
class BaseGeneric<T,U>
with a specific class
class MyGeneric<T> : BaseGeneric<T, string>
This makes it easy to keep your logic in one place (the base class), but also easy to provide both usage options. Depending on the class, there is probably very little extra work needed to make this happen.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With