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

2

2 Answers 2

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;
Sign up to request clarification or add additional context in comments.

1 Comment

And it will tell you at compile-time if the name is changed.
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.