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);
Was it helpful?

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.

OTHER TIPS

No, this is not legal. A Cat is an Animal but an Animal is not necessarily a Cat (replace A by Cat and B by Animal in your example).

Composition might not make sense, as the Cat and Animal example shows again. Composition is usually for "has a" relationships, and an Animal does not have a Cat.

What pattern will work for your specific case depends on the concrete types in your domain.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top