# String Format object extension

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.

• Sure, looks like fun, however make sure you check for null on @this – Walter Vehoeven Oct 7 '19 at 9:37
• @PPann I saw, in my library i mostly check for null and throw ArgumentNullException if it's null - so I will add this here too :) – Matthias Burger Oct 7 '19 at 10:03
• Just so you know, Func<T, string> is not called a predicate. – Denis Oct 7 '19 at 10:18
• worth reading about null reference exception vs argument null exception: docs.microsoft.com/en-us/dotnet/api/… – dfhwze Oct 7 '19 at 19:13
• @dfhwze thanks for the article, I read it but still didn't get the point.. what should I throw? 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 an ArgumentNullException is correct when I validate the argument. isn't it? – Matthias Burger Oct 8 '19 at 7:09

1. It's a good extension if you can see it useful in more than one place.
2. It makes sense.
3. I can't see anything else to consider - a null check on the predicate maybe?
4. If the exception thrown by the predicate when @this is null 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.

• thx! yeah the restriction is unneccessary.. could also call it on a struct. – Matthias Burger Oct 7 '19 at 10:02