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:
- public class Author
- {
- public Author()
- {
- }
- public Author(string firstName, string lastName, int rank)
- {
- FirstName = firstName;
- LastName = lastName;
- Rank = rank;
- }
- public int num;
- public string FirstName { get; set; }
- public string LastName { get; set; }
- public int Rank { get; set; }
- new public string FullName()
- {
- return string.Format("{0} {1}", FirstName, LastName);
- }
- }
Initialize a class:
-
- var author = new Author();
Initialize collections:
-
-
- var authors = new List<Author>();
Create an instance of anonymous types:
-
-
- var authorAnonymous = from auth in authors
- 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.
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:
- Public struct MyStruct
- {
- Public MyStruct() { }
- 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:
- public class BaseAuthor
- {
- public class Author
- {
- public virtual string FullName()
- {
- return string.Format("{0} {1}", FirstName, LastName);
- }
- }
- }
- public class DerivedAuthor:BaseAuthor
- {
- new public override string FullName()
- {
- return string.Format("{0} {1}", FirstName, LastName);
- }
- }
Here we are hiding the base class in the derived class:
- public class BaseAuthor
- {
- public class Author
- {
- public virtual string FullName()
- {
- return string.Format("{0} {1}", FirstName, LastName);
- }
- }
- }
- public class DerivedAuthor:BaseAuthor
- {
- new public class Author
- {
- public virtual string FullName()
- {
- return string.Format("{0} {1}", FirstName, LastName);
- }
- }
- }
Now, we can invoke the parent and derived classes as:
- Author = new Author();
-
- 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.
- public class AuthorFactory<T> where T : new()
- {
- public T GetAuthor()
- {
- return new T();
- }
- }
Now, we can initialize the preceding as:
- var factoryAuth = new AuthorFactory<Author>();
To get an instance of the preceding type:
- var objAuth = factoryAuth.GetAuthor();
If using multiple constraints then the "new" constraint must be last:
- public class AuthorFactoryComparable<T>
- where T : IComparable, new()
- {
-
- }
Conclusion
We have discussed the "new" keyword of C#. It is defined as:
- an operator
- a modifier
- a constraint