A
A
Artem2017-09-02 16:46:21
OOP
Artem, 2017-09-02 16:46:21

How can I find out which class property is assigned to a given instance?

Question for C# experts.
I have two classes:

class A {
    public B prop1 {get; set;}
    public B prop2 {get; set;}
}

class B {
    public B() {
        // я присвоен свойству prop1 или prop2?
    }
}

How can I find out from the constructor of class B which of the properties of the parent class A (prop1 or prop2) this instance of class B is assigned to? Interested in the name of the property.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Artem, 2017-09-03
@devspec

class A
{
    private B _prop1;
    public B prop1
    {
        get => _prop1;
        set => SetProp(value, ref _prop1);
    }

    private B _prop2;
    public B prop2
    {
        get => _prop2;
        set => SetProp(value, ref _prop2);
    }

    private void SetProp(B value, ref B field, [CallerMemberName] string propName = null)
    {
        if(field != null) field.Association = null;
        field = value;
        if (field != null) field.Association = propName;
    }

}

class B
{
    public string Association { get; set; }
}

How do you like this decision?

A
alexs0ff, 2017-09-03
@alexs0ff

The question is incorrect. an instance of class B at the time of code execution in the constructor cannot be assigned to anything. First, the type constructor is executed, and then the instance can get into either prop1 or prop2.

G
Griboks, 2017-09-02
@Griboks

Pass class A to the constructor or use reflection. Well, or just pass the name to the constructor.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question