Search code examples
c#polymorphismdowncast

C# Down-casting question


Is it valid and legal and to down-cast in the following case:

public interface IA {
  string Property1 {get;}
}
public class B {
   public string Name {get;set;}
}

// class A doesn't have it's own fields, all IA methods/properties are implemented through B methods
public class A:B,IA 
{
   public string Property1
   {
      get {return this.Name}
   }
}
.....
B b = new B();
A a = (A)b; // will it work ?

Or is it better to use composition/aggregation?

public class A :IA
{
   private B b;
   ....
   public string Property1 {get {return b.Name;} }
   public A(B b) {this.b = b}
}
....
B b= new B();  
A a = new A(b);

Solution

  • The first example will not work, because A is-a B; an instance of type B might be an A, but in your case it is not. Casting will fail, and you will get an InvalidCastException at runtime.

    The second example will work, in that it will compile and execute as you expect. But without knowing more details about your actual problem (not a mock problem) I can't tell you if this is the right pattern.