Programming/C#
[Programming/C#] 프로퍼티와 생성자
scii
2020. 9. 14. 00:11
프로퍼티를 이용한 초기화는 다음과 같다.
클래스이름 인스턴스 = new 클래스이름()
{
프로퍼티1 = 값,
프로퍼티2 = 값,
프로퍼티3 = 값
}
객체를 생성할 때 <프로퍼티 = 값> 목록에 객체의 모든 프로퍼티가 올 필요는 없다. 초기화하고 싶은 프로퍼티만 넣어서 초기화하면 된다.
매개 변수가 있는 생성자를 작성할 때와는 달리 어떤 필드를 생성자 안에서 초기화할지를 미리 고민할 필요가 없다.
using System;
namespace CSharpExample
{
class MainApp
{
class BirthdayInfo
{
public string Name { get; set; }
public DateTime Birthday { get; set; }
public int Age
{
get
{
return new DateTime(DateTime.Now.Subtract(Birthday).Ticks).Year;
}
}
}
static int Main(string[] args)
{
BirthdayInfo birth = new BirthdayInfo()
{
Name = "김연아",
Birthday = new DateTime(1990, 09, 05)
};
Console.WriteLine($"Name : {birth.Name}");
Console.WriteLine($"Birthday : {birth.Birthday.ToShortDateString()}");
Console.WriteLine($"Age : {birth.Age}");
return 0;
}
}
}
/* 결과
Name : 김연아
Birthday : 9/5/1990
Age : 31
*/