I have a method that accepts a generic delegate as a parameter, and inserts it in a list:
public void AddFilterMember<T>(Func<T, bool> filterMember)
{
filter.Add(filterMember);
}
Later on all delegates are invoked over an instance of type T to find out if this instance passes the filter, i.e, if true is returned for every filterMember invoked.
I noticed that it is possible to pass an invalid lambda expression like the following:
string str = null;
AddFilterMember(x => str.Contains((string)x));
Which obviously will throw an exception when invoked because the str string is null. So I would like to know the best way to validate a lambda expression against null references (other than its parameters) at the moment it is defined?
I guess one option would be to invoke it using a default instance of T, but sometimes this is not feasible because T may not have a default parameterless constructor.
Thanks in advance!
Here’s a possible solution:
If the caller knows that
default(T)won’t work, but expects all actually-used values to work, they can specify thecheckValueto be an example. From there, you just try to run the delegate and see if it works or not. Aboolis returned to let the caller know whether it was successfully done or not.Note that invoking the delegate can cause side effects. The behavior of this should be documented so callers aren’t surprised.