static 실무 예제

황현중·2025년 11월 18일

C#

목록 보기
2/24

✅ 1. 공용 유틸리티 클래스 (Utility Class)

가장 대표적인 static 사용 예
상태가 필요 없고 “기능만” 제공하는 경우.

📌 문자열 유효성 검사 유틸
public static class StringUtil
{
public static bool IsEmpty(string s)
=> string.IsNullOrWhiteSpace(s);

public static bool IsNumeric(string s)
    => s.All(char.IsDigit);

}

사용:

if (StringUtil.IsEmpty(userInput)) { ... }

➡ 상태가 없으므로 static이 매우 적합함.

✅ 2. 공용 설정값(Read-only Config)

앱 전체에서 공유하는 설정값.

📌 AppConfig (읽기 전용)
public static class AppConfig
{
public static readonly string AppName = "My ERP System";
public static readonly int MaxUserCount = 100;
}

사용:

Console.WriteLine(AppConfig.AppName);

➡ “읽기 전용 전역 설정”은 static이 실무에서 매우 자주 쓰임.

✅ 3. 날짜/시간 제공 유틸 (실무에서 매우 많이 사용)

예: ERP 시스템에서 “현재 서버시간” 자주 필요

public static class TimeUtil
{
public static DateTime Now => DateTime.Now;

public static string NowString 
    => DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

}

사용:

Log.Write($"Process Start at {TimeUtil.NowString}");

➡ DateTime처럼 공용적으로 사용하는 기능은 static 형태가 딱 맞음.

✅ 4. 공용 ID 생성기 (Thread-safe)

ERP/쇼핑몰 등에서 주문번호, 거래번호를 만들 때 많이 사용.

단, “멀티스레드 안전하게” 만들어야 함.

public static class IdGenerator
{
private static int _seq = 0;

public static int Next()
{
    return Interlocked.Increment(ref _seq);
}

}

사용:

int orderId = IdGenerator.Next();

➡ 상태가 있지만, “전역에서 하나만 존재하는 시퀀스”는 static + 동기화로 해결.

✅ 5. Singleton 패턴 (정상적인 static 활용)

Logger, Cache, ConfigManager 등 "전역적으로 하나만 있어야 하는 객체"

📌 Thread-safe Singleton Logger
public sealed class Logger
{
private static readonly Logger _instance = new Logger();

public static Logger Instance => _instance;

private Logger() { }

public void Write(string msg)
{
    Console.WriteLine($"[{DateTime.Now}] {msg}");
}

}

사용:

Logger.Instance.Write("Start Work");

➡ Logger는 프로그램 전체에서 하나만 있어야 하므로 static이 적합.

✅ 6. 확장 메서드(Extension Method) 선언용 클래스
📌 문자열 확장
public static class StringExtensions
{
public static bool IsEmail(this string s)
{
return s.Contains("@") && s.Contains(".");
}
}

사용:

string mail = "test@mail.com";

if (mail.IsEmail())
Console.WriteLine("유효한 이메일");

➡ 확장 메서드는 반드시 static 클래스 + static 메서드여야 함.

✅ 7. 상수(Constant) 그룹 모음

예: 데이터베이스 컬럼 값, 공통 코드값

public static class ErrorCodes
{
public const string NOT_FOUND = "E404";
public const string SERVER_ERROR = "E500";
}

사용:

if (code == ErrorCodes.NOT_FOUND) { ... }

➡ 상수를 그룹화하기에 static class가 가장 깔끔함.

✅ 8. Application 전체에서 공유하는 자원 (제한적 사용)

예: HttpClient (Singleton패턴으로)

public static class HttpService
{
public static readonly HttpClient Client = new HttpClient();
}

사용:

var response = await HttpService.Client.GetAsync(url);

➡ HttpClient는 static 1개로 두는 것이 MS 공식 권장 패턴.

0개의 댓글