728x90
✅ 1. 기본 문법 및 자료형
int number = 10; // 정수형 변수 선언
double pi = 3.14; // 실수형 변수 선언
string name = "Alice"; // 문자열 변수 선언
bool isReady = true; // 불리언 변수 선언
char grade = 'A'; // 문자형 변수 선언
var autoType = 123; // 타입 추론 변수
const int MAX = 100; // 상수 선언
✅ 2. 조건문 & 반복문
if (number > 0) Console.WriteLine("양수"); // if 조건문
else if (number == 0) Console.WriteLine("0");
else Console.WriteLine("음수");
switch (grade) // switch 조건문
{
case 'A': Console.WriteLine("Excellent"); break;
case 'B': Console.WriteLine("Good"); break;
default: Console.WriteLine("Try harder"); break;
}
for (int i = 0; i < 5; i++) // for 반복문
{
Console.WriteLine(i);
}
int j = 0;
while (j < 5) // while 반복문
{
Console.WriteLine(j++);
}
do // 최소 1회 실행 보장
{
Console.WriteLine("한 번은 출력됨");
} while (false);
✅ 3. 배열 및 컬렉션
int[] arr = {1, 2, 3}; // 정수 배열
string[] names = new string[3]; // 문자열 배열 (크기 지정)
List<string> fruits = new List<string>(); // 리스트 선언
fruits.Add("Apple");
fruits.Add("Banana");
Dictionary<string, int> scores = new Dictionary<string, int>(); // 딕셔너리 선언
scores["Alice"] = 90;
foreach (var item in fruits) // foreach 반복문
{
Console.WriteLine(item);
}
✅ 4. 메서드 정의 및 호출
void SayHello() // 반환값 없는 메서드
{
Console.WriteLine("Hello");
}
int Add(int a, int b) // int 반환 메서드
{
return a + b;
}
SayHello();
int result = Add(2, 3);
✅ 5. 클래스 & 객체지향
class Person // 클래스 정의
{
public string Name { get; set; } // 자동 프로퍼티
public int Age { get; set; }
public void Introduce()
{
Console.WriteLine($"이름: {Name}, 나이: {Age}");
}
}
Person p = new Person { Name = "철수", Age = 25 }; // 객체 생성
p.Introduce();
✅ 6. 생성자 & this 키워드
class Student
{
public string Name;
public int Age;
public Student(string name, int age) // 생성자
{
this.Name = name;
this.Age = age;
}
}
✅ 7. 상속 & 오버라이딩
class Animal
{
public virtual void Speak()
{
Console.WriteLine("동물이 말함");
}
}
class Dog : Animal
{
public override void Speak() // 오버라이드
{
Console.WriteLine("멍멍");
}
}
Animal a = new Dog();
a.Speak(); // 멍멍 출력
✅ 8. 인터페이스 & 추상 클래스
interface IPrintable
{
void Print();
}
class Document : IPrintable
{
public void Print()
{
Console.WriteLine("문서 출력");
}
}
abstract class Shape
{
public abstract void Draw(); // 추상 메서드
}
class Circle : Shape
{
public override void Draw()
{
Console.WriteLine("원을 그림");
}
}
✅ 9. 예외 처리
try
{
int x = 0;
int y = 5 / x;
}
catch (DivideByZeroException ex)
{
Console.WriteLine("0으로 나눌 수 없습니다.");
}
finally
{
Console.WriteLine("예외 처리 완료");
}
✅ 10. LINQ 사용 예시
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
var evenNumbers = numbers.Where(n => n % 2 == 0).ToList(); // 짝수 필터
int sum = numbers.Sum(); // 합계
int max = numbers.Max(); // 최댓값
✅ 11. 파일 입출력
File.WriteAllText("test.txt", "Hello"); // 파일 쓰기
string content = File.ReadAllText("test.txt"); // 파일 읽기
Console.WriteLine(content);
✅ 12. 날짜 & 시간
DateTime now = DateTime.Now; // 현재 시간
Console.WriteLine(now.ToString("yyyy-MM-dd HH:mm"));
TimeSpan ts = TimeSpan.FromMinutes(90); // 시간 간격
Console.WriteLine(ts.TotalHours); // 1.5 출력
✅ 13. 비동기 프로그래밍 (async/await)
async Task<string> GetDataAsync()
{
await Task.Delay(1000); // 1초 대기
return "데이터 도착";
}
string result = await GetDataAsync();
Console.WriteLine(result);
✅ 14. 람다식 & 델리게이트
Func<int, int, int> add = (x, y) => x + y; // 람다식 함수
Console.WriteLine(add(3, 4)); // 7
Action sayHi = () => Console.WriteLine("Hi");
sayHi();
✅ 15. Nullable 타입 & Null 병합 연산자
int? x = null;
int y = x ?? 10; // x가 null이면 10
Console.WriteLine(y); // 10 출력
✅ 16. 문자열 다루기
string s = " Hello ";
string trimmed = s.Trim(); // 공백 제거
string upper = s.ToUpper(); // 대문자 변환
bool contains = s.Contains("ell"); // 포함 여부
string[] parts = s.Split(' '); // 공백 기준 분할
✅ 17. 환경 변수 & 콘솔 입력
Console.Write("이름 입력: ");
string name = Console.ReadLine();
Console.WriteLine($"안녕하세요, {name}님");
✅ 18. 정규 표현식
string email = "test@example.com";
bool isEmail = Regex.IsMatch(email, @"^[\w\.-]+@[\w\.-]+\.\w+$");
Console.WriteLine(isEmail); // true
✅ 19. enum 및 switch 활용
enum State { Ready, Playing, GameOver }
State gameState = State.Ready;
switch (gameState)
{
case State.Ready: Console.WriteLine("준비 중"); break;
case State.Playing: Console.WriteLine("플레이 중"); break;
}
✅ 20. 튜플 및 Deconstruction
(string, int) GetUser() => ("철수", 30);
var (username, age) = GetUser();
Console.WriteLine(username); // 철수
✅ 21~30: 클래스 문법
// 21. 클래스 상속 + base 키워드
class Parent {
public Parent(string msg) { Console.WriteLine(msg); }
}
class Child : Parent {
public Child() : base("부모 생성자 호출") {}
}
// 22. static 멤버
class Util {
public static int Square(int x) => x * x;
}
// 23. sealed 클래스 (상속 불가)
sealed class FinalClass { }
// 24. readonly 필드
class Config {
public readonly int MaxValue = 100;
}
// 25. enum 사용
enum Direction { Up, Down, Left, Right }
// 26. indexer 사용
class Collection {
private int[] data = new int[5];
public int this[int index] {
get => data[index];
set => data[index] = value;
}
}
// 27. 구조체 정의
struct Point {
public int X, Y;
public Point(int x, int y) => (X, Y) = (x, y);
}
// 28. record 타입 (불변 객체)
public record Person(string Name, int Age);
// 29. this 키워드 메서드 체이닝
class Builder {
public Builder SetA() { Console.WriteLine("A"); return this; }
public Builder SetB() { Console.WriteLine("B"); return this; }
}
// 30. object.Equals(), GetHashCode()
public override bool Equals(object obj) => base.Equals(obj);
✅ 31~40: LINQ 확장 활용
// 31. Select
var squares = numbers.Select(n => n * n);
// 32. Where
var odds = numbers.Where(n => n % 2 == 1);
// 33. OrderBy
var sorted = numbers.OrderBy(n => n);
// 34. Take & Skip
var firstThree = numbers.Take(3);
var afterThree = numbers.Skip(3);
// 35. Any, All
bool hasNegative = numbers.Any(n => n < 0);
bool allPositive = numbers.All(n => n > 0);
// 36. Distinct
var unique = numbers.Distinct();
// 37. GroupBy
var grouped = people.GroupBy(p => p.Age);
// 38. ToDictionary
var dict = people.ToDictionary(p => p.Name, p => p.Age);
// 39. Join
var joined = people.Join(depts, p => p.DeptId, d => d.Id, (p, d) => new { p.Name, d.DeptName });
// 40. Aggregate
int product = numbers.Aggregate((acc, n) => acc * n);
✅ 41~50: 컬렉션 관련 추가 기능
// 41. Stack
Stack<int> stack = new Stack<int>();
stack.Push(1); stack.Pop();
// 42. Queue
Queue<string> queue = new Queue<string>();
queue.Enqueue("A"); queue.Dequeue();
// 43. HashSet
HashSet<int> set = new HashSet<int> { 1, 2 };
set.Add(3);
// 44. SortedList
SortedList<string, int> sl = new SortedList<string, int>();
// 45. ObservableCollection (UI 바인딩)
ObservableCollection<string> items = new ObservableCollection<string>();
// 46. Dictionary TryGetValue
if (dict.TryGetValue("key", out int val)) { Console.WriteLine(val); }
// 47. ConcurrentDictionary (멀티스레드 안전)
var cd = new ConcurrentDictionary<string, int>();
// 48. Tuple 클래스
Tuple<int, string> t = Tuple.Create(1, "A");
// 49. PriorityQueue (.NET 6 이상)
var pq = new PriorityQueue<string, int>();
pq.Enqueue("B", 2); pq.Enqueue("A", 1);
// 50. KeyValuePair 순회
foreach (var kv in dict) Console.WriteLine($"{kv.Key}: {kv.Value}");
✅ 51~60: 파일/시스템 I/O
// 51. 디렉토리 존재 확인 및 생성
if (!Directory.Exists("Data")) Directory.CreateDirectory("Data");
// 52. 파일 복사/삭제
File.Copy("a.txt", "b.txt");
File.Delete("b.txt");
// 53. StreamReader/Writer
using var sw = new StreamWriter("out.txt");
sw.WriteLine("Hello");
using var sr = new StreamReader("out.txt");
string line = sr.ReadLine();
// 54. BinaryReader/Writer
using var bw = new BinaryWriter(File.Open("data.bin", FileMode.Create));
bw.Write(123);
using var br = new BinaryReader(File.Open("data.bin", FileMode.Open));
int read = br.ReadInt32();
// 55. File.AppendAllText
File.AppendAllText("log.txt", "추가 로그\n");
// 56. 파일 존재 여부
if (File.Exists("test.txt")) { /* 로직 */ }
// 57. 드라이브 정보 조회
foreach (var d in DriveInfo.GetDrives()) Console.WriteLine(d.Name);
// 58. 현재 경로 확인
string path = Directory.GetCurrentDirectory();
// 59. 경로 조합
string fullPath = Path.Combine(path, "file.txt");
// 60. 경로에서 파일명 추출
string fileName = Path.GetFileName(fullPath);
✅ 61~70: 쓰레드 & 동시성
// 61. Thread 사용
Thread t = new Thread(() => Console.WriteLine("새 쓰레드"));
t.Start();
// 62. lock (임계 구역)
object _lock = new();
lock (_lock) {
// 동기화된 코드
}
// 63. Task 실행
Task.Run(() => Console.WriteLine("비동기 실행"));
// 64. async 메서드 + await Task
async Task<int> GetValueAsync() {
await Task.Delay(500);
return 42;
}
// 65. Parallel.For
Parallel.For(0, 10, i => Console.WriteLine(i));
// 66. SemaphoreSlim
SemaphoreSlim semaphore = new(3);
await semaphore.WaitAsync();
semaphore.Release();
// 67. Timer
Timer timer = new(_ => Console.WriteLine("반복"), null, 0, 1000);
// 68. BackgroundWorker (WinForms)
BackgroundWorker worker = new();
worker.DoWork += (s, e) => { /* 백그라운드 작업 */ };
worker.RunWorkerAsync();
// 69. CancellationToken
CancellationTokenSource cts = new();
cts.Cancel();
// 70. Thread.Sleep
Thread.Sleep(1000); // 1초 대기
✅ 71~80: UI 이벤트 처리 (WinForms/WPF 기준)
// 71. 버튼 클릭 이벤트 등록 (WinForms)
button1.Click += (s, e) => MessageBox.Show("클릭됨!");
// 72. 텍스트박스 값 가져오기
string text = textBox1.Text;
// 73. 콤보박스 값 설정 및 선택
comboBox1.Items.Add("선택지1");
comboBox1.SelectedIndex = 0;
// 74. 리스트박스 선택 항목 가져오기
string selected = listBox1.SelectedItem.ToString();
// 75. 체크박스 상태 확인
bool isChecked = checkBox1.Checked;
// 76. 라디오버튼 그룹 중 선택된 것
if (radioButton1.Checked) { /* 처리 */ }
// 77. 폼 로딩 시 초기화
this.Load += (s, e) => InitUI();
// 78. KeyDown 이벤트 처리
this.KeyDown += (s, e) => {
if (e.KeyCode == Keys.Enter) Console.WriteLine("엔터 입력");
};
// 79. 타이머 사용 (WinForms)
Timer timer = new Timer();
timer.Interval = 1000;
timer.Tick += (s, e) => label1.Text = DateTime.Now.ToString();
timer.Start();
// 80. WPF에서 ICommand 패턴 사용
public class RelayCommand : ICommand {
public event EventHandler CanExecuteChanged;
private readonly Action _execute;
public RelayCommand(Action execute) => _execute = execute;
public bool CanExecute(object parameter) => true;
public void Execute(object parameter) => _execute();
}
✅ 81~90: ASP.NET & 네트워크 관련 기능
// 81. HttpClient로 GET 요청
using var client = new HttpClient();
string result = await client.GetStringAsync("https://api.example.com");
// 82. POST 요청 + JSON
var data = new { name = "test" };
var response = await client.PostAsJsonAsync("url", data);
// 83. Web API 컨트롤러
[ApiController]
[Route("api/[controller]")]
public class HelloController : ControllerBase {
[HttpGet]
public string Get() => "Hello!";
}
// 84. Middleware 생성
public class MyMiddleware {
private readonly RequestDelegate _next;
public MyMiddleware(RequestDelegate next) => _next = next;
public async Task InvokeAsync(HttpContext context) {
Console.WriteLine("요청 처리 전");
await _next(context);
}
}
// 85. SignalR 허브 정의
public class ChatHub : Hub {
public async Task Send(string user, string message) =>
await Clients.All.SendAsync("ReceiveMessage", user, message);
}
// 86. TCP 클라이언트
TcpClient client = new();
await client.ConnectAsync("127.0.0.1", 9000);
NetworkStream ns = client.GetStream();
// 87. UDP 송신
UdpClient udp = new();
byte[] msg = Encoding.UTF8.GetBytes("Hello");
await udp.SendAsync(msg, msg.Length, "127.0.0.1", 7000);
// 88. 쿠키 설정
Response.Cookies.Append("token", "abc123");
// 89. 세션 저장
HttpContext.Session.SetString("userId", "123");
// 90. 인증 어트리뷰트
[Authorize]
public IActionResult SecureData() => Ok("보호된 데이터");
✅ 91~100: 고급 문법 (리플렉션, 예외 처리 등)
// 91. try-catch-finally 예외 처리
try {
int x = int.Parse("abc");
} catch (FormatException ex) {
Console.WriteLine("숫자 변환 실패");
} finally {
Console.WriteLine("항상 실행");
}
// 92. 사용자 정의 예외
public class CustomException : Exception {
public CustomException(string msg) : base(msg) {}
}
// 93. throw 키워드로 예외 던지기
throw new InvalidOperationException("잘못된 호출");
// 94. Reflection으로 타입 정보 가져오기
Type t = typeof(string);
MethodInfo[] methods = t.GetMethods();
// 95. dynamic 키워드 사용
dynamic obj = "hello";
Console.WriteLine(obj.Length); // 런타임에 동작
// 96. nameof 연산자
string column = nameof(User.Id); // "Id"
// 97. Expression Tree
Expression<Func<int, bool>> expr = x => x > 5;
// 98. 람다로 Func 정의
Func<int, int, int> sum = (a, b) => a + b;
// 99. unsafe 코드 (포인터 사용)
unsafe {
int x = 10;
int* p = &x;
Console.WriteLine(*p);
}
// 100. 애트리뷰트 정의 및 사용
[AttributeUsage(AttributeTargets.Class)]
public class MyAttribute : Attribute {
public string Info { get; }
public MyAttribute(string info) => Info = info;
}
[My("이 클래스는 커스텀 속성이 붙어 있음")]
public class MyClass { }
✅ 전체 요약
- 01~20: 기본 문법, 반복문, 배열, 문자열
- 21~30: 클래스, 구조체, 레코드 등 객체지향 문법
- 31~40: LINQ 활용
- 41~50: 컬렉션 API (Dictionary, Stack 등)
- 51~60: 파일 및 시스템 I/O
- 61~70: 비동기, 쓰레딩, Task
- 71~80: UI 이벤트 (WinForms/WPF)
- 81~90: 네트워크 & ASP.NET 관련 기능
- 91~100: 예외, 리플렉션, dynamic, Expression 등 고급 문법