Wednesday, November 4, 2009

Reflection and Explicitly implemented interface members

I have an interface ISomeInterface that does something.

public interface ISomeInterface
{
void DoSomething();
}

And a class SomeClass that implements ISomeInterface explicitly.

public class SomeClass : ISomeInterface
{
#region ISomeInterface Members

void ISomeInterface.DoSomething()
{
throw new NotImplementedException();
}

#endregion
}

My goal was to reflect the members of SomeClass. So i went ahead and wrote this common code :

Type type = typeof(SomeClass);
MethodInfo[] methodInfo = type.GetMethods();

To my surprise methodInfo had only those methods provided by System.Object.



Hold on where's my interface method? Taking a second look at my SomeClass i found that explicitly implemented member was private to SomeClass. Ok So this brings BindingFlags into play. BindingFlags control the binding and specify the way search is conducted for types and members in reflection. Luckly GOOGLE did the trick again.

Type type = typeof(SomeClass);


MethodInfo[] methodInfo = type.GetMethods(BindingFlags.NonPublic
BindingFlags.Instance);


No comments:

Post a Comment