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:
- //We can instantiate or invoke a construtor
- var author = new Author();
Initialize collections:
- //we can initialize a collection
- var authors = new List<Author>();
Create an instance of anonymous types:
- //anonymous can also be initialized by new
- 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.
- 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:
- 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.

Gaurav Kumar AroraPosted Jan 27, 2015, 7:20 AM
Thanks Michal Habalcik
Michal HabalcikPosted Jan 26, 2015, 2:44 AM
great summary, thanks