?. ??=
- Visual Studio 2022
- .Net 6.0
- Console Application
Person? p1 = null;
Person? p2 = new Person("John", 23);
Console.WriteLine(p1?.Name);
Console.WriteLine(p2?.Name);
Console.WriteLine($"p1 is {(p1 ?? new Person("Bob", 12)).ToString()}");
List<Person> pl = new List<Person>();
(pl ??= new List<Person>()).Add(new Person("Jane", 23));
Console.WriteLine($"{pl.Count} : {pl[0].ToString()}");
(pl ??= new List<Person>()).Add(new Person("Sally", 25));
Console.WriteLine($"{pl.Count} : {pl[1].ToString()}");
Console.ReadKey();
class Person
{
public string Name { get; set; }
public int Age { get; set; }
public Person(string name, int age)
{
this.Name = name;
this.Age = age;
}
public override string ToString()
{
return $"{Name}, {Age}";
}
}
'C# > C# Common' 카테고리의 다른 글
Reflection (0) | 2022.09.06 |
---|---|
Generics (0) | 2022.09.04 |
Extension Methods (0) | 2022.09.03 |
LINQ (0) | 2022.09.01 |
Event (0) | 2022.08.30 |