본문 바로가기
IT/C#

C# 기본 문법

by eplus 2024. 11. 24.

C#의 기본 문법은 간결하고 직관적이며, 객체 지향 프로그래밍(OOP)을 기반으로 합니다. 아래는 C#의 기본 문법을 주요 구성 요소별로 정리한 내용입니다.


1. 기본 구조

using System;

namespace MyNamespace
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello, World!"); // 출력
        }
    }
}
  • using: 네임스페이스를 가져오는 키워드.
  • namespace: 코드 그룹을 정의.
  • class: 클래스 선언.
  • Main: 프로그램의 시작점.
  • Console.WriteLine: 텍스트 출력.

2. 변수 및 상수

변수 선언

int number = 10;         // 정수
double pi = 3.14;        // 실수
string name = "Alice";   // 문자열
bool isAlive = true;     // 논리값
char grade = 'A';        // 문자

상수 선언

const double Pi = 3.14159;

3. 데이터 입력/출력

입력

Console.WriteLine("Enter your name:");
string name = Console.ReadLine();

출력

Console.WriteLine("Hello, " + name);

4. 조건문

if문

if (number > 0)
{
    Console.WriteLine("Positive number");
}
else if (number < 0)
{
    Console.WriteLine("Negative number");
}
else
{
    Console.WriteLine("Zero");
}

switch문

switch (grade)
{
    case 'A':
        Console.WriteLine("Excellent");
        break;
    case 'B':
        Console.WriteLine("Good");
        break;
    default:
        Console.WriteLine("Try harder");
        break;
}

5. 반복문

for문

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

while문

int count = 0;
while (count < 5)
{
    Console.WriteLine(count);
    count++;
}

do-while문

int count = 0;
do
{
    Console.WriteLine(count);
    count++;
} while (count < 5);

foreach문

int[] numbers = {1, 2, 3};
foreach (int num in numbers)
{
    Console.WriteLine(num);
}

6. 메서드

메서드 정의

static int Add(int a, int b)
{
    return a + b;
}

메서드 호출

int result = Add(3, 5);
Console.WriteLine(result);

7. 클래스와 객체

클래스 정의

class Person
{
    public string Name;
    public int Age;

    public void Greet()
    {
        Console.WriteLine($"Hello, my name is {Name} and I am {Age} years old.");
    }
}

객체 생성 및 사용

Person person = new Person();
person.Name = "Alice";
person.Age = 30;
person.Greet();

8. 배열

int[] numbers = {1, 2, 3, 4, 5};
Console.WriteLine(numbers[0]); // 배열 요소 접근

numbers[0] = 10;               // 배열 요소 변경

9. 예외 처리

try
{
    int number = int.Parse("abc");
}
catch (FormatException e)
{
    Console.WriteLine("Invalid input: " + e.Message);
}
finally
{
    Console.WriteLine("Execution complete.");
}

10. 주요 키워드

  • public, private, protected, internal: 접근 제한자.
  • static: 정적 멤버 선언.
  • void: 반환값이 없는 메서드.
  • return: 메서드에서 값 반환.
  • new: 객체 생성.

11. LINQ (간단한 데이터 처리 예제)

int[] numbers = {1, 2, 3, 4, 5};
var evenNumbers = numbers.Where(n => n % 2 == 0);

foreach (var num in evenNumbers)
{
    Console.WriteLine(num); // 2, 4
}

C#은 강력한 타입 안정성, 간결한 문법, 풍부한 라이브러리를 제공해 개발자가 생산성을 높일 수 있는 언어입니다. 이를 바탕으로 다양한 애플리케이션을 효율적으로 개발할 수 있습니다.

728x90
반응형

'IT > C#' 카테고리의 다른 글

C#과 VB.NET의 차이  (41) 2024.11.25
C# 개발툴은?  (38) 2024.11.24
C# Class는?  (45) 2024.11.24
C# 데이터 유형은?  (0) 2024.11.24
C# 이란?  (41) 2024.11.24