Click here to Skip to main content
12,699,308 members (32,685 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as


8 bookmarked

Playing With LINQ: Getting Interface Property Implementations

, 15 Apr 2010 CPOL
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:


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 | 
            from methodInfo in implementer.GetInterfaceMap
            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)

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.


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

You may also be interested in...


Comments and Discussions

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