目次
リリース時期
init 専用セッター
public record WeatherObservation
{
public DateTime RecordedAt { get; init; }
public decimal TemperatureInCelsius { get; init; }
public readonly decimal PressureInMillibars = 1000.0m;
public WeatherObservation()
{
TemperatureInCelsius = 10;
PressureInMillibars = 1000.0m;
}
}
public class Features
{
public static void Init専用セッター()
{
var now = new WeatherObservation
{
RecordedAt = DateTime.Now,
TemperatureInCelsius = 20,
};
}
}
Records
public record Person
{
public string LastName { get; }
public string FirstName { get; }
public Person(string first, string last)
=> (FirstName, LastName) = (first, last);
}
public record Teacher : Person
{
public string Subject { get; }
public Teacher(string first, string last, string sub) : base(first, last)
=> Subject = sub;
}
public record Pet(string Name, string Type);
public static void Records()
{
var p1 = new Person("Taro", "Saito");
var p2 = new Person("Taro", "Saito");
Debug.WriteLine($"p1==p2 : {p1 == p2}");
Debug.WriteLine(p1.ToString());
var cat = new Pet("Pochi", "Cat");
var cat2 = cat with { Name = "Tama" };
Debug.WriteLine(cat2.ToString());
var (name, type) = cat2;
Debug.WriteLine($"{type}の{name}。");
}
using System;
using System.Threading.Tasks;
Console.WriteLine("Hello world!");
Console.WriteLine(args.Length);
void m1(string s)
{
Console.WriteLine(s);
}
void m2(string s) => Console.WriteLine(s);
m1("Hoge");
m2("Fuga");
await Task.Delay(1000);
return 0;
public class TopLevelStatements
{
public static void Features()
{
}
}
ターゲットからの new 型推論
Dictionary<string, string> _dic = new();
Dictionary<string, List<(int x, int y)>> _cache = new()
{
{ "A", new() { (1, 1), (2, 2) } },
{ "B", new() { (1, 1), (2, 2) } },
};
public static void ターゲットからのnew型推論()
{
ReturnNew(new());
(int X, int Y) p = new(1, 2);
throw new("This is Exception.");
}
private static List<int> ReturnNew(List<int> list)
{
return new();
}
public static void ラムダ式の引数を破棄()
{
Action<int, int> action = (_, _) =>
{
};
Action<int, int> action2 = (_, _1) =>
{
Console.WriteLine(_);
};
}
ローカル関数への属性適用
public static void ローカル関数への属性適用()
{
[return: NotNullIfNotNull("s")]
string? toLower(string? s) => s?.ToLower();
}
パターンマッチングの拡張機能
public static void パターンマッチングの拡張機能()
{
var x = 80;
if (x is (>= 0 and < 10) or (> 80 and <= 100)) { }
if (x is 80 or > 80) { }
Func<int> func = () => 5;
if (func() is > 0 and < 10) { }
string s = null;
if (s is not null) { }
}
コード置き場
github.com