C# New (How It Works For Developers)

The new operator keyword in C# is versatile, serving multiple essential functions in the language. From instantiating objects to hiding inherited members, understanding their applications is crucial for effective C# development. This guide explores the new keyword's various uses, providing clear examples to illustrate its power and flexibility. We'll also explore the IronPDF library later in this guide.

Introduction to Object Instantiation

Object instantiation is the process where the new operator creates an instance of a class or struct. In C#, this is primarily achieved using the new keyword, which calls the constructor of the specified type and allocates memory for the new object.

Creating Instances with new

To create an instance of an object, the new operator is followed by the class name and a pair of parentheses. If the class has a constructor that takes parameters, arguments must be supplied within these parentheses.

public class Book {
    public string Title { get; set; }
    public Book(string title) {
        Title = title;
    }
}
Book book = new Book("The C# Programming Language");
public class Book {
    public string Title { get; set; }
    public Book(string title) {
        Title = title;
    }
}
Book book = new Book("The C# Programming Language");
Public Class Book
	Public Property Title() As String
	Public Sub New(ByVal title As String)
		Me.Title = title
	End Sub
End Class
Private book As New Book("The C# Programming Language")
VB   C#

Default and Parameterless Constructors

A default constructor is provided by C# if no constructors are explicitly defined in a class. However, once a constructor with parameters is defined, a parameterless constructor must be explicitly declared if needed.

public class ExampleClass {
    // Parameterless constructor
    public ExampleClass() {
        // Initialization code here
    }
}
public class ExampleClass {
    // Parameterless constructor
    public ExampleClass() {
        // Initialization code here
    }
}
Public Class ExampleClass
	' Parameterless constructor
	Public Sub New()
		' Initialization code here
	End Sub
End Class
VB   C#

Advanced Object Creation Techniques

In C#, object creation isn't just about instantiating classes; it's a gateway to leveraging the language's powerful features for more efficient, readable, and concise code. Here, we explore advanced techniques like working with arrays, utilizing types, and employing object initializers to streamline your coding efforts.

Arrays and Collections

Creating arrays of a specific array type in C# is a fundamental skill, but it's the nuances that elevate your coding capabilities. Using the new keyword, you can instantiate arrays, specifying their type and the number of elements they should contain. This is crucial for managing collections of variables in a structured way. Beyond basic arrays, new facilitates the creation of multidimensional and jagged arrays, accommodating complex data structures.

// Single-dimensional array
int[] numbers = new int[5]; // Initializes an array for 5 integers
// Multidimensional array
int[,] matrix = new int[3, 2]; // A 3x2 matrix
// Jagged array (an array of arrays)
int[][] jaggedArray = new int[3][];
jaggedArray[0] = new int[4]; // First row has 4 columns
jaggedArray[1] = new int[5]; // Second row has 5 columns
jaggedArray[2] = new int[3]; // Third row has 3 columns
// Single-dimensional array
int[] numbers = new int[5]; // Initializes an array for 5 integers
// Multidimensional array
int[,] matrix = new int[3, 2]; // A 3x2 matrix
// Jagged array (an array of arrays)
int[][] jaggedArray = new int[3][];
jaggedArray[0] = new int[4]; // First row has 4 columns
jaggedArray[1] = new int[5]; // Second row has 5 columns
jaggedArray[2] = new int[3]; // Third row has 3 columns
' Single-dimensional array
Dim numbers(4) As Integer ' Initializes an array for 5 integers
' Multidimensional array
Dim matrix(2, 1) As Integer ' A 3x2 matrix
' Jagged array (an array of arrays)
Dim jaggedArray(2)() As Integer
jaggedArray(0) = New Integer(3){} ' First row has 4 columns
jaggedArray(1) = New Integer(4){} ' Second row has 5 columns
jaggedArray(2) = New Integer(2){} ' Third row has 3 columns
VB   C#

Anonymous Types

Anonymous types shine in scenarios requiring temporary data structures without the overhead of declaring a formal class. By using new with a property initializer syntax, you can create objects on the fly. This feature is incredibly useful for LINQ queries where you need to select a subset of properties from a larger object or for quickly grouping data without creating a specific type.

var person = new { Name = "Alice", Age = 30 };
Console.WriteLine($"Name: {person.Name}, Age: {person.Age}");
// In LINQ
var results = from p in people
              select new { p.Name, p.Age };
var person = new { Name = "Alice", Age = 30 };
Console.WriteLine($"Name: {person.Name}, Age: {person.Age}");
// In LINQ
var results = from p in people
              select new { p.Name, p.Age };
Dim person = New With {
	Key .Name = "Alice",
	Key .Age = 30
}
Console.WriteLine($"Name: {person.Name}, Age: {person.Age}")
' In LINQ
Dim results = From p In people
	Select New With {
		Key p.Name,
		Key p.Age
	}
VB   C#

Object Initializers

An object initializer represents a syntactic convenience, allowing you to create an instance of a class and immediately set its properties without calling a constructor with parameters. This not only makes the code more readable but also reduces the likelihood of errors by eliminating the need for multiple constructors for different scenarios. Object initializers are particularly handy when working with complex objects, enabling you to set only the properties you need.

public class Rectangle {
    public int Width { get; set; }
    public int Height { get; set; }
    public Point Location { get; set; }
}
Rectangle rect = new Rectangle {
    Width = 100,
    Height = 50,
    Location = new Point { X = 0, Y = 0 }
};
public class Rectangle {
    public int Width { get; set; }
    public int Height { get; set; }
    public Point Location { get; set; }
}
Rectangle rect = new Rectangle {
    Width = 100,
    Height = 50,
    Location = new Point { X = 0, Y = 0 }
};
Public Class Rectangle
	Public Property Width() As Integer
	Public Property Height() As Integer
	Public Property Location() As Point
End Class
Private rect As New Rectangle With {
	.Width = 100,
	.Height = 50,
	.Location = New Point With {
		.X = 0,
		.Y = 0
	}
}
VB   C#

Local Functions and Lambda Expression

C# supports local functions and lambda expressions, enhancing the flexibility and conciseness of the code.

Local Function

A local function is a method defined within the scope of another method, serving as a powerful tool for organizing code and encapsulating functionality.

public void PerformOperation() {
    int LocalFunction(int x) {
        return x * x;
    }
    Console.WriteLine(LocalFunction(5)); // Output: 25
}
public void PerformOperation() {
    int LocalFunction(int x) {
        return x * x;
    }
    Console.WriteLine(LocalFunction(5)); // Output: 25
}
Public Sub PerformOperation()
'INSTANT VB TODO TASK: Local functions are not converted by Instant VB:
'	int LocalFunction(int x)
'	{
'		Return x * x;
'	}
	Console.WriteLine(LocalFunction(5)) ' Output: 25
End Sub
VB   C#

C# New (How It Works For Developers): Figure 1 - Local Function Output

Lambda Expressions

Lambda expression provides a concise way to write inline expressions or methods without the need for explicit delegate types.

Func<int, int> square = x => x * x;
Console.WriteLine(square(5)); // Output: 25
Func<int, int> square = x => x * x;
Console.WriteLine(square(5)); // Output: 25
Dim square As Func(Of Integer, Integer) = Function(x) x * x
Console.WriteLine(square(5)) ' Output: 25
VB   C#

C# New (How It Works For Developers): Figure 2 - Lambda Output

Using 'new' in Inheritance

In class inheritance, new can hide inherited members, allowing derived classes to introduce a member with the same name as those in their base classes.

Hiding Inherited Members

Using new to hide a member in a derived class does not override the same member; instead, it introduces a new member that is distinct from the base class version.

public class BaseClass {
    public void Display() {
        Console.WriteLine("Base display");
    }
}
public class DerivedClass : BaseClass {
    public new void Display() {
        Console.WriteLine("Derived display");
    }
}
public class BaseClass {
    public void Display() {
        Console.WriteLine("Base display");
    }
}
public class DerivedClass : BaseClass {
    public new void Display() {
        Console.WriteLine("Derived display");
    }
}
Public Class BaseClass
	Public Sub Display()
		Console.WriteLine("Base display")
	End Sub
End Class
Public Class DerivedClass
	Inherits BaseClass

	Public Shadows Sub Display()
		Console.WriteLine("Derived display")
	End Sub
End Class
VB   C#

C# New (How It Works For Developers): Figure 3 - Hiding Inherited Member Output

Understanding new with Generics

Generics introduce a level of abstraction in C# programming, allowing developers to design classes, methods, and interfaces that operate on generic types. When paired with the new keyword, generics empower you to instantiate types dynamically, further enhancing code reusability and reducing redundancy.

The new() Constraint in Generic Type

The new() constraint is a cornerstone of using new with generics, specifying that a type argument in a generic class or method must have a public parameterless constructor. This constraint enables you to create instances of your generic type within the class or method, making your generic classes and methods more flexible and powerful.

public class Container<T> where T : new() {
    public T CreateItem() {
        return new T(); //new T
    }
}
public class Container<T> where T : new() {
    public T CreateItem() {
        return new T(); //new T
    }
}
public class Container(Of T) where T : New() {
	public T CreateItem() { Return New T(); }
}
VB   C#

In this example, Containercan create instances of T, provided T has a parameterless constructor. This capability is invaluable when developing libraries or frameworks that require object creation but don't know the specific types ahead of time.

Introduction to IronPDF

C# New (How It Works For Developers): Figure 4 - IronPDF

IronPDF stands out as a powerful tool that uses C#’s capabilities to work with PDF files. By incorporating IronPDF, developers can programmatically create new PDF documents from HTML strings, files, or URLs, manipulate existing PDFs, and extract content, all through the familiar syntax of C# and leveraging the new keyword for object instantiation.

Code Example

using IronPdf;
using System;
namespace IronPdfExample
{
    class Program
    {
//static void main
        static void Main(string[] args)
        {
            IronPdf.License.LicenseKey = "License-Key";
            // Create a new PDF document from HTML content
            var renderer = new ChromePdfRenderer();
            var pdf = renderer.RenderHtmlAsPdf("<h1>Hello, World!</h1><p>This is a PDF generated from HTML using IronPDF.</p>");
            // Save the PDF to a file
            string filePath = "HelloWorld.pdf";
            pdf.SaveAs(filePath);
            // Confirmation message
            Console.WriteLine($"PDF file has been generated at: {Environment.CurrentDirectory}\\{filePath}");
        }
    }
}
using IronPdf;
using System;
namespace IronPdfExample
{
    class Program
    {
//static void main
        static void Main(string[] args)
        {
            IronPdf.License.LicenseKey = "License-Key";
            // Create a new PDF document from HTML content
            var renderer = new ChromePdfRenderer();
            var pdf = renderer.RenderHtmlAsPdf("<h1>Hello, World!</h1><p>This is a PDF generated from HTML using IronPDF.</p>");
            // Save the PDF to a file
            string filePath = "HelloWorld.pdf";
            pdf.SaveAs(filePath);
            // Confirmation message
            Console.WriteLine($"PDF file has been generated at: {Environment.CurrentDirectory}\\{filePath}");
        }
    }
}
Imports IronPdf
Imports System
Namespace IronPdfExample
	Friend Class Program
'static void main
		Shared Sub Main(ByVal args() As String)
			IronPdf.License.LicenseKey = "License-Key"
			' Create a new PDF document from HTML content
			Dim renderer = New ChromePdfRenderer()
			Dim pdf = renderer.RenderHtmlAsPdf("<h1>Hello, World!</h1><p>This is a PDF generated from HTML using IronPDF.</p>")
			' Save the PDF to a file
			Dim filePath As String = "HelloWorld.pdf"
			pdf.SaveAs(filePath)
			' Confirmation message
			Console.WriteLine($"PDF file has been generated at: {Environment.CurrentDirectory}\{filePath}")
		End Sub
	End Class
End Namespace
VB   C#

In this class Program snippet, new IronPdf.ChromePdfRenderer() demonstrates the instantiation of an IronPDF renderer object. This object is then used to create a new PDF from an HTML string, showcasing the seamless integration of third-party libraries with C#’s object creation patterns. IronPDF requires the use of the new keyword to initiate its classes, making it a relevant example for developers learning about object instantiation and exploring advanced features of C#.

Output

When you run the program, you'll see the following message on the console:

C# New (How It Works For Developers): Figure 5 - Console Output

And once you open the PDF file, you'll see this:

C# New (How It Works For Developers): Figure 6 - PDF Output

Conclusion

The new keyword in C# is a cornerstone of object-oriented programming, enabling developers to instantiate objects, manage inheritance, and utilize generics with precision and ease. Through practical examples, from creating simple class instances to leveraging advanced features like anonymous types and object initializers, this guide demonstrates the versatility and power of new.

The integration of IronPDF showcases how C# can extend its reach beyond traditional applications, allowing for the generation and manipulation of PDF files through code. IronPDF offers a free trial for developers to explore its features, with licenses starting at $749.