Pacman Pacman - 1 year ago 77
C# Question

Is there a way to tell in runtime if a class property comes from an interface?

public class Bus : IPresentable
public string Name { get; set; } = "Bus";
public int ID { get; set; } = 12345;

//******** IPresentable interface ***************//
public int LocX { get; set; }

public int LocY { get; set; }


public interface IPresentable
int LocX { get; set; }
int LocY { get; set; }

in my application:

Bus bus = new Bus();
bus.LocX = 10; // is there a way to tell that this comes from interface
bus.Name = "New Name" ; // but this is not ?

Answer Source

Using reflection, we can interrogate the Bus class and retrieve the list of property names that "belong" both to the class and all interfaces it might be implementing:

var interfaceProperties = typeof(Bus)
    .GetProperties().Select(p => p.Name)
        .SelectMany(i => i.GetProperties())
        .Select(p => p.Name))

The result interfaceProperties is an IEnumerable<string>. In this case, it would contain:


You can check the list for the properties you want.

IMO, this is an expensive way to interrogate your classes for this information. Maybe with more background about why you want to do this, a better alternative could be produced.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download