728x90
반응형
1. 컬렉션 (List)
using System.Collections.Generic;
List<string> names = new List<string> { "A", "B", "C" };
names.Add("D");
foreach (var name in names)
{
Console.WriteLine(name);
}
C#에서 List<T>는 동적으로 크기가 조정되는 배열입니다.
데이터를 저장하고, 추가하거나 삭제할 수 있습니다.
2. 예외처리 (try - catch)
try
{
int result = 10 / 0; // 예외 발생
}
catch (DivideByZeroException ex)
{
Console.WriteLine("0으로 나눌 수 없습니다: " + ex.Message);
}
프로그램 실행 중 발생할 수 있는 오류를 처리하기 위해 try-catch 블록을 사용합니다.
3. LINQ (Language Integrated Query)
using System.Linq;
int[] numbers = { 1, 2, 3, 4, 5 };
var evenNumbers = numbers.Where(n => n % 2 == 0);
foreach (var num in evenNumbers)
{
Console.WriteLine(num);
}
LINQ는 C#에서 데이터를 쿼리하는 데 사용되는 기능입니다.
컬렉션, 데이터베이스 등에서 데이터를 쉽게 검색할 수 있습니다.
4. 비동기 프로그래밍 (async / await)
public async Task<string> FetchDataAsync()
{
await Task.Delay(2000); // 2초 대기
return "데이터 수신 완료";
}
// 호출 예
var result = await FetchDataAsync();
Console.WriteLine(result);
비동기 프로그래밍을 통해 긴 작업이 완료될 때까지 프로그램이 멈추지 않도록 할 수 있습니다.
async 키워드는 비동기 메서드를 정의하고, await은 비동기 작업이 완료될 때까지 기다립니다.
5. 속성과 접근자 (Properties) / (Accessors)
public class Rectangle
{
private int width;
private int height;
public int Width
{
get { return width; }
set { width = value; }
}
public int Height
{
get { return height; }
set { height = value; }
}
public int Area => Width * Height; // 계산된 속성
}
클래스의 필드에 대한 접근을 제어하기 위해 속성을 사용합니다.
get과 set 접근자를 통해 외부에서 필드에 접근할 수 있습니다.