Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default value on generic predicate as argument

First time question for me :)

I need some way to define a default predicate using a generic on the format

Func<T, bool>

and then use this as a default argument. Something like this:

public bool Broadcast(byte command, MemoryStream data, bool async, Func<T, bool> predicate = (T t) => true)

When i do this i get the compile error:

Default parameter value for 'predicate' must be a compile-time constant

Is there a smooth way of doing this that I am missing or should a make the predicate function nullable and change my function logic accordingly?

Thanks,

like image 430
Bakery Avatar asked Jan 26 '11 12:01

Bakery


People also ask

What is the value of a default argument?

A default argument is a value provided in a function declaration that is automatically assigned by the compiler if the calling function doesn't provide a value for the argument. In case any value is passed, the default value is overridden.

Can a function argument have default value?

Any number of arguments in a function can have a default value.

Which is the default argument?

In computer programming, a default argument is an argument to a function that a programmer is not required to specify. In most programming languages, functions may take one or more arguments. Usually, each argument must be specified in full (this is the case in the C programming language).


3 Answers

Make an overload for Broadcast which does not take the last argument.

like image 24
tenfour Avatar answered Oct 06 '22 08:10

tenfour


Default values for method parameters have to be compile-time constants, as the default values are actually copied to all the call sites of the method by the compiler.

You have to use an overload to do this:

public bool Broadcast(byte command, MemoryStream data, bool async) {
    return Broadcast(command, data, async, t => true);
}

public bool Broadcast(byte command, MemoryStream data, bool async, Func<T, bool> predicate) {
    // ...
}

Also, there is a specific Predicate<T> delegate in mscorlib which you can use instead. It's the same signature as Func<T, bool>, but it explicitly marks it as a delegate which decides whether an action is performed on instances of T

like image 82
thecoop Avatar answered Oct 06 '22 09:10

thecoop


Try this:

public bool Broadcast(byte command, MemoryStream data, bool async, Func<T, bool> predicate = default(Func<T, bool>))

But I think you have to check for predicate!=null.

like image 3
Amir Rezaei Avatar answered Oct 06 '22 08:10

Amir Rezaei