Finalizer
以下のようなコード。
using System; namespace Finalizer { class Sample:IDisposable { public Sample() { Console.WriteLine("私、産まれました!"); } ~Sample() { Console.WriteLine("私、消えます"); } public void Dispose() { Console.WriteLine("私、Disposeされました!"); } } class Program { static void Main(string[] args) { var a = new Sample(); Console.WriteLine($"a of {a} is here"); a = null; GC.Collect(); using var b = new Sample(); Console.WriteLine($"b of {b} is here!"); } } }
record
不変のクラスとなるrecordを使う方法も紹介されています。
using System; namespace Record { public record ProductInfo(string Name, int Price); class Program { private static void Dump(ProductInfo info) { Console.WriteLine($"{info.Name}: {info.Price}yen"); } static void Main(string[] args) { var info = new ProductInfo("Coffee", 120); Dump(info); var info2 = info with {Price = 130}; Dump(info2); } } }