static constructor vs instance constructor

C#은 두 가지 종류의 constructor, 즉 class constructor(static constructor), instance constructor(non-static constructor)를 지원한다.

static constructor
-static constructor는 static data member를 초기화하는데 사용
-static constructor는 접근 지정자를 쓸수 없음
-static constructor는 인자를 가질 수 없음
-static constructor는 non-static data member를 접근할 수 없음

// Test.cs
Test
{
//Declaration and initialization of static data member
private static int id = 5;
public static int Id
{
get
{
return id;
}
}

public static void print()
{
Console.WriteLine(“Test.id=” + id);
}
}

class Program
{
static void Main(string[] args)
{
Test.print(); // 정적 메소드를 사용하여 Test.id를 출력
}
}
Test.id=5

// Test1.cs
class Test1
{
private static int id;

// static constructor를 사용하여 Test.id값에 따라서 Test1.id를 지정
static Test()
{
if( Test.Id < 10 ) { id = 20; }
else { id = 100; }
}

public static void print()
{
Console.WriteLine(“Test.id=” + id);
}
}

class Program
{
static void Main(string[] args)
{
Test1.print(); // 정적 메소드를 사용하여 Test.id를 출력
}
}

Test.id=20 // 정적 생성자 내에서 Test.id=5였기때문에 Test.id=20

instance constructor
-instance constructor는 new 키워드를 사용하여 객체 생성에 사용
-instance constructor는 일반적으로 constructor라고 불림
-constructor initializer는 생성자들 코드를 간략하게 만들기 위해 사용

public class MySimpleClass
{
public MySimpleClass (int x)
{
Console.WriteLine (x);
}
}

// 위의 코드는 컴파일러에서 아래의 코드처럼 해석
public class MySimpleClass
{
public MySimpleClass (int x) : base()
{
Console.WriteLine (x);
}
}

public class MyClass {
private ArrayList col;
private string name;
public MyClass() : this(0,””) // 생성자 초기화목록을 사용하여 기본 생성자 지정 { }
public MyClass(int initialCount) : this (initialCount, “”) { }
public MyClass(int initialCount, string name)
{
col = (initialCount > 0) ? new ArrayList(initialCount) : new ArrayList();
this.name = name;
}
}

-default constructor가 지정되어 있지 않다면 컴파일러에서 자동 생성해줌

public class MySimpleClass
{
int someMemberVariable;
}

// 위의 코드를 컴파일러에서 아래와 같이 해석함
public class MySimpleClass
{
int someMemberVariable;public MySimpleClass() : base()
{
}
}

-constructor는 상속되지 않음

public class MyBaseClass
{
public MyBaseClass (int x)
{
}
}

public class MyDerivedClass : MyBaseClass
{
// This constructor itself is okay – it invokes an
// appropriate base class constructor
public MyDerivedClass () : base (5)
{
}

public static void Main()
{
new MyDerivedClass (10); // ERROR: MyDerivedClass는 인자를 받는 생성자가 없음
}
}