본문 바로가기

C#/C# 문법

[C#] 정적 필드

728x90
반응형

 정적 필드

 

만약 클래스의 객체가 생성될 때마다 증가하는 필드를 선언하고 싶어서 다음과 같은 코드를 작성하였다고 해보자.

 

using System;

namespace ConsoleApp1
{
    public class Print
    {
        public int calltimes;
        public Print() {
            Console.WriteLine("Hello World!");
            calltimes++;
        }

        
    }

    class Program
    {
        static void Main(string[] args)
        {
            Print print1 = new Print();
            Console.WriteLine(print1.calltimes);

            Print print2 = new Print();
            Console.WriteLine(print2.calltimes);
        }
    }
}

 

하지만 위 코드를 실행할 경우 print1.calltimes 와 print2.calltimes 모두 1이라는 값이 출력될 것이다.

Print 클래스의 객체를 생성할 때마다 calltimes 는 각각의 객체와 함께 새로 생성되기 때문에

print1.calltimes 와 print2.calltimes 는 다른 필드인 것이다.

이를 해결하기 위해 정적 필드를 사용할 수 있다.

정적 필드를 선언하기 위해서 static 예약어를 public 예약어 앞에 사용해 주면 된다.

static 예약어를 사용하면 객체를 생성하지 않아도 필드에 메모리가 할당되며 객체를 여러 개 생성하더라도

필드가 여러 개 생성되거나 초기화되지 않는다.

또한 필드에 접근할 때에도 생성된 객체를 통해 접근하는 것이 아닌 클래스 명을 통해 접근할 수 있다.

따라서 다음과 같이 static 예약어만 추가해 주면 의도한 대로 코드를 작성할 수 있다.

 

using System;

namespace ConsoleApp1
{
    public class Print
    {
        static public int calltimes;
        public Print() {
            Console.WriteLine("Hello World!");
            calltimes++;
        }

        
    }

    class Program
    {
        static void Main(string[] args)
        {
            Print print1 = new Print();
            Console.WriteLine(Print.calltimes);

            Print print2 = new Print();
            Console.WriteLine(Print.calltimes);

            Print print3 = new Print();
            Console.WriteLine(Print.calltimes);
        }
    }
}

 

따라서 다음 코드를 실행시켜보면 순서대로 Print.calltimes를 출력하였을 때 1, 2, 3이 출력되는 것을 알 수 있다.

728x90
반응형

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

[C#] 인스턴스, 싱글턴  (0) 2023.10.06
[C#] 생성자, 소멸자  (0) 2023.10.06
[C#] 오버로딩  (0) 2023.10.06
[C#] 클래스  (0) 2023.10.06
[C#] 가변 배열  (0) 2023.10.06