Simcha Khabinsky
Simcha Khabinsky

Reputation: 2039

Optional Function Parameter

In C# I have the following function definition:

public static TResult SomeParentFunctionName<TSource, TResult>(
    TSource SomeValue,
    Func<TSource, TResult> ChildFunction1,
    Func<TSource, TResult> ChildFunction2)

This function takes SomeValue and then calls ChildFunction1 and ChildFunction2

According to my business rules, I always need to run ChildFunction1, but only sometimes need to run ChildFunction2.

Can I make ChildFunction2 an optional parameter? How do I go about doing that? And how do I know if it has been passed in.

Options I have considered:

  1. I could create two SomeParentFunctionName functions, one with ChildFunction2 and one without.

  2. I could pass in a blank function that just won't do anything - but that's not good practice.

Upvotes: 8

Views: 13207

Answers (3)

Pat Hensel
Pat Hensel

Reputation: 1354

There is a 3rd option. Use the params keyword to indicate that the function takes a variable number of arguments. But, then you need to handle the case where no Func<TSource, TResult> objects are passed.

If your always going to need either 1 or 2 Func<TSource, TResult> objects, then overloading the function as you suggest in option 1 is the most common way to handle the situation.

Upvotes: 2

D Stanley
D Stanley

Reputation: 152566

Can I make ChildFunction2 an optional parameter?

Sure, just give a default value of null:

public static TResult SomeParentFunctionName<TSource, TResult>(
       TSource SomeValue,
       Func<TSource, TResult> ChildFunction1,
       Func<TSource, TResult> ChildFunction2 = null)

then just check for null:

{
    TResult res = ChildFunction1(source);

    if(ChildFunction2 != null)
        TResult res2 = ChildFunction1(source2);

}

Upvotes: 1

Neil Smith
Neil Smith

Reputation: 2565

Sure, just set it to null:

public static TResult SomeParentFunctionName<TSource, TResult>(
    TSource SomeValue,
    Func<TSource, TResult> ChildFunction1, 
    Func<TSource, TResult> ChildFunction2 = null)
{
    ...
    if (ChildFunction2 != null)
        ChildFunction2();
}

If you want to pass in a func for ChildFunction2, go ahead and do it. If you don't want to pass anything for it just omit it when calling the function.

This is actually exactly what you were calling it - optional argument

Upvotes: 13

Related Questions