CuriousDeveloper
CuriousDeveloper

Reputation: 899

Take single or IEnumerable parameter without an overload

Consider the following two overloaded functions. The first one just wraps the single value into a list and passes to the one that takes in multiple values.

I feel like the overloaded single function isn't needed. Is there an easy yet not too hacky method for having just 1 function that can handle a single or an enumerable ?

    public static void Insert<T>(EntityType entityType, long entityId, string shortName, T value, string owner = null, OptionSearch optionSearch = OptionSearch.Name)
    {
        Insert(entityType, entityId, shortName, new List<T> {value}, owner, optionSearch);
    }

    public static void Insert<T>(EntityType entityType, long entityId, string shortName, IEnumerable<T> values, string owner = null, OptionSearch optionSearch = OptionSearch.Name)
    {
        // Do all the stuff and things using a list of values.
    }

Normally I wouldn't care about the overload but with all these parameters (and making them one input object isn't an option) it just makes it seem unneeded.

PS: Related Passing a single item as IEnumerable<T> but that only discusses ways of doing the overload not so much how to get rid of it

Upvotes: 3

Views: 1419

Answers (2)

Optimistic Peach
Optimistic Peach

Reputation: 4298

Sure, just use the one method that takes the IEnumerable as the input, and require the user to cast their single argument to an array like this:

////Bool for example

Insert<bool>(... new bool[] { singleBool }, ...)

And modify the method to:

public static void Insert<T>(EntityType entityType, long entityId, string shortName, IEnumerable<T> values, string owner = null, OptionSearch optionSearch = OptionSearch.Name)
{
    Insert(entityType, entityId, shortName, new List<T> {value}, owner, optionSearch);
}

Although, I just noticed, that the method refers to itself... Make sure it does what you want it to do.

Upvotes: 1

Fredy Treboux
Fredy Treboux

Reputation: 3331

There's no way to avoid the overload other than the proposed on the comments, that is: You could get the values parameter to be the last one, change it to an array, and use the params keyword:

public static void Insert<T>(... other parameters... , params T[] values)

Then you will be able to call the method with an array, with a single T parameter, or with multiple comma-separated T parameters. However, you won't be able to use just any IEnumerable<T>.

I really think that having the overload is the best way to do this at the moment. To track the proposal of including IEnumerable<T> params parameters into C# you can use the following link: https://github.com/dotnet/csharplang/issues/179

Upvotes: 4

Related Questions