"new" Keyword of C#

Updated 8/29/2018 - Formatted 
 
Abstract
 
This article explains the "new" keyword in C#.
 
Introduction
 
In C# there are many operators and keywords available.
 
Today, we will explain "new". We can divide the use of the "new" keyword into the following uses:
  • An operator
  • A modifier
  • A constraint
We will discuss all the preceding in this article.
 
new as an operator
 
It is used to create objects and invoke a constructor.
 
Using the "new" operator, we can create an object or instantiate an object, in other words with the "new" operator we can invoke a constructor.
 
Let's create a class for example:
  1. public class Author  
  2. {  
  3. public Author()  
  4. {  
  5. }  
  6. public Author(string firstName, string lastName, int rank)  
  7. {  
  8. FirstName = firstName;  
  9. LastName = lastName;  
  10. Rank = rank;  
  11. }  
  12. public int num;  
  13. public string FirstName { getset; }  
  14. public string LastName { getset; }  
  15. public int Rank { getset; }  
  16. new public string FullName()  
  17. {  
  18. return string.Format("{0} {1}", FirstName, LastName);  
  19. }  
  20. }  
Initialize a class:
  1. //We can instantiate or invoke a construtor  
  2. var author = new Author();  
Initialize collections:
  1. //we can initialize a collection  
  2.   
  3. var authors = new List<Author>();  
Create an instance of anonymous types:
  1. //anonymous can also be initialized by new  
  2.   
  3. var authorAnonymous = from auth in authors  
  4. select new { FullName = string.Format("{0} {1}", auth.FirstName, auth.LastName) };  
An important thing to notice is that with the use of the "new" operator we can invoke the default constructor of a value type.
  1. Int num = new int(); //think about this 
Interesting point
 
We cannot overload the "new" operator.
 
It will throw an exception if it fails to allocate memory. Think of a scenario where it does fail.
 
Declaring a default constructor for a struct results in an error. The reason is that every value type implicitly invokes its default constructor.
 
The following is wrong:
  1. Public struct MyStruct  
  2. {  
  3. Public MyStruct() { }  
  4. Public int num1;  

The "new" operator only assigns the memory and does not destroy memory that depends upon the scope.
 
Value-types objects, like int, are created on the stack and reference type objects like "Author" are created on the heap.
 
The new as a modifier
 
It hides a member that is inherited from a base class.
 
So, what does this mean?
 
It simply replaces the base class version.
 
What happens if I do not use "new"?
 
So, in this case your code runs perfectly with a compiler warning that you are hiding without using the "new" modifier.
 
There will be an error if you use both "new" and "override" on the same member.
 
The following is wrong:
  1. public class BaseAuthor  
  2. {  
  3. public class Author  
  4. {  
  5. public virtual string FullName()  
  6. {  
  7. return string.Format("{0} {1}", FirstName, LastName);  
  8. }  
  9. }  
  10. }  
  11. public class DerivedAuthor:BaseAuthor  
  12. {  
  13. new public override string FullName()  
  14. {  
  15. return string.Format("{0} {1}", FirstName, LastName);  
  16. }  

Here we are hiding the base class in the derived class:
  1. public class BaseAuthor  
  2. {  
  3. public class Author  
  4. {  
  5. public virtual string FullName()  
  6. {  
  7. return string.Format("{0} {1}", FirstName, LastName);  
  8. }  
  9. }  
  10. }  
  11. public class DerivedAuthor:BaseAuthor  
  12. {  
  13. new public class Author  
  14. {  
  15. public virtual string FullName()  
  16. {  
  17. return string.Format("{0} {1}", FirstName, LastName);  
  18. }  
  19. }  
  20. }  
Now, we can invoke the parent and derived classes as:
  1. Author = new Author();  
  2.   
  3. BaseAuthor.Author = new BaseAuthor.Author(); 
"new" as a Constraint
 
It specifies that the generic type must have a public parameterless constructor. The "new" constraint cannot be used on an abstract type.
  1. public class AuthorFactory<T> where T : new()  
  2. {  
  3. public T GetAuthor()  
  4. {  
  5. return new T();  
  6. }  
  7. }  
Now, we can initialize the preceding as:
  1. var factoryAuth = new AuthorFactory<Author>();  
To get an instance of the preceding type:
  1. var objAuth = factoryAuth.GetAuthor();  
If using multiple constraints then the "new" constraint must be last:
  1. public class AuthorFactoryComparable<T>  
  2. where T : IComparable, new()  
  3. {  
  4. //logic goes here  

Conclusion
 
We have discussed the "new" keyword of C#. It is defined as:
  • an operator
  • a modifier
  • a constraint


Recommended Free Ebook
Similar Articles