C#을 학습하거나 실무 개발을 하다 보면 가장 많이 헷갈리는 개념 중 하나가 static 메서드와 인스턴스 메서드입니다.
이 글에서는 두 개념의 차이, 예제, 실무 적용 기준까지 한 번에 정리합니다.
static 메서드는 객체 생성 없이 호출할 수 있는 메서드입니다.
public static void PrintDate()
{
Console.WriteLine(DateTime.Now);
}
// 호출
MyClass.PrintDate();
인스턴스 메서드는 객체를 만든 뒤 호출할 수 있는 메서드입니다.
public void PrintName()
{
Console.WriteLine(Name);
}
Person p = new Person();
p.PrintName();
| 구분 | static 메서드 | 인스턴스 메서드 |
|---|---|---|
| 객체 생성 필요 | ❌ 필요 없음 | ✔ 필요함 |
| 호출 방식 | 클래스명.메서드() | 객체명.메서드() |
| 인스턴스 필드 접근 | ❌ 불가 | ✔ 가능 |
| static 필드 접근 | ✔ 가능 | ✔ 가능 |
| 주된 목적 | 공용 기능, 유틸 | 객체 상태 기반 기능 |
public static class MathUtil
{
public static int Add(int a, int b)
{
return a + b;
}
}
int result = MathUtil.Add(3, 5);
➡ 상태가 필요 없고 기능만 제공 → static 메서드가 정답
public class Person
{
public string Name;
public void Introduce()
{
Console.WriteLine($"안녕하세요, 저는 {Name}입니다.");
}
}
Person p1 = new Person { Name = "철수" };
p1.Introduce(); // 철수
➡ 객체마다 상태(Name)가 다르므로 인스턴스 메서드 사용
class User
{
public string Name;
public static void ShowName()
{
Console.WriteLine(Name); // ❌ 오류 발생
}
}
이유: static 메서드는 객체 생성 없이 실행될 수 있기 때문입니다.
즉, User 인스턴스가 없을 수도 있어서 인스턴스 필드에 접근할 수 없습니다.
class User
{
public string Name;
public static int UserCount;
public void PrintInfo()
{
Console.WriteLine(Name); // ✔ 인스턴스 필드
Console.WriteLine(UserCount); // ✔ static 필드
}
}
➡ 인스턴스가 존재하므로 static 영역 접근 가능
public class FileManager
{
public string BasePath;
// 인스턴스 메서드
public void Save(string fileName, string content)
{
File.WriteAllText(Path.Combine(BasePath, fileName), content);
}
// static 메서드
public static bool Exists(string fileName)
{
return File.Exists(fileName);
}
}
// 사용 예
var fm = new FileManager { BasePath = "C:/temp" };
fm.Save("test.txt", "hello"); // 인스턴스 메서드
bool exists = FileManager.Exists("test.txt"); // static 메서드
➡ 실무에서는 이처럼 두 가지 방식을 적절하게 조합해서 사용합니다.