Selecting class at runtime

Tech-Archive recommends: Fix windows errors by optimizing your registry

From: Daniel Bolege (usenet03_at_bolege.de)
Date: 04/22/04


Date: Thu, 22 Apr 2004 15:00:47 +0200

Hello,

I've a problem that drives me crazy. There must be a simple solution, but I
just can't see it. The following code is just a simple example that
demonstrates my problem:

I have an abstract class named "Human" containing members that all derived
classes will need. "Human" does not know anything about its child classes,
so no way for the "virtual/override"-Construct:

1 abstract class Human {
2 public int age = 0;
3 }

Now I have two classes derived from "Human" that contain specific members:

1 class Woman : Human {
2 public void DoFemaleStuff() {
3 System.Console.WriteLine("Go shopping.");
4 }
5 }

and (you guess right)

1 class Man : Human {
2 public void DoMaleStuff() {
3 System.Console.WriteLine("Repair car.");
4 }
5 }

Now, I can do the following trivial stuff:

1 Woman myWoman = new Woman();
2 myWoman.age = 25;
3 myWoman.DoFemaleStuff();
4
5 Man myMan = new Man();
6 myMan.age = 30;
7 myMan.DoMaleStuff();

But, what I want to do is that I only have one human whose sex ist defined
at runtime, like the follwing:

1 if (true) {
2 Woman myHuman = new Woman();
3 myHuman.DoFemaleStuff();
4 } else {
5 Man myHuman = new Man();
6 myHuman.DoMaleStuff();
7 }
8 myHuman.age = 30;

In this example, the compiler says that "myHuman" in Line 8 ist unknown. For
my point of view, this is not correct, although I know that in some
conditional statments more complex than this one a situation may occur
where "myHuman" will not be declared. But I would say, this is the
programmer's, not the comiler's problem.

But the following example fails as well (Note: Class "Human" is now NOT
abstract anymore):

1 Human myHuman;
2 if (true) {
3 myHuman = new Woman();
4 myHuman.DoFemaleStuff();
5 } else {
6 myHuman = new Man();
7 myHuman.DoMaleStuff();
8 }
9 myHuman.age = 30;

Now the compiler says that "myHuman" does not contain a definition for
"DoFemaleStuff" in Line 4 and no for "DoMaleStuff" in Line 7. Aargh!

It seems I just misunderstand a fundamental thing. Any suggestion that
bails me out would be very appreciated.

Daniel

-- 
http://www.bolege.de
E-mails to specified address will NOT be read.
Please use db[at]bolege[dot]de instead.


Relevant Pages

  • Re: Selecting class at runtime
    ... public abstract void DoStuff(); ... public override void DoStuff() { ... > I have an abstract class named "Human" containing members that all derived> classes will need. ... > 2 Woman myHuman = new Woman; ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: Selecting class at runtime
    ... Daniel Bolege wrote: ... the compiler is completely correct. ... The two myHuman ... The last line is not within the scope of either of them. ...
    (microsoft.public.dotnet.languages.csharp)