1

Why doesn't any of the following compile:

NameOf(value.GetType())
NameOf(GetType(value))

This expression doesn't have a name.

How can I get the string name of the type of the value that was passed? ToString() might be overloaded, so can't use that.

dotNET
  • 33,414
  • 24
  • 162
  • 251

3 Answers3

4

You can't use NameOf in that case because this new operator gets the name of a member from the member itself.

GetType doesn't return the member but the type metadata of a class, structure, interface or enumeration.

Thus, you'll be able to get the whole type name getting the Type.Name property value: value.GetType().Name

Matías Fidemraizer
  • 63,804
  • 18
  • 124
  • 206
1

You can use value.GetType().Name to get the name of type as a string

Your code doesn't compile because GetType() returns an object of type System.Type, as opposed to an expression, which is required, per documentation.

CoolBots
  • 4,770
  • 2
  • 16
  • 30
  • Thanks. Any clue on why `NameOf` doesn't work here even though its argument is explicitly named `typeOrMember`? – dotNET May 28 '16 at 07:11
  • Per [documentation](https://msdn.microsoft.com/en-us/library/dn986596.aspx), the argument needs to be an expression, not an object. Recommended solution per MSDN is to use [TypeOf](https://msdn.microsoft.com/en-us/library/0ec5kw18.aspx) in conjunction with NameOf. – CoolBots May 28 '16 at 07:19
  • Fast and accurate. Thanks a lot. – dotNET May 28 '16 at 07:25
  • @MatíasFidemraizer: I just went through the entire thing again and think you're right. – dotNET May 28 '16 at 07:44
  • @MatíasFidemraizer I updated my answer to address both questions in the original post (which I thought I did earlier via a comment response...) – CoolBots May 28 '16 at 08:09
  • @CoolBots Now it answers the question! – Matías Fidemraizer May 28 '16 at 08:41
1

VB .Net has a built-in function named TypeName. Instead of getting the object type prior to getting that type name, you can pass an object directly to the TypeName function:

The_Black_Smurf
  • 5,178
  • 14
  • 52
  • 78
  • Great piece of info. No one else suggested this. – dotNET May 28 '16 at 07:26
  • I affraid `TypeName` not usefull in some cases. For example for variable of type Array of Integer returned name will be `"Integer()"` or if variable is `null` then `"Nothing"` will be returned. – Fabio May 28 '16 at 19:35