내가쓰는 C# 문법

또는 괜찮아서 도입을 하려고하는데 아직 익숙하지 않은 것들 포함하여 정리

당연하지만 제한을 걸 수 있는 문법을 많이 도입

Property: get, set, init(9.0)

value라는 암묵적 매개변수를 통해 전달된 값을 필드에 할당한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class Person
{
    private string _name;

    public string Name
    {
        get { return _name; }
        set 
        { 
            if (!string.IsNullOrEmpty(value))
            {
                _name = value; 
            }
        }
    }
}

init 접근자 (Init-only Setter)

생성자 또는 객체 초기화 구문({})을 통해서만 값을 할당

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class Person
{
    // get만 사용하면 생성자에서만 초기화 가능
    public string FirstName { get; } 
    
    // init을 사용하면 객체 초기화 구문에서도 초기화 가능
    public string LastName { get; init; } 

    public Person(string firstName)
    {
        FirstName = firstName;
    }
}

// 사용 예시
var person = new Person("John") 
{
    LastName = "Doe" // 객체 초기화 시점에만 할당 가능
};

Console.WriteLine($"{person.FirstName} {person.LastName}"); // "John Doe" 출력

// person.LastName = "Smith"; // 컴파일 오류: init 전용 속성이므로 할당 불가

파라미터 한정자: out, ref

ref는 생략

1
2
3
4
5
6
7
8
9
void GetValue(out int result)
{
    result = 100;
}

// 사용 예시
int myResult; // 초기화할 필요 없음
GetValue(out myResult);
Console.WriteLine("Result: " + myResult); 

C# 7.0에서 쓰는 out 변수를 인라인으로 선언은 사용하지 않는다. (조건문 안에서 같이 변수 lifecycle을 일부러 줄이기 위한게 아닌이상)

1
2
3
4
if (int.TryParse("123", out int parsedValue))
{
    Console.WriteLine("Parsed: " + parsedValue);
}

readonly

생략

8.0

switch expression

1
2
3
4
5
6
7
8
double area = shape switch 
{
    null        => 0,
    Line _      => 0,
    Rectangle r => r.Width * r.Height,
    Circle c    => Math.PI * c.Radius * c.Radius,
    _           => throw new ArgumentException()
};

switch의 간편화 및 변수에 바로 초기화까지 할 수 있어 편리

using 선언

1
2
3
4
5
6
    using (var reader = new StreamReader("src.txt"))
    { 
        string data = reader.ReadToEnd();
        Debug.WriteLine(data);
    }  // 여기서 Dispose() 호출

범위 한정 및 객체의 lifeCycle을 확실하게 구분

record

1
2
3
4
5
6
7
8
9
public record Person
{
    public string Name { get; }
    public int Age { get; }

    public Person(string name, int age)
        => (Name, Age) = (name, age);
}

readonly용으로만 사용되는 객체 타입을 만들고싶을때

extension 메소드

1
2
3
4
5
6
7
8
public static class MyStringExtension
{
  public static string RemoveL(this string str)
  {
    // str의 문자열 중 'L'을 삭제하는 코드 구현
    return str.Replace("L", "");
  }
}
Posted 2025-09-09