bot_insane
bot_insane

Reputation: 2604

How to get variable name of object inside class?

I have class A which stores ref to object B in BObject variable.

public class A
{
    public B BObject;
}

I want to get BObject ( name of variable ) in B class constructor.

Is there any way to do this ?

Purpose of doing it: I want to create ODBCFramework and I want to get Table Name based on Variable Name. ( Like in EntityFramework Context )

Update: I want to handle it in C#5.

Upvotes: 1

Views: 3315

Answers (4)

bot_insane
bot_insane

Reputation: 2604

@Damien_The_Unbeliever give me some points to solve my problem. And I tried this, and it works.

public class A
{
    public B BObject { get; set; }
    public A()
    {
        var BTypeProperties = this.GetType().GetProperties().Where(x => x.PropertyType == typeof(B));
        foreach (var prop in BTypeProperties)
        {
            prop.SetValue(this, new B(prop.Name));
        }
    }

}

public class B
{
    string _propName;
    public B(string propertyName)
    {
        _propName = propertyName;
    }
}

Also, to be clear in answer: @Yuval Itzchakov suggested that in C#6 solution is:

var a = new A();
string bName = nameof(a.B);

Upvotes: 1

Yuval Itzchakov
Yuval Itzchakov

Reputation: 149636

You can use C#-6 nameof operator:

var a = new A();
string bName = nameof(a.B);

Note that generally attempting to relay on a run-time name of a property/field for table lookup seems like a bad idea.

Upvotes: 5

Lundsern
Lundsern

Reputation: 170

Can you use the PropertyInfo class?

var a = B.GetInfo().GetProperties();
foreach(PropertyInfo propertyInfo in a)
    string name = propertyInfo.Name

Upvotes: 1

Lasse V. Karlsen
Lasse V. Karlsen

Reputation: 391704

There is no way to do what you want.

You cannot find the name of whatever it is that is storing the reference to your object, that information is simply not available.

Basically, this:

var x = new BObject();
// from inside BObject, get the name "x"

is not possible. The fact that you have stored it in a field of another object changes nothing, it simply cannot be done.

You need to have a way to explicitly tell that object which table name it should use.

Upvotes: 3

Related Questions