Target-Typed new Expressions
Simplify object creation with target typing.
Target-Typed new
Since C# 9, you can write Type x = new(); and omit the type after new when the target type is known.
using System;
using System.Collections.Generic;
class Program {
static void Main() {
List<int> numbers = new();
numbers.Add(1);
Console.WriteLine(numbers.Count);
}
}Removing Redundancy
When the variable already states the type, repeating it after new is noise. The empty new() removes it.
using System;
using System.Text;
class Program {
static void Main() {
StringBuilder sb = new();
sb.Append("Hi");
Console.WriteLine(sb.ToString());
}
}All lessons in this course
- Local Variable Type Inference with var
- When to Avoid var
- The dynamic Type
- Target-Typed new Expressions