C# 전체 문법 가이드

C# 문법을 체계적으로 학습할 수 있는 튜토리얼 가이드입니다.

00. C# 코드 구조

C# 프로그램은 기본적으로 네임스페이스, 클래스, 메서드로 구성됩니다.

• using - 네임스페이스 선언

• 외부 라이브러리나 네임스페이스를 사용하기 위한 선언

using System;
using System.Collections.Generic;

• namespace - 네임스페이스 정의

  • 코드를 논리적으로 그룹화하는 컨테이너
  • 클래스 이름 충돌을 방지
namespace MyProject
{
  // 클래스 정의
}

• class - 클래스 정의

  • 객체 지향 프로그래밍의 기본 단위
  • 데이터와 메서드를 캡슐화
namespace MyProject
{
  public class MyClass
  {
    // 필드, 속성, 메서드 정의
  }
}

01. C# 기본 문법

변수, 데이터 타입, 연산자 등 C#의 기본 문법을 학습합니다.

변수 선언

// 명시적 타입 선언
int number = 10;
string text = "Hello";
bool isActive = true;

// var 키워드 (타입 추론)
var name = "World";
var count = 5;

데이터 타입

// 정수형
int integer = 42;
long bigInteger = 1000000L;
short smallInteger = 100;

// 실수형
float f = 3.14f;
double d = 3.14159;
decimal money = 100.50m;

// 문자형
char ch = 'A';
string str = "Hello World";

// 불린형
bool flag = true;

02. C# 제어문

조건문과 반복문을 사용하는 방법입니다.

if-else 문

int score = 85;

if (score >= 90)
{
  Console.WriteLine("A");
}
else if (score >= 80)
{
  Console.WriteLine("B");
}
else
{
  Console.WriteLine("C");
}

switch 문

int day = 3;

switch (day)
{
  case 1:
    Console.WriteLine("Monday");
    break;
  case 2:
    Console.WriteLine("Tuesday");
    break;
  default:
    Console.WriteLine("Other day");
    break;
}

for 루프

for (int i = 0; i < 10; i++)
{
  Console.WriteLine(i);
}

foreach 루프

int[] numbers = {1, 2, 3, 4, 5};

foreach (int num in numbers)
{
  Console.WriteLine(num);
}

03. C# 클래스와 객체

클래스를 정의하고 객체를 생성하는 방법입니다.

클래스 정의 예제

public class Person
{
  // 필드
  private string name;
  private int age;

  // 생성자
  public Person(string name, int age)
  {
    this.name = name;
    this.age = age;
  }

  // 속성
  public string Name
  {
    get { return name; }
    set { name = value; }
  }

  // 메서드
  public void Display()
  {
    Console.WriteLine($"Name: {name}, Age: {age}");
  }
}

객체 생성 및 사용

Person person = new Person("John", 30);
person.Display();
person.Name = "Jane";

04. C# 컬렉션

리스트, 딕셔너리 등 컬렉션을 사용하는 방법입니다.

List 예제

using System.Collections.Generic;

List<string> names = new List<string>();
names.Add("Alice");
names.Add("Bob");
names.Add("Charlie");

foreach (string name in names)
{
  Console.WriteLine(name);
}

Dictionary 예제

Dictionary<string, int> ages = new Dictionary<string, int>();
ages["Alice"] = 25;
ages["Bob"] = 30;

Console.WriteLine(ages["Alice"]); // 25

05. C# 예외 처리

try-catch-finally를 사용한 예외 처리 방법입니다.

예외 처리 예제

try
{
  int result = 10 / 0;
}
catch (DivideByZeroException ex)
{
  Console.WriteLine($"Error: {ex.Message}");
}
catch (Exception ex)
{
  Console.WriteLine($"General error: {ex.Message}");
}
finally
{
  Console.WriteLine("This always executes");
}

관련 문서