The New keyword is often used in daily C# programming.
(1)new modifier is used to hide inherited members of base class members.
(2)new operator is used to create objects and call constructors.
(3)new constraints are used to constrain the types of parameters that may be used as type parameters in a generic declaration.
new modifier
Use the new modifier to explicitly hide members inherited from a base class. To hide an inherited member, declare the member in a derived class with the same name and modify it with the new modifier.
Please look at the following classes:
1 public class MyClass
2
3 {
4 < /p>
5 public int x;
6
7 public void Invoke() {}
8
9 }
10
Declaring members with the Invoke name in the derived class will hide the Invoke method in the base class, that is:
1 public class MyDerivedC : MyClass < /p>
2
3 {
4
5 new public void Invoke() {}
6
p>
7 }
8
However, because field x is not hidden by a similar name, this does not affect the field.
new operator
1. Used to create objects and call constructors
Example: Class_Test MyClass = new Class_Test();
2. Also used to call the default constructor for value types
Example: int myInt = new int();
myInt is initialized to 0, which is the default value of the int type . The effect of this statement is equivalent to: int myInt = 0;
3. The new operator cannot be overloaded.
4. If the new operator fails to allocate memory, it will throw an OutOfMemoryException exception.
Hiding names through inheritance takes one of the following forms:
1. Introducing methods in a class or structure hides properties, fields and types with the same name in the base class. Also hides all base class methods with the same signature.
2. Introducing an indexer in a class or structure will hide all base class indexers with the same name.
3. It is wrong to use new and override at the same time on the same member.
4. Introducing constants, assignments, properties or types in a class or structure hides all base class members with the same name.
Note: Using the new modifier in a declaration that does not hide inherited members will generate a warning.