C#: Why isn't the expected override result coming out? [duplicate] - c#

This question already has answers here:
new keyword in method signature
(9 answers)
Closed 9 years ago.
I have two classes
class A
{
public virtual void Metod1()
{
Console.WriteLine("A.Method1");
}
}
class B : A
{
public new void Metod1()
{
Console.WriteLine("B.Method1");
}
}
Then I write some code that declares instances of these classes, and calls their methods
static void Main(string[] args)
{
A a = new B();
a.Metod1();
B b = new B();
b.Metod1();
Console.ReadKey();
}
I gave following result:
A.Method1
B.Method1
But when I delete keyword new from signature method1 of class B and run Main method I got same result.
Question:Is new keyword in signature of methods only for better readability?
Edit:Are there cases where we can not do without a new keyword?

The new keyword let the code reader be aware that this method will hide the method with the same name in its base. Even if you ommited it, the compiler would treat it in the same way, but warn you about that.
Since you declared the method as virtual, you would get this warning when you compile:
'B.Metod1()' hides inherited member 'A.Metod1()'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword.
However, if you change the declaration by removing virtual as:
Declaration without virtual in A
class A {
public void Metod1() {
Console.WriteLine("A.Method1");
}
}
class B: A {
public void Metod1() {
Console.WriteLine("B.Method1");
}
}
Will still compile, but the warning message would be:
'B.Metod1()' hides inherited member 'A.Metod1()'. Use the new keyword if hiding was intended.
In either way as above, the following:
Test code
var b=new B();
b.Metod1();
(b as A).Metod1();
will output:
B.Method1
A.Method1
But, if you declare as the following:
Declaration with override in B
class A {
public virtual void Metod1() {
Console.WriteLine("A.Method1");
}
}
class B: A {
public override void Metod1() {
Console.WriteLine("B.Method1");
}
}
Then the output would be:
B.Method1
B.Method1
That is because Method1 of the base class is not just hidden but overridden by the derived class.
A case that you cannot just use new is that if Method1 is a abstract method in a abstract class:
Code that must use override in derived classes
abstract class A {
public abstract void Metod1();
}
class B: A {
public override void Metod1() { // use `new` instead of `override` would not compile
Console.WriteLine("B.Method1");
}
}
In this case you cannot just use new, because A requires derived classes to override Method1.

Knowing When to Use Override and New Keywords (C# Programming Guide)
In C#, a method in a derived class can have the same name as a method
in the base class. You can specify how the methods interact by using
the new and override keywords. The override modifier extends the base
class method, and the new modifier hides it.
also
By using new, you are asserting that you are aware that the member
that it modifies hides a member that is inherited from the base
class.

Yes, you are correct, it is for better readability in this situation.
But check carefully you should have a warning for not using new when hiding the base method.
You can read more here:
http://msdn.microsoft.com/en-us/library/vstudio/435f1dw2.aspx

Related

Why in this code the output of the virtual functions is like this? [duplicate]

What are differences between declaring a method in a base type "virtual" and then overriding it in a child type using the "override" keyword as opposed to simply using the "new" keyword when declaring the matching method in the child type?
I always find things like this more easily understood with pictures:
Again, taking joseph daigle's code,
public class Foo
{
public /*virtual*/ bool DoSomething() { return false; }
}
public class Bar : Foo
{
public /*override or new*/ bool DoSomething() { return true; }
}
If you then call the code like this:
Foo a = new Bar();
a.DoSomething();
NOTE: The important thing is that our object is actually a Bar, but we are storing it in a variable of type Foo (this is similar to casting it)
Then the result will be as follows, depending on whether you used virtual/override or new when declaring your classes.
The "new" keyword doesn't override, it signifies a new method that has nothing to do with the base class method.
public class Foo
{
public bool DoSomething() { return false; }
}
public class Bar : Foo
{
public new bool DoSomething() { return true; }
}
public class Test
{
public static void Main ()
{
Foo test = new Bar ();
Console.WriteLine (test.DoSomething ());
}
}
This prints false, if you used override it would have printed true.
(Base code taken from Joseph Daigle)
So, if you are doing real polymorphism you SHOULD ALWAYS OVERRIDE. The only place where you need to use "new" is when the method is not related in any way to the base class version.
Here's some code to understand the difference in the behavior of virtual and non-virtual methods:
class A
{
public void foo()
{
Console.WriteLine("A::foo()");
}
public virtual void bar()
{
Console.WriteLine("A::bar()");
}
}
class B : A
{
public new void foo()
{
Console.WriteLine("B::foo()");
}
public override void bar()
{
Console.WriteLine("B::bar()");
}
}
class Program
{
static int Main(string[] args)
{
B b = new B();
A a = b;
a.foo(); // Prints A::foo
b.foo(); // Prints B::foo
a.bar(); // Prints B::bar
b.bar(); // Prints B::bar
return 0;
}
}
The new keyword actually creates a completely new member that only exists on that specific type.
For instance
public class Foo
{
public bool DoSomething() { return false; }
}
public class Bar : Foo
{
public new bool DoSomething() { return true; }
}
The method exists on both types. When you use reflection and get the members of type Bar, you will actually find 2 methods called DoSomething() that look exactly the same. By using new you effectively hide the implementation in the base class, so that when classes derive from Bar (in my example) the method call to base.DoSomething() goes to Bar and not Foo.
Beyond just the technical details, I think using virtual/override communicates a lot of semantic information on the design. When you declare a method virtual, you indicate that you expect that implementing classes may want to provide their own, non-default implementations. Omitting this in a base class, likewise, declares the expectation that the default method ought to suffice for all implementing classes. Similarly, one can use abstract declarations to force implementing classes to provide their own implementation. Again, I think this communicates a lot about how the programmer expects the code to be used. If I were writing both the base and implementing classes and found myself using new I'd seriously rethink the decision not to make the method virtual in the parent and declare my intent specifically.
virtual / override tells the compiler that the two methods are related and that in some circumstances when you would think you are calling the first (virtual) method it's actually correct to call the second (overridden) method instead. This is the foundation of polymorphism.
(new SubClass() as BaseClass).VirtualFoo()
Will call the SubClass's overriden VirtualFoo() method.
new tells the compiler that you are adding a method to a derived class with the same name as a method in the base class, but they have no relationship to each other.
(new SubClass() as BaseClass).NewBar()
Will call the BaseClass's NewBar() method, whereas:
(new SubClass()).NewBar()
Will call the SubClass's NewBar() method.
The difference between the override keyword and new keyword is that the former does method overriding and the later does method hiding.
Check out the folllowing links for more information...
MSDN and Other
new keyword is for Hiding. - means you are hiding your method at runtime. Output will be based base class method.
override for overriding. - means you are invoking your derived class method with the reference of base class. Output will be based on derived class method.
My version of explanation comes from using properties to help understand the differences.
override is simple enough, right ? The underlying type overrides the parent's.
new is perhaps the misleading (for me it was). With properties it's easier to understand:
public class Foo
{
public bool GetSomething => false;
}
public class Bar : Foo
{
public new bool GetSomething => true;
}
public static void Main(string[] args)
{
Foo foo = new Bar();
Console.WriteLine(foo.GetSomething);
Bar bar = new Bar();
Console.WriteLine(bar.GetSomething);
}
Using a debugger you can notice that Foo foo has 2 GetSomething properties, as it actually has 2 versions of the property, Foo's and Bar's, and to know which one to use, c# "picks" the property for the current type.
If you wanted to use the Bar's version, you would have used override or use Foo foo instead.
Bar bar has only 1, as it wants completely new behavior for GetSomething.
Not marking a method with anything means: Bind this method using the object's compile type, not runtime type (static binding).
Marking a method with virtual means: Bind this method using the object's runtime type, not compile time type (dynamic binding).
Marking a base class virtual method with override in derived class means: This is the method to be bound using the object's runtime type (dynamic binding).
Marking a base class virtual method with new in derived class means: This is a new method, that has no relation to the one with the same name in the base class and it should be bound using object's compile time type (static binding).
Not marking a base class virtual method in the derived class means: This method is marked as new (static binding).
Marking a method abstract means: This method is virtual, but I will not declare a body for it and its class is also abstract (dynamic binding).
using System;
using System.Text;
namespace OverrideAndNew
{
class Program
{
static void Main(string[] args)
{
BaseClass bc = new BaseClass();
DerivedClass dc = new DerivedClass();
BaseClass bcdc = new DerivedClass();
// The following two calls do what you would expect. They call
// the methods that are defined in BaseClass.
bc.Method1();
bc.Method2();
// Output:
// Base - Method1
// Base - Method2
// The following two calls do what you would expect. They call
// the methods that are defined in DerivedClass.
dc.Method1();
dc.Method2();
// Output:
// Derived - Method1
// Derived - Method2
// The following two calls produce different results, depending
// on whether override (Method1) or new (Method2) is used.
bcdc.Method1();
bcdc.Method2();
// Output:
// Derived - Method1
// Base - Method2
}
}
class BaseClass
{
public virtual void Method1()
{
Console.WriteLine("Base - Method1");
}
public virtual void Method2()
{
Console.WriteLine("Base - Method2");
}
}
class DerivedClass : BaseClass
{
public override void Method1()
{
Console.WriteLine("Derived - Method1");
}
public new void Method2()
{
Console.WriteLine("Derived - Method2");
}
}
}

Difference in replacing "new" with "override" keyword [duplicate]

This question already has answers here:
Difference between new and override
(14 answers)
Closed 9 years ago.
Please find the code below:
using System;
namespace MainNS
{
abstract class BaseClass
{
abstract public void fun();
}
class DerivedClass1 : BaseClass
{
override public void fun()
{
Console.WriteLine("fun() of DerivedClass1 invoked!");
}
}
class DerivedClass2 : DerivedClass1
{
new public void fun()
{
Console.WriteLine("fun() of DerivedClass2 invoked!");
}
}
class MainClass
{
public static void Main(string[] args)
{
DerivedClass1 d1 = new DerivedClass2();
d1.fun();
Console.ReadKey();
}
}
}
What is the use of replacing new with override here and Please explain the actual concept behind this.
Override keyword makes fun() of DerivedClass2 to be executed and new keyword makes fun() of DerivedClass1 to be executed.
class DerivedClass2 : DerivedClass1
{
new public void fun()
{
Console.WriteLine("fun() of DerivedClass2 invoked!");
}
}
The following page summarizes your question very nicely.
Knowing When to Use Override and New Keywords
Summary
Override: When a method of a base class is overridden in a derived class, the version in the derived class is used, even if the calling code didn't "know" that the object was an instance of the derived class.
New: If you use the new keyword instead of override, the method in the derived class doesn't override the method in the base class, it merely hides it.
If you don't specify either new or overrides, the resulting output is the same as if you specified new, but you'll also get a compiler warning (as you may not be aware that you're hiding a method in the base class method, or indeed you may have wanted to override it, and merely forgot to include the keyword).
Override: used with virtual/abstract/override type of method in base class
New: when base class has not declared method as virtual/abstract/override
New Vs Override

Use new keyword in c# [duplicate]

This question already has answers here:
new keyword in method signature
(9 answers)
Closed 9 years ago.
I have two classes
class A
{
public virtual void Metod1()
{
Console.WriteLine("A.Method1");
}
}
class B : A
{
public new void Metod1()
{
Console.WriteLine("B.Method1");
}
}
Then I write some code that declares instances of these classes, and calls their methods
static void Main(string[] args)
{
A a = new B();
a.Metod1();
B b = new B();
b.Metod1();
Console.ReadKey();
}
I gave following result:
A.Method1
B.Method1
But when I delete keyword new from signature method1 of class B and run Main method I got same result.
Question:Is new keyword in signature of methods only for better readability?
Edit:Are there cases where we can not do without a new keyword?
The new keyword let the code reader be aware that this method will hide the method with the same name in its base. Even if you ommited it, the compiler would treat it in the same way, but warn you about that.
Since you declared the method as virtual, you would get this warning when you compile:
'B.Metod1()' hides inherited member 'A.Metod1()'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword.
However, if you change the declaration by removing virtual as:
Declaration without virtual in A
class A {
public void Metod1() {
Console.WriteLine("A.Method1");
}
}
class B: A {
public void Metod1() {
Console.WriteLine("B.Method1");
}
}
Will still compile, but the warning message would be:
'B.Metod1()' hides inherited member 'A.Metod1()'. Use the new keyword if hiding was intended.
In either way as above, the following:
Test code
var b=new B();
b.Metod1();
(b as A).Metod1();
will output:
B.Method1
A.Method1
But, if you declare as the following:
Declaration with override in B
class A {
public virtual void Metod1() {
Console.WriteLine("A.Method1");
}
}
class B: A {
public override void Metod1() {
Console.WriteLine("B.Method1");
}
}
Then the output would be:
B.Method1
B.Method1
That is because Method1 of the base class is not just hidden but overridden by the derived class.
A case that you cannot just use new is that if Method1 is a abstract method in a abstract class:
Code that must use override in derived classes
abstract class A {
public abstract void Metod1();
}
class B: A {
public override void Metod1() { // use `new` instead of `override` would not compile
Console.WriteLine("B.Method1");
}
}
In this case you cannot just use new, because A requires derived classes to override Method1.
Knowing When to Use Override and New Keywords (C# Programming Guide)
In C#, a method in a derived class can have the same name as a method
in the base class. You can specify how the methods interact by using
the new and override keywords. The override modifier extends the base
class method, and the new modifier hides it.
also
By using new, you are asserting that you are aware that the member
that it modifies hides a member that is inherited from the base
class.
Yes, you are correct, it is for better readability in this situation.
But check carefully you should have a warning for not using new when hiding the base method.
You can read more here:
http://msdn.microsoft.com/en-us/library/vstudio/435f1dw2.aspx

Preventing a method from being overridden in C#

How do I prevent a method from being overridden in a derived class?
In Java I could do this by using the final modifier on the method I wish to prevent from being overridden.
How do I achieve the same in C#?
I am aware of using sealed but apparently I can use it only with the override keyword?
class A
{
public void methodA()
{
// Code.
}
public virtual void methodB()
{
// Code.
}
}
class B : A
{
sealed override public void methodB()
{
// Code.
}
}
So in the above example I can prevent the methodB() from being overridden by any classes deriving from class B, but how do I prevent class B from overriding the methodB() in the first place?
Update: I missed the virtual keyword in the methodB() declaration on class A when i posted this question. Corrected it.
You don't need to do anything. The virtual modifier specifies that a method can be overridden. Omitting it means that the method is 'final'.
Specifically, a method must be virtual, abstract, or override for it to be overridden.
Using the new keyword will allow the base class method to be hidden, but it will still not override it i.e. when you call A.methodB() you will get the base class version, but if you call B.methodB() you will get the new version.
As you mentioned, you can prevent further overriding of MethodB in class B by using sealed with override
class B : A
{
public sealed override void methodB()
{
Console.WriteLine("Class C cannot override this method now");
}
}
Use of the sealed modifier along with override prevents a derived class from further overriding the method.
If you do not want methodB in class A to be overridden by any child classes, do not mark that method virtual. Simply remove it. virtual keyword enable the method to be overridden in child classes
public void methodA()
{
}
Use sealed keyword on your classes to prevent further overriding of the class
In C#, a function not marked virtual (which also includes overrides of virtual functions) is effectively sealed and cannot be overridden. So, your example code actually won't compile because the override keyword is not valid unless there is a method marked virtual with the same signature in a base class.
If A.methodB() were marked virtual, then you could override the method from A, but prevent it being further overridden in classes deriving more indirectly, using the sealed keyword exactly as you have shown.
One thing to keep in mind is that while method overriding can be prevented, method hiding cannot. Given your current definition of class A, the following definition of class B is legal and there's nothing you can do about it:
class B:A
{
public new void methodB()
{
//code
}
}
The new keyword basically "breaks" the inheritance/overriding hierarchy as it pertains to this one method; any reference to a class B, treated as a class B (or any further derived type) will use the implementation from class B and ignore the one from class A unless B's implementation specifically calls back to it. However, if you were to treat an instance of class B as a class A (by casting it or passing it as a parameter), then the "new" implementation is ignored.
This differs from overriding, where a class B that is being treated as a class A and truly overrides a virtual methodB would still use class B's override of the method. Also understand that method hiding is inferred (though you will get a compiler warning); if you declare a method with the same signature in a derived class and do not specify either new or override, the base class method will be hidden.
In a base class, the sealed keyword is only used to prevent a class from being derived, but in inherited classes it can be used to prevent another inherited class from overriding the method.
To prevent a base class method from being overridden, just do not specify it as virtual. In the example you provided, class B could not override methodB because methodB was not marked as virtual on the original class.
this will compile:
class A
{
public virtual void methodA()
{
//code
}
public virtual void methodB()
{
//code
}
}
class B:A
{
public override void methodB()
{
//code
}
}
this will not:
class A
{
public void methodA()
{
//code
}
public void methodB()
{
//code
}
}
class B:A
{
public override void methodB()
{
//code
}
}
EDITTED: clarified and corrected my original statement about the sealed keyword

What is the difference between the override and new keywords in C#?

What is the difference between the override and new keywords in C# when defining methods in class hierarchies?
The following page summarizes your question very nicely.
Knowing When to Use Override and New Keywords
Summary
Override: When a method of a base class is overridden in a derived class, the version in the derived class is used, even if the calling code didn't "know" that the object was an instance of the derived class.
New: If you use the new keyword instead of override, the method in the derived class doesn't override the method in the base class, it merely hides it.
If you don't specify either new or overrides, the resulting output is the same as if you specified new, but you'll also get a compiler warning (as you may not be aware that you're hiding a method in the base class method, or indeed you may have wanted to override it, and merely forgot to include the keyword).
Override: used with virtual/abstract/override type of method in base class
New: when base class has not declared method as virtual/abstract/override
new will shadow the method with a completely new method (which may or may not have the same signature) instead of overriding it (in which case the new method must have the same signature), meaning that polymorphism won't work. For example, you have these classes:
class A {
public virtual int Hello() {
return 1;
}
}
class B : A {
new public int Hello(object newParam) {
return 2;
}
}
class C : A {
public override int Hello() {
return 3;
}
}
If you do this:
A objectA;
B objectB = new B();
C objectC = new C();
Console.WriteLine(objectB.Hello(null)); // 2
Console.WriteLine(objectC.Hello()); // 3
objectA = objectB;
Console.WriteLine(objectA.Hello()); // 1
objectA = objectC;
Console.WriteLine(objectA.Hello()); // 3
Since you can define new method signatures with new, it's impossible for the compiler to know that the instance of A is actually an instance of B and the new method B defines should be available. new can be used when the parent object's method, property, field or event is not declared with virtual, and because of the lack of virtual the compiler won't “look up” the inherited method. With virtual and override, however, it works.
I would strongly recommend you avoid new; at best, it’s confusing, because you’re defining a method with a name that could be recognized as something else, and at worst, it can hide mistakes, introduce seemingly impossible bugs, and make extending functionality difficult.
Looks like an old question, let me try a different answer:
new : as the name says, it is a new member in the family of inheritance hierarchy and this will be used as base member for further down the chain (if marked as virtual).
override : It means I don't accept my parent class' member implementation and I will do differently.
Consider the following class hierarchy:
using System;
namespace ConsoleApp
{
public static class Program
{
public static void Main(string[] args)
{
Overrider overrider = new Overrider();
Base base1 = overrider;
overrider.Foo();
base1.Foo();
Hider hider = new Hider();
Base base2 = hider;
hider.Foo();
base2.Foo();
}
}
public class Base
{
public virtual void Foo()
{
Console.WriteLine("Base => Foo");
}
}
public class Overrider : Base
{
public override void Foo()
{
Console.WriteLine("Overrider => Foo");
}
}
public class Hider : Base
{
public new void Foo()
{
Console.WriteLine("Hider => Foo");
}
}
}
Output of above codes must be:
Overrider => Foo
Overrider => Foo
Hider => Foo
Base => Foo
A subclass overrides a virtual method by applying the override modifier:
If you want to hide a member deliberately, in which case you can apply the new modifier to the member in the subclass. The new modifier does nothing more than suppress the compiler warning that would otherwise result
override lets you override a virtual method in a base class so that you can put a different implementation in. new will hide a non-virtual method in a base class.
The simple difference is that override means the method is virtual (it goes in conduction with virtual keyword in base class) and new simply means it's not virtual, it's a regular override.
So both really are function overrides, one is with virtual characteristics, the other not.
What does mean exactly? It simply means polymorphism will not be in play for `new' methods.
The following image illustration might make this clear.
Note if you don't use new keyword, it is still implied but it will generate a warning message.

Categories

Resources