static void Main()
{
TestToString testToString = new TestToString();
Console.WriteLine(testToString);
}
public class TestToString
{
public string Engine { get; set; } = "V8";
public string Tires { get; set; } = "Low-profile tires";
public string Color { get; set; } = "Red";
public override string ToString()
{
return $"Engine:{Engine}, Tires:{Tires}, Color:{Color}";
}
}
출력결과
Engine:V8, Tires:Low-profile tires, Color:Red
- ToString() 메서드는 C#에서 객체를 문자열로 표현할 때 사용되는 메서드
- 만약 ToString()을 오버라이드(재정의)하지 않으면, 기본적으로 다음과 같이 클래스 이름을 반환한다.
TestToString obj = new TestToString();
Console.WriteLine(obj.ToString());
// 출력 예시: "TestToString"
'프로그래밍 > C#' 카테고리의 다른 글
[C#] DebuggerDisplay 어트리뷰트 (0) | 2025.05.09 |
---|---|
[C#] Action (0) | 2025.04.21 |
[C#] Json에서 데이터 읽기 (jsonconvert) (0) | 2025.03.13 |
[C#] System.String 클래스에서 많이 사용되는 메서드 (1) | 2025.02.21 |
[C#] 팩토리 패턴 (0) | 2025.01.03 |