Hi,
Here is an example of poly you are assigning your class to a type of object
which does not contain a "Hello" method if you were to cast it back to your
ClassA or ClassB it would then know that this method exists hop my code below
will shed some light.
cheers
keyoke.
using System;
namespace Polymorphism
{
public class Program
{
public static void Main(string[] args)
{
ClassA a = new ClassA();
ClassB b = new ClassB();
baseClass[] classes = new baseClass[] { a, b };
foreach (baseClass obj in classes)
{
Console.WriteLine(obj.Hello());
}
}
}
public class ClassA:baseClass
{
public ClassA()
{
base._message = "Hello from ClassA";
}
}
public class ClassB:baseClass
{
public ClassB()
{
base._message = "Hello from ClassA";
}
}
public class baseClass
{
public string _message;
public string Hello()
{
return _message;
}
}
}
[quoted text, click to view] C <C@discussions.microsoft.com> wrote:
>Hi,
>
>I am trying to demonstrate Polymorphism using below code.
>
>When I run the code I want to get below.
>
>"Hello from ClassA"
>"Hello from Classb"
>
>What am I doing wrong?
>
>Thanks,
>
>
>using System;
>
>namespace Polymorphism
>{
> public class Program
> {
> public static void Main(string[] args)
> {
> ClassA a = new ClassA();
> ClassB b = new ClassB();
>
> Object[] classes = new Object[] {a, b};
>
> foreach (Object obj in classes)
> {
> Console.WriteLine(obj.Hello());
> }
> }
> }
>
>
> public class ClassA
> {
> public string Hello()
> {
> return "Hello from ClassA";
> }
> }
>
>
> public class ClassB
> {
> public string Hello()
> {
> return "Hello from ClassB";
> }
> }
>}