What is the purpose of the C# new
keyword when used before an attribute class name?
I am using Rider and it suggests to place a new keyword before attribute names pretty often.
public class MyClass
{
new AttributeClass attribute;
...
}
As explained in documentation:
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.
new
keyword on an attribute will let you overwrite type of it. Object when viewed as the base type will not know about it. It can also have a different value in base type and derived type of the same object instance. Needles to say, that can lead to some very confusing bugs.
Consider this example:
class Super
{
int Id;
}
class Sub : Super
{
new string Id;
}
static class Another
{
static void AssignId(Super test, int val)
{
test.Id = val;
}
static Super ShowId(Super test)
{
return test.Id;
}
}
...
var test = new Sub
{
Id = "SUB123"
};
Another.AssignId(test, 123);
Console.WriteLine(Another.ShowId(test)); // 123
Console.WriteLine(test.Id); // SUB123