سؤال

I have the following two use cases:

class BaseCalculator
{
    public int Sum(int x, int y)
    {
        return x + y;
    }   
}

class Calculator : BaseCalculator
{
    public new int Sum ( int x , int y )
    {
        return x + y;
    }
}

This did explicitly hide the Sum method using the new keyword.

class BaseCalculator
{
    public int Sum(int x, int y)
    {
        return x + y;
    }
}

class Calculator : BaseCalculator
{
    public int Sum ( int x , int y )
    {
        return x + y;
    }
}

I didn't understand the difference between the two. Does the second code implicitly hide the Sum method?

هل كانت مفيدة؟

المحلول

From MSDN documentation:

In C#, derived classes can contain methods with the same name as base class methods. 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.

And why the two code pieces are the same is explained below:

Using the new keyword tells the compiler that your definition hides the definition that is contained in the base class. This is the default behavior.

The only difference is that by using new keyword, you avoid the compiler warning.

More explanation can also be found on MSDN in Knowing When to Use Override and New Keywords (C# Programming Guide).

نصائح أخرى

Yes it does. There is no semantic difference. The new keyword merely emphasizes the hiding. It is similar to the behavior of the private modifier. Members are private by default, but you can write private anyway.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top