본문 바로가기

기초코딩강좌/유니티 기초 강좌

6. 기본 문법

반응형

C#의 기본 문법을 간략하게 소개하겠습니다. C#은 강력한 객체 지향 프로그래밍 언어이며, 다양한 기능과 문법을 제공합니다. 아래는 C#의 핵심적인 기본 문법 요소들입니다.

 

1. 변수 및 자료형 (Variables and Data Types):

// 변수 선언과 초기화
int age = 25;
string name = "John";
float height = 175.5f;
bool isStudent = true;

 

2. 제어 구조 (Control Structures):
조건문 (Conditional Statements):

int number = 10;

if (number > 0) {
    Console.WriteLine("양수입니다.");
} else if (number < 0) {
    Console.WriteLine("음수입니다.");
} else {
    Console.WriteLine("0입니다.");
}

 

반복문 (Loops):

// for 문
for (int i = 0; i < 5; i++) {
    Console.WriteLine(i);
}

// while 문
int j = 0;
while (j < 5) {
    Console.WriteLine(j);
    j++;
}

 

3. 메서드 (Methods):

// 메서드 정의
int Add(int a, int b) {
    return a + b;
}

// 메서드 호출
int result = Add(3, 5);
Console.WriteLine(result); // 출력: 8

 

4. 클래스와 객체 (Classes and Objects):

// 클래스 정의
class Person {
    public string Name { get; set; }
    public int Age { get; set; }

    public void PrintInfo() {
        Console.WriteLine($"이름: {Name}, 나이: {Age}");
    }
}

// 객체 생성과 사용
Person person1 = new Person();
person1.Name = "Alice";
person1.Age = 30;
person1.PrintInfo();

 

5. 배열 (Arrays):

// 배열 선언과 초기화
int[] numbers = { 1, 2, 3, 4, 5 };

// 배열 순회
foreach (int num in numbers) {
    Console.WriteLine(num);
}

 

6. 예외 처리 (Exception Handling):

try {
    // 예외 발생 가능한 코드
    int result = 10 / 0;
} catch (DivideByZeroException ex) {
    // 예외 처리
    Console.WriteLine("0으로 나눌 수 없습니다.");
}

 

7. 속성과 인덱서 (Properties and Indexers):

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 this[int index] {
        get {
            if (index == 0) return width;
            else if (index == 1) return height;
            else throw new IndexOutOfRangeException();
        }
        set {
            if (index == 0) width = value;
            else if (index == 1) height = value;
            else throw new IndexOutOfRangeException();
        }
    }
}

// 사용
Rectangle rect = new Rectangle();
rect.Width = 10;
rect.Height = 5;
Console.WriteLine($"Width: {rect.Width}, Height: {rect.Height}");
Console.WriteLine($"Width (using indexer): {rect[0]}, Height (using indexer): {rect[1]}");

 

C#의 간단한 기본 문법 예제들이며, C#은 더 많은 특징과 고급 기능을 지원합니다. 객체 지향 프로그래밍, LINQ, 람다식, 이벤트 등 다양한 개념과 기능을 통해 다양한 프로그래밍 시나리오에 적용할 수 있습니다.

728x90
반응형

'기초코딩강좌 > 유니티 기초 강좌' 카테고리의 다른 글

8. 스크립트 생성과 연결  (1) 2023.12.28
7. 변수와 자료형  (1) 2023.12.27
5. C# 언어 소개  (0) 2023.12.25
4. 컴포넌트의 역할  (1) 2023.12.24
3. 게임 오브젝트의 개념  (1) 2023.12.23