C# 기초 문법과 OOP 개념: 클래스, 멤버, 식별자, 키워드 총정리
객체지향 프로그래밍과 C# 기본 문법
C#은 객체지향 언어입니다. 객체는 동작(메서드)으로 상호작용하며, 같은 종류 객체는 같은 클래스에 속합니다.
예제: Rectangle 클래스 구현
using System;
namespace RectangleApplication {
class Rectangle {
// 멤버 변수
double length;
double width;
public void Acceptdetails() {
length = 4.5; width = 3.5;
}
public double GetArea() {
return length * width;
}
public void Display() {
Console.WriteLine("Length: {0}", length);
Console.WriteLine("Width: {0}", width);
Console.WriteLine("Area: {0}", GetArea());
}
}
class ExecuteRectangle {
static void Main(string[] args) {
Rectangle r = new Rectangle();
r.Acceptdetails();
r.Display();
Console.ReadLine();
}
}
}
실행 결과:
Length: 4.5
Width: 3.5
Area: 15.75
핵심 키워드와 문법 요소
using 키워드
네임스페이스 포함. 프로그램 첫 줄에 보통 위치.
class 키워드
클래스 선언.
주석
멤버 변수 (필드)
클래스의 속성/데이터 저장. 예제에서 length, width.
멤버 함수 (메서드)
특정 작업 수행 문장 집합. 클래스 내부 선언. 예제: Acceptdetails, GetArea, Display.
클래스 인스턴스화
new Rectangle()로 객체 생성 후 멤버 접근.
식별자 명명 규칙
- 문자로 시작, 이후 문자/숫자/언더스코어 가능. 숫자로 시작 불가.
- 공백이나 특수문자(?, -, +, !, @, #, %, ^, &, *, (, ), [, ], {, }, ., ;, :, ", ', /, \) 불가. 언더스코어(_)만 허용.
- C# 예약어(keyword) 사용 불가. 단,
@ 접두사 붙이면 사용 가능.
C# 키워드 전체 목록
예약어 (Reserved Keywords): abstract, as, base, bool, break, byte, case, catch, char, checked, class, const, continue, decimal, default, delegate, do, double, else, enum, event, explicit, extern, false, finally, fixed, float, for, foreach, goto, if, implicit, in, in(generic), int, interface, internal, is, lock, long, namespace, new, null, object, operator, out, out(generic), override, params, private, protected, public, readonly, ref, return, sbyte, sealed, short, sizeof, stackalloc, static, string, struct, switch, this, throw, true, try, typeof, uint, ulong, unchecked, unsafe, ushort, using, virtual, void, volatile, while.
문맥 키워드 (Contextual Keywords): add, alias, ascending, descending, dynamic, from, get, global, group, into, join, let, orderby, partial(type), partial(method), remove, select, set.
문맥 키워드는 특정 문맥에서 특별한 의미(예: get/set는 속성 접근자)를 가지며, 식별자로도 사용 가능.