This question already has answers here:
new keyword in method signature
(9 answers)
Closed 9 years ago.
I have seen methods that are declared like this:
public void new SortItems()
What does this actually do? I know that the new keyword is used to invoke constructors, but I have also seen it on method definitions like the example above.
When use this way, it's a modifier. It's used to hide an inherited member rather than to override it. This is useful if the base method is sealed. Here's a quick example to demonstrate the difference between overriding and hiding inherited members:
public class Foo
{
public virtual void OverriddenMethod() { Console.WriteLine("foo"); }
public void HiddenMethod() { Console.WriteLine("foo"); }
}
public class Bar : Foo
{
public override void OverriddenMethod() { Console.WriteLine("bar"); }
public new void HiddenMethod() { Console.WriteLine("bar"); }
}
void Main()
{
Bar bar = new Bar();
Foo foo = bar;
bar.OverriddenMethod(); // "bar"
bar.HiddenMethod(); // "bar"
foo.OverriddenMethod(); // "bar"
foo.HiddenMethod(); // "foo"
}
Further Reading
new Modifier (C# Reference)
It should be like this:
public new void SortItems(){
//...
}
This new keyword is used to shadow the base member (method, property, ...) which has the same name (for property, event...) and same signature (for method), in this case it is the method SortItems. It's different from the new in creating new instance. No matter using new to shadow the conflicted member in base class or not, to access the base member you have to use the keyword base to access it in the derived class.
When used in a method signature, it means that the implementation details are different for the class defining them. The problem with this approach is that it is not used polymorphically so:
class Thing
{
void DoSomething()
{
Console.WriteLine("Thing");
}
}
class Other : Thing
{
new void DoSomething()
{
Console.WriteLine("Other");
}
}
var thing = new Thing();
thing.DoSomething(); \\ prints Thing
var other = new Other();
other.DoSomething(); \\ prints Other
((Thing)other).DoSomething(); \\ prints Thing
It is the opposite of override. Say you have:
public class A
{
public virtual void f() { Console.WriteLine( "A" ); }
}
public class B : A
{
public override void f() { Console.WriteLine( "B" ); }
}
public class C : A
{
public new void f() { Console.WriteLine( "C" ); }
}
And then in main:
A b = new B();
A c = new C();
b.f();
c.f();
(c as C).f();
This would print:
B
A
C
It will only call the new method when the type is that of the defining class.
Related
I would like to ask you for an explanation of this example:
public class A : B
{
public override void Method()
{
Console.WriteLine("A");
}
}
public class B
{
public virtual void Method()
{
Console.WriteLine("B");
}
}
Equation:
void Main()
{
B b = (B)new A();
b.Method(); // result A
}
Why upcasting did not work in this case?
How microsoft docs say:
If you want your derived class to have a member with the same name as a member in a base class, you can use the new keyword to hide the base class member. The new keyword is put before the return type of a class member that is being replaced. The following code provides an example:
I am new in c#.confuse with this question.
I Have override ToString() with override and new keyword.both are give me same output.then what is the difference between both.
here is my Example
class A
{
public new string ToString()
{
return "With New Keyword";
}
}
class B
{
public override string ToString()
{
return "With Override Keyword";
}
}
class Program
{
static void Main(string[] args)
{
A a = new A();
B b = new B();
Console.WriteLine(a.ToString());
Console.WriteLine(b.ToString());
Console.Read();
}
}
Output
With New Keyword
With Override Keyword
I know its a silly question.
please anyone help me to give me difference between both methods.
I am not asking about difference between new and override key word.I want to know that difference between both method.In concept of Override Object methods.
It makes a difference when you do this:
object a = new A(); // notice the type of the variable here!
object b = new B();
Console.WriteLine(a.ToString());
Console.WriteLine(b.ToString());
a.ToString() will not call your implementation of ToString and will instead call object.ToString, which returns the fully qualified type name of the object. b.ToString() will call your implementation.
What you did in B is called overriding. What you did in A is called hiding. Hiding loses its effect when the compile time type of a variable is not that type anymore. Your implementation of ToString will only be called when the compile time type is A.
Learn more here.
You can easily google this.
From MSDN
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. The difference is
illustrated in the examples in this topic.
In a console application, declare the following two classes, BaseClass
and DerivedClass. DerivedClass inherits from BaseClass.
In class B you are overriding ToString() method that is Object.ToString() because you have not inherited A. Now consider below example,
class A
{
public string ReturnString()
{
return "ClassA::Method";
}
}
class B : A
{
public newstring ReturnString()
{
return "ClassB::Method";
}
}
class Program
{
static void Main(string[] args)
{
A a = new A();
B b = new B();
Console.WriteLine(a.ToString());
Console.WriteLine(b.ToString());
Console.Read();
}
}
Here you are hiding the method in class B as you have inherited Class A. So you will get the output as ClassA::Method for both method calls.
Now consider below example
class A
{
public virtual string ReturnString()
{
return "ClassA::Method";
}
}
class B : A
{
public override string ReturnString()
{
return "ClassB::Method";
}
}
class Program
{
static void Main(string[] args)
{
A a = new A();
B b = new B();
Console.WriteLine(a.ToString());
Console.WriteLine(b.ToString());
Console.Read();
}
}
Here we have overridden the Class A's method in Class B. This means ClassB method is like extension or you can say it has different meaning than ClassA. You will get output like below
ClassA::Method
ClassB::Method
I have read an article regarding the new keyword. It says it is used to hide methods. This is example they give:
using System;
namespace ConsoleApplication3
{
class SampleA
{
public void Show()
{
Console.WriteLine("Sample A Test Method");
}
}
class SampleB:SampleA
{
public void Show()
{
Console.WriteLine("Sample B Test Method");
}
}
class Program
{
static void Main(string[] args)
{
SampleA a = new SampleA();
SampleB b = new SampleB();
a.Show();
b.Show();
a = new SampleB();
a.Show();
Console.ReadLine();
}
}
}
Output:
Sample A Test Method
Sample B Test Method
Sample A Test Method
So my question isn't the new keyword used to instantiated an object? and its used to allocate memory for new created objects? Then how can method hiding be done using it? And is above example correct?
new is used for 3 different things. You could say there are 3 different keywords with the same name.
It's an operator, used to invoke constructors. Example: new object();
It's a modifier, used to hide an inherited member from a base class member. Example:
class Base {
public void MyMethod() {
//Do stuff
}
}
class Derived : Base {
public new void MyMethod() {
//Do other stuff
}
}
It's a generic type constraint, used to indicate that a generic type parameter has a parameterless constructor. Example:
class MyGenericClass<T> : where T : new() { ... }
Source: new
Isn't the new keyword used to instantiated an object?
Yes it is. Among other things.
then how can method hiding done using it?
The new keyword in the context of method and property definitions has another meaning than the new keyword used to instantiate objects. The new keyword in that context tells that there is a new start of the inheritance tree of that particular method or property. That's all.
Then how can method hiding be done using it? And is above example
correct?
Programming language syntax, grammar and semantics are just an arbitrary set of conventions and specifications. That is, C# can invent one, two or dozen of usages of a given keyword like new.
When new is used during a class member declaration, it means that you're re-using an identifier:
public class A
{
public string Text { get; set; }
}
public class B : A
{
new public int Text { get; set; }
}
As you can check in above code sample, B also implements a Text property, but since derives from A which has also defined a Text property, there's a naming collision.
The so-called new keyword can be used to re-use Text identifier and being able to implement another property Text which may behave absolutely different than the one implemented in the base class. See that Text on B is of type int!
The most important point here is that re-using identifiers isn't the same as using polymorphism, where a class method or property override must match base class' member signature:
public class A
{
public virtual string Text { get; set; }
}
public class B : A
{
public override string Text
{
get { return base.Text; }
set { base.Text = value; }
}
}
Also, re-used identifiers are dangerous:
public class A
{
public string Text { get; set; }
}
public class B : A
{
new public int Text { get; set; }
}
B b = new B();
b.Text = 4;
// Upcast B to A
A a = b;
a.Text = "Bye bye";
Console.WriteLine(a.Text); // Output: Bye bye
Console.WriteLine(b.Text); // Output: 4
See the output of Text. Since re-using identifiers isn't polymorphism, and in above case both are completely different properties, there's an A.Text and B.Text that can be set separately.
To hide an inherited member, declare it in the derived class by using the same member name, and modify it with the new keyword. For example:
public class BaseC
{
public static int x = 55;
public static int y = 22;
}
public class DerivedC : BaseC
{
// Hide field 'x'.
new public static int x = 100;
static void Main()
{
// Display the new value of x:
Console.WriteLine(x);
// Display the hidden value of x:
Console.WriteLine(BaseC.x);
// Display the unhidden member y:
Console.WriteLine(y);
}
}
/*
Output:
100
55
22
*/
You can read more in here
1) Why does the following codes differ.
C#:
class Base
{
public void foo()
{
System.Console.WriteLine("base");
}
}
class Derived : Base
{
static void Main(string[] args)
{
Base b = new Base();
b.foo();
b = new Derived();
b.foo();
}
public new void foo()
{
System.Console.WriteLine("derived");
}
}
Java:
class Base {
public void foo() {
System.out.println("Base");
}
}
class Derived extends Base {
public void foo() {
System.out.println("Derived");
}
public static void main(String []s) {
Base b = new Base();
b.foo();
b = new Derived();
b.foo();
}
}
2) When migrating from one language to another what are the things we need to ensure for smooth transition.
The reason is that in Java, methods are virtual by default. In C#, virtual methods must explicitly be marked as such.
The following C# code is equivalent to the Java code - note the use of virtual in the base class and override in the derived class:
class Base
{
public virtual void foo()
{
System.Console.WriteLine("base");
}
}
class Derived
: Base
{
static void Main(string[] args)
{
Base b = new Base();
b.foo();
b = new Derived();
b.foo();
}
public override void foo()
{
System.Console.WriteLine("derived");
}
}
The C# code you posted hides the method foo in the class Derived. This is something you normally don't want to do, because it will cause problems with inheritance.
Using the classes you posted, the following code will output different things, although it's always the same instance:
Base b = new Derived();
b.foo(); // writes "base"
((Derived)b).foo(); // writes "derived"
The fixed code I provided above will output "derived" in both cases.
The C# code will compile with warnings, since you are hiding methods there.
In Java, class-methods are always virtual, whereas in C# they're not, and you have to mark them explicitly as 'virtual'.
In C#, you'll have to do this:
public class Base
{
public virtual void Foo()
{
Console.WriteLine ("Base");
}
}
public class Derived : Base
{
public override void Foo()
{
Console.WriteLine ("Derived.");
}
}
Today, I found something in legacy code. It has "static new" for one function. It looks like this.
class Foo
{
public static void Do()
{
Console.WriteLine("Foo.Do");
}
}
class Bar: Foo
{
public static new void Do()
{
Console.WriteLine("Bar.Do");
}
}
I don't understand the static new modifier for the Do method in class Bar. In C#, static method can only be invoked with class name instead of object name. So, I don't think there is any difference between having the "new" and not.
Generally, if some syntax is unnecessary, C# just treat it is error.
Anybody has any idea about why C# allows such syntax?
If you remove the new from your code you get:
warning CS0108: 'Bar.Do()' hides inherited member 'Foo.Do()'. Use the new keyword if hiding was intended.
The C# compiler just warns you that you might be doing something you did not intend and asks you to insert the new keyword to confirm that you know what you are doing. Besides suppressing the warning, it has no other effects.
That applies only for external callers. Remember that you can call a static method of the base class, so something like this is valid:
class Foo
{
public static void Do() { Console.WriteLine("Foo.Do"); }
}
class Bar : Foo // :Foo added
{
public static void Something()
{
Do();
}
}
This is why the warning tells you to put the new, you want to avoid any confusion when doing this:
class Foo
{
public static void Do() { Console.WriteLine("Foo.Do"); }
}
class Bar : Foo // :Foo added
{
public static void Something()
{
Do();
}
public static new void Do() { Console.WriteLine("Bar.Do"); }
}
have a look at this
public class BaseC
{
public static int x = 55;
public static int y = 22;
}
public class DerivedC : BaseC
{
// Hide field 'x'.
new public static int x = 100;
static void Main()
{
// Display the new value of x:
Console.WriteLine(x);
// Display the hidden value of x:
Console.WriteLine(BaseC.x);
// Display the unhidden member y:
Console.WriteLine(y);
}
}
/*
Output:
100
55
22
*/
Your example, to make it clear, should be
public class Foo
{
public static void Do() {}
}
public class Bar :Foo
{
public new static void Do() {}
}
In your example, the second class Bar doesn't seem to inherit from Foo. This seems to be a typo because it doesn't makes sense otherwise.
Assuming it to be a typo, the "new" modifier explicitly hides the base class version of the function Do(). This means that the derived version of the Do() method effectively replaces the base class version.
Using "new" here documents the fact that the inherited method is intended as a replacement for the base class version of Do().
For more information, see new Modifier (C#)