Question

I have a function

public List<Item> Filter(params String[] valuesOrdered)
{
    //...
}

which acts as a filter on all Items.

public class Item
{
    List<String> propertiesOrdered;
    //...
}

So that if I call e.g. Filter("prop1"), then all Items with "prop1" as the first entry their properties will be matched.

If I call Filter(), then all Items should be returned.

I also need to be able to match on null values. So for instance right now I can call Filter(null, null) and all Items with null, null as their first properties will be matched.

All of this works except when I call Filter(null). It will be interpreted the same way as Filter(), but the intention is that the former should return all Items with null as their first property, and the latter should return all Items.

I tried defining an overload to deal with this

public List<Item> Filter(String value)
{
    if(value == null)
        return Filter(new String[] {null});
    else
        return Filter(value);
}

But the compiler just shows an Ambiguous Invocation error when I call Filter(null).

Was it helpful?

Solution

If you drop the overload, then this:

Filter(null);

will be called as this:

string[] valuesOrdered = null;
Filter(valuesOrdered);

and not like this:

Filter(new string[] { null });

So, you can detect this, and if you want it to behave as though you passed an array containing a single null, then this will suffice:

public List<Item> Filter(params String[] valuesOrdered)
{
    valuesOrdered = valuesOrdered ?? new string[] { null };

    //...
}

Note that this:

Filter();

will in fact be called as this:

Filter(new string[0]);

so there is a difference between the two that you can detect.

Here's a simple LINQPad program that demonstrates:

void Main()
{
    Filter();
    Filter(new[] { "a" });
    Filter("a");
    Filter(null);
}

public static void Filter(params string[] values)
{
    values.Dump();
}

output:

LINQPad output

OTHER TIPS

You can use the syntax

Filter((String)null)

to call the method in its "expanded" form with a length-one array.

If that syntax is unpleasant to you, you might want to define a constant

const String NullStr = null;

and use

Filter(NullStr)

instead.

PS! Personally I prefer string over String but I stuck to your convention here since it was not relevant to your question.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top