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.
1 Answer 1
There are not much to review, so to answer your questions:
- It's a good extension if you can see it useful in more than one place.
- It makes sense.
- I can't see anything else to consider - a
null
check on thepredicate
maybe? - If the exception thrown by the predicate when
@this
isnull
is good enough for you, don't bother further.
I don't see why the restriction where T: class
is necessary
If you always want to generate a string containing a list of properties (or another predefined format), you could change the signature to:
public static string ToString<T>(this T @this, params Func<T, object>[] getters)
{
return string.Join(", ", getters.Select(g => g(@this)));
}
called as:
handler.GetUserById(id)?.ToString(p => p.LastName, p => p.FirstName)
so that you don't have to format the input when calling the extension.
-
1\$\begingroup\$ thx! yeah the restriction is unneccessary.. could also call it on a struct. \$\endgroup\$Matthias Burger– Matthias Burger2019年10月07日 10:02:30 +00:00Commented Oct 7, 2019 at 10:02
Explore related questions
See similar questions with these tags.
Func<T, string>
is not called a predicate. \$\endgroup\$A 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\$