How to get the lowercase name of an object, even when null, in C# [duplicate]

Jeff is correct. That’s like asking what kind of cake would have been in an empty box with no label.

As an alternative to Fortran’s answer you could also do:

string TypeNameLower<T>(T obj) {
   return typeof(T).Name.ToLower(CultureInfo.InvariantCulture);
}

string TypeNameLower(object obj) {
   if (obj != null) { return obj.GetType().Name.ToLower(CultureInfo.InvariantCulture); }
   else { return null; }
}

string s = null;
TypeNameLower(s); // goes to the generic version

That way, C# will pick the generic one at compile time if it knows enough about the type you’re passing in.

Leave a Comment