Today I got to know that we can apply new
inheritance modifier to const field also. I have used it for normal fields and methods and they make complete sense to me as they participate in inheritance hierarchy. I tried my level best to understand the applicability of this keyword to const fields also but couldn't. Here are few things that are coming to my mind:
Inheritance and run time polymorphism make sense in normal (non static) classes. Const fields are static by default. Also, static classes do not support inheritance in C#.
Let's say I've two classes as shown below:
class MyClass1
{
public const string PI = "3.14";
}
class MyClass2 : MyClass1
{
public const string PI = "3.141";
}
For outside world they always access the constants present in these classes using ClassName.FieldName
syntax e.g. MyClass1.PI
or MyClass2.PI
. So for outside world it doesn't matter if MyClass1 and MyClass2 are related through an inheritance hierarchy. MyClass1.PI
fetches 3.14 and MyClass2.PI
fetches 3.141.
If I'm inside an instance method of MyClass2
as shown below the class is fully aware if he is using the static member of his own class or static member of his base class. It uses MyClass1.PI
syntax if he is referring to base class's static field. There is nothing which gets resolved at run-time.
class MyClass2 : MyClass1
{
public const string PI = "3.141";
string GetValueOfPi()
{
return PI;
}
string GetValueOfPiFromBaseClass()
{
return MyClass2.PI; //It clearly uses the syntax for accessing a static field of its base type
}
}
Thus I'm not able to figure out the usage/relevance/significance of new
inheritance modifier for const fields. In code snippet # 1 parser clearly gives me following warning:
'MyClass2.PI' hides inherited member 'MyClass1.PI'. Use the new keyword if hiding was intended.
But what is the piece of consumer code will get confused or break or fall into a problem if I don't use the new
inheritance access modifier here (i.e. if I don't fix the warning). Can someone help me in understanding the concept involved in it?