0

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);
a1ex07
  • 36,826
  • 12
  • 90
  • 103

2 Answers2

2

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.

cdhowie
  • 158,093
  • 24
  • 286
  • 300
  • I interpreted the code as failing because B is not an A, so the cast is not possible, in the first case. Am I at the wrong end of the stick? – Tim Barrass Dec 15 '10 at 18:25
  • @Tim: Not at all. That's the same thing I said, just with different words. :) – cdhowie Dec 15 '10 at 18:29
  • Thanks for your answer. My real problem is that I'm creating custom identity that should implement IIdentity and contain extra useful information about user. I just tried to avoid aggregation. – a1ex07 Dec 15 '10 at 18:44
  • @a1ex07: I see. Yeah, if you have an existing object and have no control over its creation, and you want to tack an interface on to it, aggregation is really your only option. – cdhowie Dec 15 '10 at 18:48
  • Ha, long day 8{ Thanks @cdhowie – Tim Barrass Dec 15 '10 at 19:18
1

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.

jason
  • 236,483
  • 35
  • 423
  • 525