Records and Modern Types
Target-Typed New
Target-typed new lets C# infer the constructed type from the variable type.
Target-Typed New
TargetTypedNew.cs
using System;
record Counter(int Start)
{
public int Next()
{
return Start + 1;
}
public override string ToString()
{
return Start.ToString();
}
}
class Program
{
static void Main()
{
int start = ;
Counter counter = new(start);
int next = counter.Next();
Console.WriteLine($"start={start}");
Console.WriteLine($"next={next}");
}
}
using System;
record Counter(int Start)
{
public int Next()
{
return Start + 1;
}
public override string ToString()
{
return Start.ToString();
}
}
class Program
{
static void Main()
{
int start = ;
Counter counter = new(start);
int next = counter.Next();
Console.WriteLine($"start={start}");
Console.WriteLine($"next={next}");
}
}
using System;
record Counter(int Start)
{
public int Next()
{
return Start + 1;
}
public override string ToString()
{
return Start.ToString();
}
}
class Program
{
static void Main()
{
int start = ;
Counter counter = new(start);
int next = counter.Next();
Console.WriteLine($"start={start}");
Console.WriteLine($"next={next}");
}
}
target-typed new
Target-typed `new` omits the type name when the target type is clear.