In C#, the new keyword can be used as an operator or modifier
or a constraint.
OPERATOR: Hashtable h = new Hashtable()
MODIFIER: public new void SayHello()
CONSTRAINT: class MyClass where
T : new()
‘New’ as a Operator
- ‘New’ as a operator is used to create and invoke constructors of reference or value types
- int s = new int(); is same as int s = 0;
- New operator cannot be overloaded
Structure cannot have explicitly declared default constructor where as classes can have
If structure has a parameterized constructor, still structure can be instantiated with a default constructor. But if a class has a parameterized constructor explicitly declared in definition, but has no default constructor explicitly specified, it cannot be instantiated with a default constructor.
‘New’ as a modifier
Q. What is the purpose of ‘new’ keyword?
Q. Is it mandatory to apply new keyword?
Q. Where should ‘new’ keyword added in signature?
Q. Is there any change in output if I apply new keyword?
New keyword removes warning which appears when:
- Parent has some property/constant/field with public or protected access specifier and child class also has any property/constant/field/method with name matching the one used in parent.
- Parent class has a method and child class has a method (with same signatures) /constant /field/property with same name
Examples
|
Examples
|
Parent: property X
(any data type)
Child: property X
(any data type)
Use the new keyword
if hiding was intended.
|
Parent: Private
property X (any data type)
Child: property X
(any data type)
No Issues.
|
Parent: Method X
Child: Method X (same
signature)
Use the new keyword
if hiding was intended.
|
Parent: Virtual
Method X
Child: Method X (same
signature)
To make the current
member override that implementation, add the override keyword. Otherwise add
the new keyword.
|
Parent: constant X
Child: property X
Use the new keyword
if hiding was intended.
|
Parent: Method X()
Child: Method X (int
y)
No Issues.
|
Parent: Sealed Method
X
Child: Sealed Method
X
No Issues.
|
- New and override can be used together.
- New can not be used for Constructor methods
- New applied in static class method produce warning, but compiles
‘New’ as a constraint
New can be used as a constraint in generics like
class ItemFactory where T : new() which means T should have a constructor
It must be last parameter if there are multiple constraints
public class ItemFactory2where T : IComparable, new()
RULE OF THUMB:
Other than removing
warning, ‘new’ does nothing!!
Reference:
http://msdn.microsoft.com/en-us/library/51y09td4.aspx
No comments :
Post a Comment
What are your thoughts on this post? Did you like it?