Hi
can any one tell me what is doing new Keyword i am not understanding
class BC
{
public void Display()
{
System.Console.WriteLine("BC::Display");
}
}
class DC : BC
{
new public void Display()
{
System.Console.WriteLine("DC::Display");
}
}
class TC : DC
{
new public void Display()
{
Console.WriteLine("TC::Display");
}
}
class Demo
{
public static void Main()
{
DC b;
b = new DC();
b.Display();
b = new TC();
b.Display();
//b = new TC();
//b.Display();
}
}
Loading

VulpesPosted Jan 3, 2012, 8:33 AM
Sorry, I didn't understand the question in your last post - are you asking about the 'this' keyword?
VulpesPosted Jan 4, 2012, 4:49 AM
Smart LuckyPosted Jan 3, 2012, 11:58 PM
no i mean new keyword...?
Smart LuckyPosted Jan 3, 2012, 7:44 AM
Smart LuckyPosted Jan 3, 2012, 7:00 AM
Is below code right.........?
when can override a method..
with virtual->override keywords as bellow
using System;
namespace Polymorphism
{
class A
{
public virtual void Foo() { Console.WriteLine("A::Foo()"); }
}
class B : A
{
public override void Foo() { Console.WriteLine("B::Foo()"); }
}
class Test
{
static void Main(string[] args)
{
A a;
B b;
a = new A();
b = new B();
a.Foo(); // output --> "A::Foo()"
b.Foo(); // output --> "B::Foo()"
a = new B();
a.Foo(); // output --> "B::Foo()"
}
}
}
but another way to override the method...
is new keyword instead of override..as bellow
using System;
namespace Polymorphism
{
class A
{
public void Foo() { Console.WriteLine("A::Foo()"); }
}
class B : A
{
public new void Foo() { Console.WriteLine("B::Foo()"); }
}
class Test
{
static void Main(string[] args)
{
A a;
B b;
a = new A();
b = new B();
a.Foo(); // output --> "A::Foo()"
b.Foo(); // output --> "B::Foo()"
a = new B();
a.Foo(); // output --> "A::Foo()"
}
}
}
another example
class A
{
public void Foo() {}
}
class B : A
{
public virtual new void Foo() {}
}
class C : B
{
public override void Foo() {}
// or
public new void Foo() {}
}
VulpesPosted Jan 3, 2012, 5:47 AM
If you don't use 'new', the compiler will warn you that the derived class's Display() method is hiding the base class's Display() method but your program will still compile.
You can still access the base class method using the syntax : base.Display().
Notice also that 'new' is not polymorphic.
These two lines:
display DC::Display (not TC::Display) on the console because 'b' is a variable of type DC (not TC) even though it currently refers to an object of type TC. Consequently, DC's version of Display() gets called.