Skip to content

ErcanOPAK.com

  • ASP.Net WebForms
  • ASP.Net MVC
  • C#
  • SQL
  • MySQL
  • PHP
  • Devexpress
  • Reportviewer
  • About
C#

What does the word ‘new’ mean exactly in C#?

- 22.03.20 | 29.03.20 - ErcanOPAK

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.

Reference

Related posts:

How to run code if not in Debug Mode in C#
How to trim whitespaces between characters in C#
Convert List to List in one line in C#
How to add placeholder to Multiple Selection DropDownList in Asp.Net MVC
Converting a List to a comma separated string in C#
Post Views: 27

Post navigation

Determine If string contains more than 1 value in C#
Book Suggestions: The Goal & The Phoenix Project

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

April 2021
M T W T F S S
 1234
567891011
12131415161718
19202122232425
2627282930  
« Jan    

Most Viewed Posts

  • Get the First and Last Word from a String or Sentence in SQL (243)
  • How to use Map Mode for Vertical Scroll Mode in Visual Studio (194)
  • How to make some specific word(s) Bold or Underline in ReportViewer (187)
  • How to solve “Response.Redirect cannot be called in a Page callback” for DevExpress Components (183)
  • Confirm before process with ASPxButton in Devexpress (172)
  • ASPxGridView – Disable CheckBox based on condition in GridViewCommandColumn (170)
  • Find numbers with more than two decimal places in SQL (168)
  • Devexpress ASPxGridview Column Grouping in Code (164)
  • DATEADD Function in SQL (163)
  • Tense Changes When Using Reported Speech (160)

Recent Posts

  • How to check for ‘IS NOT NULL’ And ‘IS NOT EMPTY’ string in SQL
  • How to auto-scroll or manually to end of div when data is added
  • Filter Rows By Max Date in SQL
  • How to Validate a DateTime in C#?
  • Convert comma separated string into a List in C#
  • Converting a List to a comma separated string in C#
  • How to add placeholder to Multiple Selection DropDownList in Asp.Net MVC
  • How to use toFixed() for Float numbers in Javascript
  • Convert List to List in one line in C#
  • How to use column search in datatable when responsive is false

Recent Posts

  • How to check for ‘IS NOT NULL’ And ‘IS NOT EMPTY’ string in SQL
  • How to auto-scroll or manually to end of div when data is added
  • Filter Rows By Max Date in SQL
  • How to Validate a DateTime in C#?
  • Convert comma separated string into a List in C#

Most Viewed Posts

  • Get the First and Last Word from a String or Sentence in SQL (243)
  • How to use Map Mode for Vertical Scroll Mode in Visual Studio (194)
  • How to make some specific word(s) Bold or Underline in ReportViewer (187)
  • How to solve “Response.Redirect cannot be called in a Page callback” for DevExpress Components (183)
  • Confirm before process with ASPxButton in Devexpress (172)

Social

  • ErcanOPAK.com
  • GoodReads
  • LetterBoxD
  • Linkedin
  • The Blog
  • Twitter

powered by XBlog Plus WordPress Theme