Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What about optional generic type parameters in C# 5.0? [closed]

Tags:

c#

generics

Just a thought.

Wouldn't it be useful to have optional type parameters in C#?

This would make life simpler. I'm tired of having multiple classes with the same name, but different type parameters. Also VS doesn't support this very vell (file names) :-)

This would for example eliminate the need for a non-generic IEnumerable:

interface IEnumerable<out T=object>{
  IEnumerator<T> GetEnumerator()
}

What do you think?

like image 202
Lars Corneliussen Avatar asked Mar 29 '10 22:03

Lars Corneliussen


2 Answers

I am definitely for it.

I'm currently writing helper methods for different scenarios where I want to pass references to different members and methods of classes. To accomplish this I'm taking, for example, an Expression<Func<TIn, TOut>> as argument to the helper (that lets me reach the method with a lambda expression, thus keeping everything strongly typed).

BUT - I currently need to define a new helper method for each different number of input arguments, since I need to have a different amount of generic arguments to it. Instead of

HelperMethod<TIn>(Expression<Action<TIn>> arg) // Yes, C# can distinguish
HelperMethod<TOut>(Expression<Func<TOut>> arg) // these two from eachother
HelperMethod<TIn, TOut>(Expression<Func<TIn, TOut>> arg)
HelperMethod<TIn1, TIn2, TOut>(Expression<Func<TIn1, TIn2, TOut>> arg)
// etc

I could make do with, at the most, two methods:

HelperMethod<TIn>(Expression<Action<TIn>> arg)
HelperMethod<TOut, TIn1 = DummyType, ...>(Expression<Func<TIn1, ..., TOut> arg)

In my case, it would avoid a lot of code duplication...

like image 108
Tomas Aschan Avatar answered Oct 13 '22 22:10

Tomas Aschan


What would be the main use for this language feature? I can see that it could help with some administrative tasks like file names and less typing and such but beyond that I don't see how useful this would be.

Also, this feature would significantly complicate any generic constraints that could be placed on the generic type parameter and the default type itself would have to function as a sort of generic constraint itself.

I think this would complicate the language without offering any real benefit to the developer.

like image 37
Andrew Hare Avatar answered Oct 13 '22 22:10

Andrew Hare