"New" keyword used to hide properties and methods
The new keyword indicates that you do not override the method or property of the parent class, you just provide a new implementation, but the 'old', original implementation of the parent can still be used, by casting to the parent or by using polymorphism and using a reference of the father's type to the child.
A simple code example to demonstrate this:
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace NewKeyWordDemo
{
class Program
{
static void Main(string[] args)
{
Child c = new Child();
ChildWithHiddenProperty c2 = new ChildWithHiddenProperty();
//Console.WriteLine((c as Parent).Age); // prints 5
//Console.WriteLine((c2 as Parent).Age); // prints 30
(c as Parent).PrintAge(); // prints 5
(c2 as Parent).PrintAge(); // prints 30
Parent c3 = new ChildWithHiddenProperty();
c3.PrintAge(); // prints 30
IFamily c4 = new ChildWithHiddenProperty(); // prints 30 because only parent implements IFamily and therefor its method is being "chosen"..
c4.PrintAge();
// in some cases you might prefer to just write a new function in the child class that uses base.MethodName for this purpose, but when you have few classes that inherits the same parent and you use polymorphism it might be an overhead to implement it on all of them
}
}
class Parent : IFamily
{
public virtual int Age { get { return 30; } }
public virtual void PrintAge()
{
Console.WriteLine("Method printed 30");
}
}
class Child : Parent
{
public override int Age { get { return 5; } }
public override void PrintAge()
{
Console.WriteLine("Method printed 5");
}
}
class ChildWithHiddenProperty : Parent
{
public new int Age { get { return 5; } }
public new void PrintAge() // new only hides and not overrides - you can still access the parent method by casting to the parent or by using Parent c2 = new ChildWithHiddenProperty(); When called through the interface
{
Console.WriteLine("Method printed 5");
}
}
interface IFamily
{
void PrintAge();
}
}