DuckQueen
DuckQueen

Reputation: 810

How to get a field name having its instance in C#?

I have a reference to an object. Not to an object hosting it. I know it is a field in some class. I want to know the field name. So say having:

class A{}
class B{
   public A name1;
   public A name2;
}
class C{
   public A nameX;
}

I have a reference to one of the "names":

void do(A prop) {
    // How to get a field name of prop: name1 or name2 or nameX
}

How to do such thing with reflection in C#?

Upvotes: 0

Views: 210

Answers (1)

Jim Quittenton
Jim Quittenton

Reputation: 56

Something like this should get you all classes, then you could get the fields from each class and check the type for each against your object type. This can give you the first class.fieldname that matches your object type:

        string fieldName;
        IEnumerable<Type> classes = AppDomain.CurrentDomain.GetAssemblies()
            .SelectMany(t => t.GetTypes())
            .Where(t => t.IsClass);

        foreach (Type cls in classes)
        {
            foreach(FieldInfo field in cls.GetFields())
            {
                if (field.FieldType == myObject.GetType())
                {
                    fieldName = cls.FullName + "." + field.Name;
                    break;
                }
            }
        }

Upvotes: 1

Related Questions