I have read many of the stack-overflow questions and answers about "Method hiding,new keyword,overriding,and their differences but still i am confused why NEW keyword is using ?
here is my doubt,
(1.)
class Base
{
// base property
public virtual string Name
{
get { return "Base"; }
}
}
class New : Base
{
// new property, hides the base property
public new string Name
{
get { return "New"; }
}
}
New n = new New();
// type of `n` variable is `New`, and `New.Name` is not virtual,
// so compiler sees `n.Name` as a completely different property
Console.WriteLine(n.Name); // prints "New"
But my question is if we use New n = new New();
with out new
keyword also, it will print the same result "New " .Then what is the necessity of new keyword ? WHY and WHEN we use New keyword ? Can any one tell me exactly where it is useful ? With some examples ?
(2.)
class Program
{
public class A
{
public virtual string GetName()
{
return "A";
}
}
public class B : A
{
public override string GetName()
{
return "B";
}
}
public class C : B
{
new public string GetName()
{
return "C";
}
}
static void Main(string[] args)
{
A instance = new C();
Console.WriteLine(instance.GetName());
Console.ReadLine();
}
}
In the above example its printing B
Why not C
? , My question is if new keyword will hide the base class member then why here B is not hiding ?I read many stack overfolw answers but still i am confused with new
keyword some one please clear my doubt