Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a reasonable approach to "default" type parameters in C# Generics?

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.

like image 366
el2iot2 Avatar asked Apr 01 '09 23:04

el2iot2


People also ask

Does C allow default parameters?

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.

Where should be the default value of parameter be specified?

We can provide a default value to a particular argument in the middle of an argument list.

What type are C functions by default?

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.

What is the default generic type in C#?

No. There is no option for default types on generic types in C#.


1 Answers

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.

like image 78
Reed Copsey Avatar answered Sep 30 '22 14:09

Reed Copsey