7

I have variable

public string MyVariable;

I need use name of variable as string. Example:

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

How i may to 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 point out a bunch of constants. For example:

public const string FieldIdRules = "idRules"

And then to make transactions in relation samonapisannom profiler. I saw that Hibernate does not need to specify the text value (for the ratio of fields). I want to implement the same.

Sorry my bad english

user2071747
  • 201
  • 1
  • 3
  • 8
  • 1
    This Stack Overflow answer might help you: http://stackoverflow.com/questions/2566101/how-to-get-variable-name-using-reflection – Aaron Blenkush Feb 27 '13 at 04:06
  • http://stackoverflow.com/questions/2566101/how-to-get-variable-name-using-reflection thanks Aaron Blenkush8 – user2071747 Feb 27 '13 at 04:16

2 Answers2

2

Hacky approach, you can get via Expression:

string myVariable = string.Empty;
Expression<Func<object>> expression = () => myVariable;

string name = (expression.Body as MemberExpression).Member.Name;
cuongle
  • 74,024
  • 28
  • 151
  • 206
1

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

If you’ve reassigned it, this is not possible. Values don’t keep a history of variable names somewhere.


So in order to handle field to column mappings, I would suggest a Dictionary. Reflection is a possibility, but is needlessly complicated for a simple task like that.

Ry-
  • 218,210
  • 55
  • 464
  • 476