Sturm
Sturm

Reputation: 4125

Get all types in an assembly with a property named XYZ

I want to get all types in certain assembly that have declared a property with a specific name:

public class Car
{
     public WheelInfo WHEEL { get; set; }
}

public class Plane
{
    public WheelInfo WHEEL { get; set; }
}

Note that these classes are not derived from the same base class that implements WHEEL but actually those are different properties that just happen to have the same name.

What would be the proper approach to this using reflection in C#? There are 200+ classes in the assembly that will be searched.

Right now I can check if a type ABC has a property XYZ declared this way:

Type t = typeof(MyAssembly).Assembly.GetType("MyAssembly.ABC");
var customProperty = t.GetProperty("XYZ"); //check if it is null

But I don't know if there is a better way of just getting all types and for each search all properties and see if any is named as the input sting.

Upvotes: 0

Views: 115

Answers (2)

Georg
Georg

Reputation: 5791

Theoretically, it is even more complicated than that. The problem is that the CLR allows multiple properties to have the same name, as long as they have different parameters (that only holds for indexed properties not supported by C# with the exception of indexers).

Thus, you normally would even have to iterate through all properties of a given type and see whether there is at least one with your name and maybe no parameters.

However, this is a corner case and you may want to just ignore it, I just wanted to make you aware for some Exceptions that may arise if you do not take indexed properties into account.

So if you have a chance to influence the assembly you want to use, you are much better off to use an interface as indicated in the comments already.

Upvotes: 0

Patrick Hofman
Patrick Hofman

Reputation: 157098

There is not better way than to iterate over all types and check each of them for the property you are looking for.

You could use something like this:

foreach (Type t in typeof(MyAssembly).Assembly.GetTypes())
{
    PropertyInfo p = t.GetProperty("XYZ");

    if (p != null)
    { ... }
}

Of course, if possible, it would be better to create an interface to match on, but if you have no control over the code in the assembly, this is your only solution.

Upvotes: 1

Related Questions