Learner
Learner

Reputation: 4751

What alternative approach could be used in C# to avoid method returning `object` type?

I know that the method is returning List<string> at the moment. But in some (which occur quite frequently in our application) scenarios, it returns List having only one string.

So eventually it would return either string or List<string>.

Since it's unpredictable what it'll return at run time, at present it's return type is kept as object.

What alternative approach could be used to avoid method returning object?

EDIT: I would like to have answer to the question What alternative approach could be used to avoid method returning object? ; without considering the scenario I described. List is enough here.

Upvotes: 3

Views: 346

Answers (5)

bottlenecked
bottlenecked

Reputation: 2157

Hmm, does this method perhaps call 2 different methods inside its body, one returning a string and one returning a List<string>? If so, maybe you could change your method to return an IEnumerable<string>, and change the return GetSingleString(); statement to yield returnGetSingleString();

Or you could add it to a list with a single element and return the list, like some of the other answers suggest here

Upvotes: 0

Incognito
Incognito

Reputation: 16577

There is no problem to have a List with one and more and even with no string(empty list). Why you want to have string when there is only one element in the List. Just keep the API more clear.

Upvotes: 2

FIre Panda
FIre Panda

Reputation: 6637

I dont see the the problem of returning List<string> even the List contain only one element. But if you really want your method to behave differently with one string value, you could do

public List<string> GetStrList(out string val)
{
//set str = string.Empty; when value is more than one

//set str = whateverstring when value is only one
} 

Upvotes: 1

Marc Gravell
Marc Gravell

Reputation: 1062770

why return a string? a List<string> with a single string in it is perfectly well defined... use that! An ambiguous API is silly here.

Another option might be IEnumerable<string>, but... meh, just return the list with a single string!

Upvotes: 5

Tim
Tim

Reputation: 5421

Return a List that contains one or more string elements, and process the list as a list regardless of the number of elements it contains.

Upvotes: 3

Related Questions