asolvent
asolvent

Reputation: 881

Correct method overloading approach

Is overloaded methods returning different data-types good or bad?

I understand overloading can't be done on return types, what I meant is following

1) T Create(T)

2) List<T> Create(List<T>)

I think it would be counter-intuitive if an overloaded method returns different data-types, would like to have thoughts from others?

I do see such approach being following in .Net framework (Where extension method).

I understand this question might get closed as there wouldn't be any yes/no for this one but I would like to hear how people approach this?

Cheers, Avinash

Upvotes: 1

Views: 51

Answers (1)

Ondrej Janacek
Ondrej Janacek

Reputation: 12616

I would not advise that. Sure, you can do it, but you will never know what's going to be a returned value.

It's somewhat confusing when you see

var value = YourClass.Create(AnotherClass.GetResult());

sure, you could replace var with actual type you expect, or add <Type> after Create to indicate what overload would you like to use.

Personally, I would go for

T Create<T>(T values)
List<T> CreateMany<T>(List<T> values)

It is much clearer and when someone reads your code it is immediately obvious what are you trying to do.

Upvotes: 1

Related Questions