Click here to Skip to main content
Click here to Skip to main content

Playing With LINQ: Getting Interface Property Implementations

, 15 Apr 2010
Rate this:
Please Sign up or sign in to vote.
Getting Interface Property Implementations
LINQ With C# (Portuguese)

Today, my friend Nuno was writing some code to get the PropertyInfos of a class implementation of an interface.

free hit counters

Given this interface:

public interface ISomeInterface
{
    int IntProperty { get; set; }
    string StringProperty { get; }
    void Method();
}

and this class:

public class SomeClass : ISomeInterface
{
    int ISomeInterface.IntProperty { get; set; }
    public int IntProperty { get; private set; }
    public string StringProperty { get; private set; }
    public void Method() { }
}

Nuno wanted to retrieve:

  • Int32 ISomeInterface.IntProperty
  • System.String StringProperty

The code is fairly simple. First we need to get the interface mappings for the class:

typeof(SomeClass).GetInterfaceMap(typeof(ISomeInterface)).TargetMethods

and get all PropertyInfos for which the MethodInfo in the list is part of the implementation of the property (is either the set method or the get method).

Something like his:

public static bool Implements(this MethodInfo methodInfo, PropertyInfo propertyInfo)
{
    return (propertyInfo.GetGetMethod(true) == methodInfo) || 
		(propertyInfo.GetSetMethod(true) == methodInfo);
}

But what caught my eye was that, with the above extension methods, I can use LINQ to retrieve a list of the desired PropertyInfos.

Something like this:

public static IEnumerable<PropertyInfo> GetInterfacePropertyImplementation
	(Type implementer, Type implemented)
{
    return (from propertyInfo in implementer.GetProperties
	(BindingFlags.Instance | BindingFlags.Public | 
	BindingFlags.NonPublic).AsEnumerable()
            from methodInfo in implementer.GetInterfaceMap
		(implemented).TargetMethods.AsEnumerable()
            where methodInfo.Implements(propertyInfo)
            select propertyInfo).Distinct();
}

For the sample class and interface, the usage would be something like this:

var q = GetInterfacePropertyImplementation(typeof(SomeClass), typeof(ISomeInterface));

foreach (var p in q)
{
    Console.WriteLine(p);
}

which would produce the following output:

Int32 ISomeInterface.IntProperty
System.String StringProperty

UPDATED: The previous implementation was overcomplicated and had some string based logic. Kudos to Nuno.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Paulo Morgado
Software Developer (Senior) Paulo Morgado
Portugal Portugal

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Mobile
Web03 | 2.8.140721.1 | Last Updated 15 Apr 2010
Article Copyright 2010 by Paulo Morgado
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid