c# 3.0의 자동 구현 속성 사용 시, 초기값을 부여하는 간편 구문이 아래와 같은 형태로 제공된다.
public string PropertyName {get; set;} = "Initial Value"l;
✍ 샘플 코드
class Test
{
static void Main(string[] args)
{
Person person = new Person();
Console.WriteLine(person.Name);
person.Name = "Jinny";
Console.WriteLine(person.Name);
Console.WriteLine(person.Nation);
person.Nation = "USA";
Console.WriteLine(person.Nation);
Console.WriteLine(person.Education);
//person.Education = "University";
//읽기 전용이므로 할당할 수 없습니다.
//생성자에서만 조작할 수 있다.
Console.WriteLine(person.Job);
//person.Job = "Designer";
//읽기 전용이므로 할당할 수 없습니다.
//생성자에서만 조작할 수 있다.
}
}
class Person
{
//Nation이 컴파일되면 Name과 같은 형태로 컴파일 된다.
public string Name { get; set; }
public Person()
{
this.Name = "No Name";
}
public string Nation { get; set; } = "Korea";
//Education이 컴파일되면 Job과 같은 형태로 컴파일 된다.
//set 설정자 메서드를 제거하면 readonly 속성으로 정의한 것과 같게 된다.
public string Education { get; } = "HighSchool";
private readonly string job = "Programmer";
public string Job
{
get { return job; }
}
}