C # variable name for string

I have a variable

public string MyVariable; 

I need to use the variable name as a string. Example:

 var a = MyVariable.NameVariable(); // a = "MyVariable" 

How can i do this?

I would like to create your miniORM (NHibernate is too heavy and requires a separate library). At the moment, the problem is that I have to specify a bunch of constants. For instance:

 public const string FieldIdRules = "idRules" 

And then make deals in relation to a self-written profiler. I saw that Hibernate does not need to specify a text value (for field relations). I want to implement the same thing.

Sorry my bad english

+6
source share
2 answers

Hacked approach you can get through Expression :

 string myVariable = string.Empty; Expression<Func<object>> expression = () => myVariable; string name = (expression.Body as MemberExpression).Member.Name; 
+2
source

If you can access a variable by name, you already have its name, so type "MyVariable" .

If you reassign it, it is not possible. The values โ€‹โ€‹do not contain a history of variable names somewhere.


So, to handle field-column mappings, I suggest Dictionary . Reflection is an opportunity, but unnecessarily difficult for such a simple task.

+1
source

All Articles