Finding the Concrete Type behind an Interface instance
Solution 1:
Type objectType = myObject.GetType();
Should still give you the concrete type, according to your example.
Solution 2:
What are you doing is really bed design but you don't have to use reflection you can check it like this
void PerformAction(object myObject)
{
B objectType = myObject as B; // Here is where I get typeof(IA)
if ( objectType != null )
{
//use objectType.b
}
else
{
//Same with A
}
// snip - other actions on objectType
}
Solution 3:
I have to agree about the bad design. If you have an interface, it should be because you need to utilize some common functionality without caring what the concrete implementation is. Given you're example, it sounds like the PerformAction method should actually be a part of the interface:
public interface IA
{
int a { get; set; }
void PerformAction();
}
public class B: IA
{
public int a { get; set; }
public int b { get; set; }
public void PerformAction()
{
// perform action specific to B
}
}
public class C : IA
{
public int a { get; set; }
public int c { get; set; }
public void PerformAction()
{
// perform action specific to C
}
}
void PerformActionOn(IA instance)
{
if (instance == null) throw new ArgumentNullException("instance");
instance.PerformAction();
// Do some other common work...
}
B b = new B();
C c = new C();
PerformActionOn(b);
PerformActionOn(c);