D J
D J

Reputation: 243

Get properties of underlying interface in c#

After reading all of the articles related to the title of this question, I have found some that are close, but none that are perfect for what I am trying to accomplish.

I know how to use reflection to get the properties of a KNOWN interface type. What I don't know is how to get the properties of an interface type that I don't know and won't know until runtime. Here's what I am doing now:

SqlParameterCollection parameters = Command.Parameters;

thing.GetType().GetInterfaces().SelectMany(i => i.GetProperties());
foreach (PropertyInfo pi in typeof(IThing).GetProperties()
   .Where(p => p.GetCustomAttributes(typeof(IsSomAttribute), false).Length > 0))
{
    SqlParameter parameter = new SqlParameter(pi.Name, pi.GetValue(thing));
    parameters.Add(parameter);               
}

... but, this assumes I already know and am expecting an interface of type "IThing". What if I don't know the type before runtime?

Upvotes: 3

Views: 665

Answers (1)

dbugger
dbugger

Reputation: 16464

You don't know to need know the type in advance. You can iterate over the properties without specifying the type:

 static void Main(string[] args)
        {
            ClassA a = new ClassA();
            IterateInterfaceProperties(a.GetType());
            Console.ReadLine();
        }

    private static void IterateInterfaceProperties(Type type)
    {
        foreach (var face in type.GetInterfaces())
        {
            foreach (PropertyInfo prop in face.GetProperties())
            {
                Console.WriteLine("{0}:: {1} [{2}]", face.Name, prop.Name, prop.PropertyType);
            }
        }
    }

Upvotes: 2

Related Questions