C#문법

[C# 문법] Part16 static 한정자

BlackWolfDev 2024. 10. 19. 17:37

[ static 한정자란 ]

C#을 다루면서 static이라는 키워드는 많이 봤을 것이다.

static은 변수, 메서드, 클래스에서 정적 속성을 부여하여 클래스로부터 객체를 생성하지 않고 변수나 메서드를 호출할 수 있게 한다.

우리가 클래스를 구현하고 이를 new 연산자를 통해 인스턴스를 생성한다면 메모리에 할당된다는 것을 알 수 있었다. 그러나 static을 사용한다면 인스턴스를 생성하지 않아 메모리의 비용을 줄 일 수 있는 장점이 있다. 즉, 객체를 생성하지 않고 사용할 수 있는 변수, 메서드, 클래스라면 static을 사용하는 것이 유용할 수 있다.


[ static 변수 ]

또는 정적 변수라고도 부른다.

클래스의 일반 멤버 변수는 클래스로부터 객체가 생성될 때마다 각각 할당되지만, 정적 변수는 해당 클래스가 처음 사용될 때부터 한 번만 초기화되어 동일한 메모리를 사용하게 된다.

static 자료형 정적변수명

구현 방법은 일반 변수 선언 앞에 static를 사용하면 된다.

클래스명.정적변수명

사용법은 위와 같다.

보통은 객체를 생성하고 객체명으로 멤버 변수를 접근할 수 있다.

그러나 정적 변수로 선언한다면 클래스명을 통해 정적 변수를 호출할 수 있다.

(참고로 객체를 생성하여 객체명으로 정적변수 접근을 불가능하다)

class StaticClass
{
    public static int staticVariable = 0;
}

class ProgramClass
{
    public static void Main()
    {
        StaticClass.staticVariable = 10;
    }
}

StaticClass라는 클래스를 선언하고 정적변수 num을 선언하였다.

아래 Main()에서 클래스명.정적변수 형식으로 정적 변수를 호출할 수 있게 된다.

 

class StaticClass
{
    public static int staticVariable = 0;
    public int variable = 0;

    public void AddNumVariable(){
        staticVariable += 10;
        variable += 10;
        
        Console.WriteLine("staticVariable: "+ staticVariable);
        Console.WriteLine("variable: "+ variable);
    }
}

class ProgramClass
{
    public static void Main()
    {
        StaticClass staticClass1 = new StaticClass();
        StaticClass staticClass2 = new StaticClass();

        staticClass1.AddNumVariable();
        staticClass2.AddNumVariable();
    }
}

또 하나의 특징을 설명해 주자면 정적 변수는 하나의 메모리에 고정되어 있어서 인스턴스들끼리 공유가 되는 특징이 있다.

위의 코드에서는 정적 변수와 일반 변수를 선언하였고 두 변수의 값의 변화를 주는 코드이다.

정적 변수는 두 개의 인스턴스에 공유가 되기 때문에 첫 번째 인스턴스에서 값의 변화를 주면 다른 인스턴스에도 그 영향이 그대로 간다.

그러나 일반 변수는 각각의 인스턴스에만 해당이 되기 때문에 서로 간의 영향은 없다.


[ static 메서드 ]

또는 정적 메서드라고 부른다.

static 자료형 정적메서드명(){}

정적 변수의 선언 방식과 비슷하게 static만 붙여주면 된다.

클래스명.정적메서드명()

사용 방법도 클래스만으로 정적 메서드를 호출할 수 있다.

class StaticClass
{
    public static int staticVariable = 0;

    public static void AddNumVariable(){
        staticVariable += 10;
        Console.WriteLine("staticVariable: "+ staticVariable);
    }
}

class ProgramClass
{
    public static void Main()
    {
        StaticClass.AddNumVariable();
    }
}

위의 코드는 정적 메서드의 구현과 사용한 예시이다.

(참고로 정적 메서드는 인스턴스가 생성되기 전에 호출이 가능한데 이러한 특징으로 인해 정적 변수가 아닌 일반 변수는 사용할 수 없다)


[ static 클래스 ]

또는 정적 클래스라고 한다.

모든 멤버가 정적 변수, 정적 메서드로만 이루어지며, 객체를 생성할 수 없는 클래스이다.

만약 객체를 생성할 필요가 없다면 사용하기 유용할 것이다.

static class StaticClass{}

일반 클래스 선언에서 static을 붙여주면 된다.

static class StaticClass
{
    public static int staticVariable = 0;

    static StaticClass()
    {
        staticVariable = 5;
    }
    public static void AddNumVariable(){
        staticVariable += 10;
        Console.WriteLine("staticVariable: "+ staticVariable);
    }
}

class ProgramClass
{
    public static void Main()
    {
        StaticClass.staticVariable = 10;
        StaticClass.AddNumVariable();
    }
}

정적 클래스는 정적 생성자를 가질 수 있는데 이 또한 static을 사용해야 하고 정적 클래스는 초기화할 때 사용된다.

728x90
반응형