-5

The question is more theoretical than the usual questions on stack overflow. My question is: If class A inherits from class B what is/are the right ways to initialize objects if they both have an empty constructor (no parameters)?

This are the options:

  1. A a = new B();
  2. B b = new A();
  3. A a = new B() as A;
  4. B b = new A() as B;

I think that both 1 and 3 are possible but I'm really not sure. Can someone explain which are right and why?

Scott Chamberlain
  • 124,994
  • 33
  • 282
  • 431

1 Answers1

2

Short answer: it depends.

If you want an object of type A, then use constructor A(). If you want an object of type B, then use constructor B().

To make something more concrete, here come the animal classes.

public class Giraffe : Animal {}
public class Animal {}

Then your code becomes

Animal a = new Giraffe(); // perfectly normal, imo
//Giraffe  b = new Animal(); compiler error!
Animal a = new Giraffe() as Animal; // "as Animal" is redundant
Giraffe  b = new Animal() as Giraffe; // this is strange, but compiler is OK with it... not sure of a use case for this exact piece of code.

The type of the variable doesn't mean all that much, unless you are exposing a field or property on a class. In this case, consider how the object looks to outsiders. If you want outsides to view you field/property as an object of type Animal, then use that. Same for type Giraffe.

Frank Bryce
  • 8,076
  • 4
  • 38
  • 56
  • Thanks for the answer but besides the fact that it should be clear to the user what are the right ways, are they all possible or are just some possible? – Gillis Werrebrouck May 27 '16 at 20:34
  • See my revision. By "possible" I took this to mean what the compiler will allow you to do. Keep in mind that "types" really are useful for generating CLR code, in the case of C#. Once the object is created, then it "really is" an `Animal` or `Giraffe` based on the actual fields it has. I think [a question I asked a while ago may help](https://stackoverflow.com/questions/31128496/how-to-define-what-type-means). – Frank Bryce May 27 '16 at 20:39
  • Ok thank you for the revision, it cleared up a lot :) – Gillis Werrebrouck May 27 '16 at 20:43
  • No problem :). Your question was voted down because it didn't fit SO's guidelines for what makes a good question for a Q/A site. I think it was a good question, in general, though. Don't let the votes get you down – Frank Bryce May 27 '16 at 20:46