C# this 키워드 마스터하기: 용법과 실전 예제
C# this 키워드 마스터하기
간결한 설명과 실전 코드 샘플로 다재다능한 C# this 키워드를 탐구합니다.
C#에서 this는 클래스의 현재 인스턴스를 가리킵니다. 인스턴스 멤버와 메서드 매개변수 구별, 오버로드된 생성자 호출, 현재 객체 타 메서드 전달, 인덱서 선언에 필수적.
using System;
namespace ThisKeyword {
class Test {
int num;
Test(int num) {
// this.num은 인스턴스 필드 참조
this.num = num;
Console.WriteLine("object of this: " + this);
}
static void Main(string[] args) {
Test t1 = new Test(4);
Console.WriteLine("object of t1: " + t1);
Console.ReadLine();
}
}
}
출력
object of this: ThisKeyword.Test
object of t1: ThisKeyword.Test
t1과 this가 같은 인스턴스 참조하므로 문자열 표현 일치.
동명 변수 구별
인스턴스 필드와 매개변수 이름이 같을 수 있지만, this 없으면 컴파일러가 매개변수로 간주해 필드는 건드리지 않음.
using System;
namespace ThisKeyword {
class Test {
int num;
Test(int num) {
num = num; // 매개변수에 자기 자신 대입, 필드는 기본값(0) 유지
}
static void Main(string[] args) {
Test t1 = new Test(4);
Console.WriteLine("value of num: " + t1.num);
Console.ReadLine();
}
}
}
출력
0
출력이 0인 이유는 대입이 필드에 영향 주지 않기 때문. this로 모호성 해결:
using System;
namespace ThisKeyword {
class Test {
int num;
Test(int num) {
// this.num은 인스턴스 필드 참조
this.num = num;
}
static void Main(string[] args) {
Test t1 = new Test(4);
Console.WriteLine("value of num: " + t1.num);
Console.ReadLine();
}
}
}
출력
value of num: 4
this로 생성자 체이닝 (Constructor Chaining)
클래스에 여러 생성자 제공 시 한 생성자가 다른 생성자 호출해 초기화 로직 중앙화 가능. 생성자 시그니처 뒤 콜론(:)과 this로 달성.
using System;
namespace ThisKeyword {
class Test {
Test(int num1, int num2) {
Console.WriteLine("Constructor with two parameters");
}
// 두 매개변수 생성자 호출
Test(int num) : this(33, 22) {
Console.WriteLine("Constructor with one parameter");
}
public static void Main(string[] args) {
Test t1 = new Test(11);
Console.ReadLine();
}
}
}
출력
Constructor with two parameters
Constructor with one parameter
한 매개변수 생성자가 먼저 두 매개변수 생성자 실행 후 자체 본문 계속. 이 패턴을 생성자 체이닝이라 하며 초기화 로직을 DRY(Don't Repeat Yourself)하게 유지.
현재 인스턴스를 메서드에 전달
메서드가 호출한 객체에서 동작해야 할 때 this를 인수로 전달해 의도 명시.
using System;
namespace ThisKeyword {
class Test {
int num1;
int num2;
Test() {
num1 = 22;
num2 = 33;
}
// Test 인스턴스 받는 메서드
void PassParameter(Test t) {
Console.WriteLine("num1: " + t.num1);
Console.WriteLine("num2: " + t.num2);
}
void Display() {
// 현재 인스턴스 전달
PassParameter(this);
}
public static void Main(string[] args) {
Test t1 = new Test();
t1.Display();
Console.ReadLine();
}
}
}
출력
num1: 22
num2: 33
this가 호출 인스턴스 나타내므로 메서드가 private 필드 안전 접근 가능.
this로 인덱서(Indexer) 선언
인덱서로 객체를 배열처럼 인덱싱 가능. this 키워드가 인덱서 시그니처 선언.
using System;
namespace ThisKeyword {
class Student {
private string[] names = new string[3];
// 인덱서 선언
public string this[int index] {
get { return names[index]; }
set { names[index] = value; }
}
}
class Program {
public static void Main() {
Student s = new Student();
s[0] = "Ram";
s[1] = "Shyam";
s[2] = "Gopal";
for (int i = 0; i < 3; i++) {
Console.WriteLine(s[i]);
}
}
}
}
출력
Ram
Shyam
Gopal
private names 배열을 인덱서로 접근, 캡슐화 유지하며 배열 같은 문법 제공.
인덱서 더 보기: 마이크로소프트 공식 문서 C# 인덱서.