Home C# get variable name of an object in it's constructor
Reply: 1

C# get variable name of an object in it's constructor

C.Da
1#
C.Da Published in 2017-11-13 07:27:31Z

I'm creating a bunch of string variables, which are to be used to store the value of the variable name itself. e.g

string name = "name";
string number="number;

but as the list gets long, it becomes tedious to repetitively typing everything, so I made a class that just holds string data, and let the constructor to do the dirty work. e.g

class Data
{
public Data()
{
//pseudo code here:
name = NameOfTheVariable(this);
}
public string name {get;set;}    
}

So the ideal output would be something like this:

public static void Main()
{
//Declare an object here, the constructor will automatically assign the 
//variable name to the property.
 Data number = new Data();
 Console.WriteLine(number.name);
}

The output would be: "number", which is the variable name itself.

I did try to use MemberExpression mentioned in this post: get name of a variable or parameter

But the function doesn't take the keyword "this" as an valid argument. so I cannot use the function provided in that post, eg:

class Data
{
public Data()
{
//This line will not work
name= MemberInfoGetting.GetMemberName(() => this);
}
public string name{get;set;}

}

Anybody know how I could solve this problem?

Fildor
2#
Fildor Reply to 2017-11-14 07:56:18Z
Data number = new Data();
Console.WriteLine(number.name);

In C# 6.0 and above that would be:

SomeNumberClass number = new SomeNumberClass();
Console.WriteLine(nameof(number));

The solution for Pre-C# 6 you linked would work accordingly, you just would not write nameof but use a static method instead:

SomeNumberClass number = new SomeNumberClass();
Console.WriteLine(MemberInfoGetting.GetMemberName(() => number));
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.481191 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO