Class instances help

  • Thread starter Thread starter Timothy V
  • Start date Start date
T

Timothy V

Hi,
I have a problem. How do i create an instance of an unknown derived class?
I'll explain more with the following code.

abstract class Animal {}
sealed class Dog {}
sealed class Cat {}

Animal GetAnimal(string name)
{
if (name = "a")
return new Dog();
else
return new Cat();
}

static void Main()
{
Animal a = GetAnimal("a");
a.GetType() // This will be 'Dog'
}

From this code, I end up with a Dog instance inside Animal. Because it could
be a Cat, how do I dynamically cast it to the type it actually is?

I hope that makes sense because i'm stuck :-(

Thank you in advance,

Tim.
 
If this is the exact code, syntactically speaking, you can't use if(name =
"a") it should be if(name.Equals("a"));

Strings are immutable types and you must use the Equal method on strings.
Otherwise in an 'if' statement typically you will use '==' for comparisons.
 
Timothy,

If you want to use a dog instance, then you could do:

// Get a dog instance.
Dog pobjDog = a as Dog;

However, you have to make sure that pobjDog is not null, because the
cast might not be valid.

Hope this helps.
 
whoops sorry. typo :-)

stepfam said:
If this is the exact code, syntactically speaking, you can't use if(name =
"a") it should be if(name.Equals("a"));

Strings are immutable types and you must use the Equal method on strings.
Otherwise in an 'if' statement typically you will use '==' for
comparisons.
 
stepfam said:
If this is the exact code, syntactically speaking, you can't use if(name =
"a") it should be if(name.Equals("a"));

Strings are immutable types and you must use the Equal method on strings.
Otherwise in an 'if' statement typically you will use '==' for comparisons.

No, there's nothing wrong with using == on strings, so long as the
expression on both sides is of type string - then it will use the
overloaded operator.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top