this 키워드란?this 키워드는 현재 인스턴스를 가리키는 참조이며, 클래스나 구조체 내부에서 해당 인스턴스의 필드, 메서드, 속성 등에 접근할 때 사용된다.
또한 확장 메서드(Extension Method) 및 생성자 체이닝(Constructor Chaining)에서도 활용된다.
this키워드의 주요 용도는 다음과 같다.
this를 사용하여 인스턴스 멤버 참조기본 예제
using System;
class Person
{
private string name;
public Person(string name)
{
this.name = name; // this를 사용하여 필드와 매개변수 구분
}
public void PrintName()
{
Console.WriteLine($"Name: {this.name}"); // this 사용 가능 (명시적)
}
}
class Program
{
static void Main()
{
Person p = new Person("Alice");
p.PrintName(); // Name: Alice 출력
}
}
this.name을 사용하면 클래스 필드와 메서드 매개변수를 명확하게 구분할 수 있다.this를 생략해도 되지만, 가독성을 위해 사용하는 것이 일반적이다.this를 사용한 생성자 체이닝 (Constructor Chaining)this()를 사용할 수 있다.생성자 체이닝 예제
using System;
class Car
{
public string Brand { get; set; }
public string Model { get; set; }
// 기본 생성자
public Car() : this("Unknown", "Unknown") // 다른 생성자 호출
{
Console.WriteLine("Default constructor called.");
}
// 매개변수를 받는 생성자
public Car(string brand, string model)
{
this.Brand = brand;
this.Model = model;
Console.WriteLine($"Car Created: {Brand} {Model}");
}
}
class Program
{
static void Main()
{
Car car1 = new Car(); // Default constructor 호출 -> Car Created: Unknown Unknown 출력
Car car2 = new Car("Tesla", "Model S"); // Car Created: Tesla Model S 출력
}
}
출력
Default constructor called.
Car Created: Unknown Unknown
Car Created: Tesla Model S
this("Unknown", "Unknown")를 사용하면, 다른 생성자를 호출할 수 있다.this를 사용한 확장 메서드 (Extension Method)this키워드를 사용하여 특정 타입에 새로운 메서드를 추가할 수 있다.확장 메서드 예제
using System;
static class StringExtensions
{
public static int WordCount(this string str) // this를 사용하여 string 확장
{
return str.Split(new char[] { ' ', '.', '?' }, StringSplitOptions.RemoveEmptyEntries).Length;
}
}
class Program
{
static void Main()
{
string sentence = "Hello world! This is C#.";
Console.WriteLine(sentence.WordCount()); // 5 출력
}
}
this string str을 사용하여 string 클래스에 WordCount() 메서드를 추가한 것처럼 사용이 가능하다.this를 사용힌 인덱서(Indexer) 참조클래스가 인덱서(indexer) 를 제공할 경우, this 키워드를 사용하여 개별 요소에 접근할 수 있다.
인덱서 예제
using System;
class MyCollection
{
private int[] data = new int[5];
// 인덱서 정의 (this 사용)
public int this[int index]
{
get { return data[index]; }
set { data[index] = value; }
}
}
class Program
{
static void Main()
{
MyCollection collection = new MyCollection();
collection[0] = 10;
collection[1] = 20;
Console.WriteLine(collection[0]); // 10 출력
Console.WriteLine(collection[1]); // 20 출력
}
}
this를 사용한 인덱서(Indexer) 참조클래스가 인덱서(indexer)를 제공할 경우, this키워드를 사용하여 개별 요소에 접근할 수 있다.
인덱서 예제
using System;
class MyCollection
{
private int[] data = new int[5];
// 인덱서 정의 (this 사용)
public int this[int index]
{
get { return data[index]; }
set { data[index] = value; }
}
}
class Program
{
static void Main()
{
MyCollection collection = new MyCollection();
collection[0] = 10;
collection[1] = 20;
Console.WriteLine(collection[0]); // 10 출력
Console.WriteLine(collection[1]); // 20 출력
}
}
this[int index]를 사용하여 배열처럼 접근 가능한 클래스 구현할 수 있다.this와 base의 차이점| 키워드 | 설명 |
|---|---|
| this | 현재 인스턴스를 참조 |
| base | 부모 클래스의 멤버를 참조 |
using System;
class Parent
{
public void Show() => Console.WriteLine("Parent class");
}
class Child : Parent
{
public void ShowChild()
{
this.Show(); // 현재 클래스에서 상속받은 메서드 호출
base.Show(); // 부모 클래스의 메서드 호출
}
}
class Program
{
static void Main()
{
Child child = new Child();
child.ShowChild();
}
}
this.Show(); 와 base.Show(); 모두 같은 Show()를 호출하지만,base는 부모 클래스의 메서드를 명확하게 호출하는 역할을 한다.| 개념 | 설명 |
|---|---|
this 기본 사용 | 현재 인스턴스의 필드, 속성, 메서드에 접근 |
| 생성자 체이닝 | this()를 사용하여 같은 클래스의 다른 생성자 호출 가능 |
| 확장 메서드 | this를 사용하여 기존 클래스에 새 메서드를 추가 |
| 인덱서 | this를 사용하여 배열처럼 개별 요소 접근 가능 |
this vs base | this는 현재 클래스, base는 부모 클래스 참조 |
즉, this는 현재 객체를 기리키는 중요한 키워드다.