Sunday, November 23, 2008

Shall we have the method in drived class with the same name which is there in base class?

Example:

namespace ConsoleApplication5
{
class Sample
{
public int Age()
{
return 12;
}
}
class Program:Sample
{
public int Age()
{
return 56;
}
static void Main(string[] args)
{
Program pgm = new Program();
Console.WriteLine(pgm.Age());
Console.ReadLine();
}
}
}

Output:56

Warning Message: 'ConsoleApplication5.Program.Age()' hides inherited member 'ConsoleApplication5.Sample.Age()'. Use the new keyword if hiding was intended. C:\Documents and Settings\hemnam\My Documents\Visual Studio 2005\Projects\ConsoleApplication5\ConsoleApplication5\Program.cs

If you want to resolve this warning message put the 'New' keyword in the derived class.So automatically the warning message will goes off.

The reason behind, whenever if you use 'New' keyword it will hide the base class method.

1.
In C#, derived classes can contain methods with the same
name as base class methods.

2. The base class method must be defined virtual.
If the method in the derived class is not preceded by
new or override keywords, the compiler will issue a warning
and the method will behave as if the new keyword were present.

3. If the method in the derived class is preceded with
the new keyword, the method is defined as being independent
of the method in the base class.

4. If the method in the derived class is preceded with
the override keyword, objects of the derived class will call
that method instead of the base class method.

5. The base class method can be called from within the
derived class using the base keyword. The override, virtual, and new keywords can also be
applied to properties, indexers, and events.

No comments: