I wrote an extension to create a string-representation by an object:
public static string ToString<T>(this T @this, Func<T, string> predicate) where T: class
{
return predicate(@this);
}
So I can do something like
return handler.GetUserById(id)?.ToString(x => $"{x.LastName}, {x.FirstName}");
which gives me either null if the user is null or otherwise e.g. "Miller, Peter"
My question: is this a good extension? Makes it sense? Anything I didn't consider?
And what about the null-thing? Should I check the null value in the extension? Imho, the thrown NullReferenceException
is okay, if s.o. calls this with a null object.
Func<T, string>
is not called a predicate. \$\endgroup\$ – Denis Oct 7 '19 at 10:18A NullReferenceException exception is thrown by a method that is passed null. Some methods validate the arguments that are passed to them. If they do and one of the arguments is null, the method throws an System.ArgumentNullException exception.
imo, throwing anArgumentNullException
is correct when I validate the argument. isn't it? \$\endgroup\$ – Matthias Burger Oct 8 '19 at 7:09