In C# (and many other languages) you will find that you use new often as it is fundamental to using types and classes. The new keyword does pretty much what it says: it will create a new instance of a class or type, assigning it a location in memory.
Let me try and illustrate this.
Company company;
Here we have created a variable of the Company class, but note that it isn’t assigned to anything. If you try to use this now you will get an exception as it is currently null.
Let’s create a new instance of Company instead:
Company company = new Company();
This line is much more useful. First of all we are assigning the variable company to a new instance of the type Company. The new keyword instructs the application to instantiate a new instance of Company. Note that we are required to add parentheses to the end of the class name as this is calling a special function known as a constructor.
The constructor can contain logic that allows the class to be instantiated to support any desired functionality of the class.
A basic example of a constructor:
public class Company { // Public properties public int CompanyID; public string CompanyName; public List<Employee> Employees; // Constructor public Company() { Employees = new List<Employee>; } ... }
Here, the constructor is being used to instantiate the list of employees to ensure that when using the property that you do not get a NullReferenceException.
You can create multiple constructors, as long as they have unique signatures (the parameters in the constructor cannot match the pattern of parameters in another constructor).
public class Company { // Public properties public int CompanyID; public string CompanyName; public List<Employee> Employees; // Constructor public Company() { Employees = new List<Employee>; } public Company(int companyId) { LoadCompany(companyId); } ... }
You can now see that we’ve got two constructors. Calling new and passing an integer to the constructor will call the second constructor, which in this case will call a function that will load the company data (just an example, you can load data in other ways).
When you want to use this constructor, change your code, simply, to (passing the relevant integer):
Company company = new Company(1337);
One special thing about constructors is that they can be used to do things that you cannot do with an already instantiated class: you can write to readonly properties.
So, whenever you want to create a new instance of a type, you will need to call new. It is a very simple keyword, but is very powerful as it essentially does all of the heavy lifting of object creation for you.
Thanks to Dan Jackson for this great answer.