Click here to Skip to main content
15,922,584 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How would you code an alternative to NameOf using Reflection. I am using VS 2010 and NameOf is not available. I need to get the names of any Members of any Type in the hierarchy of the Structure.

VB
Structure Market
    Public Vehicle As Vehicle
    Public Place As String
End Structure

Structure Vehicle
    Public [Color] As Color
   
End Structure

Usage:
Dim Market As String = NameOf(GetType(Market)) ' "Market"
Dim Vehicle As String = NameOf(GetType(New Market().Vehicle)) '"Vehicle" or "Market.Vehicle"
Dim Place As String = NameOf(GetType(New Market().Place)) '"Place" or "Market.Place"


What I have tried:

VB
Function NameOf(Of T)(ByVal expression As T) As String

End Function
Posted
Updated 3-Aug-18 16:31pm
v2
Comments
[no name] 3-Aug-18 17:08pm    
Most probably you will find nothing...Nameof Operator: A New Feature of C# 6.0[^]
j snooze 3-Aug-18 17:27pm    
does GetType(???).FullName not work for you?
[no name] 3-Aug-18 18:07pm    
Yes, but I also need the variable name not just the name of it's underlying type.

1 solution

Reflection won't work because, in your example, every call to GetType is going to return System.String, or whatever the type of the variable is. You're not going to find your variable name on any instance of the Type class.

It can be done using an Expression Tree, but this its expensive to execute. Use this code in any case where you have to execute it thousands of times a second and you're going to notice quite the performance hit.
C#
class Program
{
    static void Main(string[] args)
    {
        string Market = string.Empty;

        Console.WriteLine(Ext.GetNameOf(() => Market));
    }

}

public static class Ext
{
    public static string GetNameOf<T>(Expression<Func<T>> expression)
    {
        var body = (MemberExpression)expression.Body;

        return body.Member.Name;
    }
}
 
Share this answer
 
Comments
[no name] 4-Aug-18 8:15am    
This is an overload for parameters of Type
Dim market2 As Market 'structure
Dim structName$ = GetNameOf(Of Market)() 'returns 
MarketPublic 
Function GetNameOf(Of T)() As String             
    Return GetType(T).Name    
End Function

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900