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

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

user1347
1#
user1347 Published in May 24, 2018, 4:01 pm

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?

You need to login account before you can post.

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

© 2016 Powered by mzan.com design MATCHINFO