Class

접근자
-protected 접근 지정자를 사용한 멤버 필드와 메소드는 파생 클래스에서는 사용가능하나 클래스 외부에서는 호출하지 못함

static 필드와 메소드
-static field는 전역 데이터로 클래스당 하나만 할당됨
-static field는 클래스명.정적필드명 형태로 사용
-static method는 class method나 static member field 조작을 위한 메소드
-static method는 instance field는 접근 불가능

constructor (생성자)
-default constructor (기본 생성자)
-constructor overloading (생성자 오버로딩) 생성자를 여러 가지 형태로 정의
-constructor initializer (생성자 초기화 목록) 생성자들 사이의 정의가 비슷한 경우 코드를 간략하게 만들기 위해 사용

-private constructor (private 생성자) 정적 멤버만 포함하는 클래스에서 사용하며 클래스가 인스턴스화 될 수 없음을 분명히 하기 위해 private 접근 지정자를 사용
-static constructor (static 생성자) 정적 데이터 멤버를 초기화하는데 사용

destructor (소멸자)
-객체가 소멸될 때 필요한 정리 작업을 정의하는 부분

C# Internal Class vs Public Class

class Test { // internal class Test (현재의 어셈블리 내부에서 접근가능한 클래스)
        //code inside it
}

public class Test{ (다른 어셈블리에서도 접근가능한 클래스)
       //code inside it
}

internal(C# 참조)
http://msdn.microsoft.com/ko-kr/library/7c5ka91b.aspx

class vs public class
http://stackoverflow.com/questions/12392876/class-vs-public-class

const vs readonly Field

<strong><em><span style=”color: #0000ff;”>const 상수(constant)은 컴파일타임(compile-time) 상수이다.</span></em>
<span style=”color: #008000;”>readonly 상수(constant)은 런타임(run-time) 상수이다.</span></strong>
<div>// const
public <strong><span style=”color: #0000ff;”>const</span></strong> int Millennium = 2000;
public <strong><span style=”color: #0000ff;”>const</span></strong> double PI = 3.141592;// readonly
public static <strong><span style=”color: #008000;”>readonly</span></strong> int ThisYear = 2010;</div>
<div></div>
<div>public class MyClass
{</div>
<div style=”padding-left: 30px;”>public <strong><span style=”color: #008000;”>readonly</span></strong> double PI;
public MyClass()
{
PI = 3.141592;
}</div>
<div>}</div>
&nbsp;

<span lang=”EN-US” xml:lang=”EN-US”>const</span> 상수는 선언하는 순간부터 <span lang=”EN-US” xml:lang=”EN-US”>static</span>이 된다<span lang=”EN-US” xml:lang=”EN-US”>.
const 상수를 선언함과 동시에 초기화를 해주어야 한다.
const 상수는 컴파일시 값이 결정 되어져 있어야 한다.</span>

readonly 상수는 static 키워드를 사용하면 static 상수가 된다. 사용하지 않으면 일반상수가 된다.
readonly 상수는 const 키워드를 사용하는 것처럼 반드시 초기화 될 필요없다.
readonly 상수는 생성자를 통해서 런타임시 값이 결정될 수 있다.
한번 값이 결정되면 다시는 그 값을 변경할 수는 없다.

Local Variable vs Field vs Method

Local variables in C# must be initialized before they are used.

https://msdn.microsoft.com/en-us/library/vstudio/s1ax56ch(v=vs.100).aspx

class Test
{

     static int test1; // static field test1 = 0 Warning CS0414: The field ‘Test.test1’ is assigned but its value is never used

    int test2; // instance field test2 = 0 Warning CS0649: The field ‘Test.test2’ is never assigned to, and will always have its default value 0

     public void Foo() // instance method
{

          int test3;                 // Declaration only; Not initialized warning CS0168: The variable ‘test3’ is declared but never used

int test4 = test2;         // Ok
          //int test5 = test3;         // Error CS0165: Use of unassigned local variable ‘test3’

}

     public static void Foo2() // static method
    {

        test1 = 2;

    }

}

class Program
{

static void Main(string[] args)
{

            // Declaration only
            float temperature; // warning CS0168: The variable ‘temperature’ is declared but never used
            string name; // warning CS0168: The variable ‘name’ is declared but never used
            Test myClass; // The variable ‘myClass’ is declared but never used

            // Declaration with initializers 
            double limit = 3.5;
            int[] source = { 0, 1, 2, 3, 4, 5 };
            var query = from item in source
                        where item <= limit
                        select item;

            Test.Foo2(); // Static method
           // Test.Foo();  // Error CS0120: An object reference is required for the non-static field, method, or property 

}

}

Instance vs Static Field

Static Field (a.k.a. Class Field)
-전역 데이터, 공유 데이터로 클래스 로딩 시 공간을 할당
-한 클래스에 하나만 정적 필드가 할당됨
-클래스명.정적필드명으로 사용
-클래스 객체의 개수를 카운트하거나 유틸리티 값들을 저장하는 경우 사용함

Instance Field
-객체의 현재 상태를 저장할 수 있는 자료
-객체가 생성될 시 메모리 공간을 할당
-객체명.객체필드명으로 사용

class ValueClass
{
     private int value = 0; // 인스턴스 필드
    public static int count = 0; // 정적 필드
     public ValueClass() { count++; }
    public void setValue(int value) { this.value = value; } // 인스턴스 메소드
    public int getValue() { return this.value; } // 인스턴스 메소드
    public void print() { Console.WriteLine(“value={0}”, this.value); } // 인스턴스 메소드
    public static void printString(string str) { Console.WriteLine(str); } // 정적 메소드
    public static int getCount() { return count; } // 정적 메소드
}
class Program
{
static void main(string[] args)
{
ValueClass c1 = new ValueClass();        c1.setValue(10); // 인스턴스 메소드
c1.print(); // 인스턴스 메소드 value=10
        ValueClass.printString(“test”); // 정적 메소드 (클래스명.정적메소드명) test
      ValueClass c2 = new ValueClass();
        c2.setValue(20); // 인스턴스 메소드
c2.print(); // 인스턴스 메소드 value=20
        Console.WriteLine(“number of ValueClass: {0}”, ValueClass.getCount()); // 정적 메소드 (클래스명.정적메소드명) number of ValueClass: 2
Console.WriteLine(“number of ValueClass: {0}”, ++ValueClass.count); // 정적 필드 (클래스명.정적필드명) number of ValueClass: 3
    }
}

Instance Method vs Static Method

Static Method (a.k.a. Class Method)
-메서드 선언에 static 한정자가 있는 경우 해당 메서드를 정적 메서드라고 한다.
-정적 메서드는 class method나 static member field 조작을 위한 메소드이다.
-정적 메서드 내에서 클래스의 instance field나 method는 접근 불가능하다.
-정적 메서드는 특정 인스턴스에서는 작동되지 않으므로, 정적 메서드 내에서 this를 참조하면 컴파일 타임 오류가 발생한다.

Instance Method
-인스턴스 메서드는 클래스의 지정된 인스턴스에서 작동한다.
-인스턴스 메서드 내에서는 this로 액세스할 수 있다.

class ValueClass
{
private int value = 0;
public void setValue(int value) { this.value = value; }
public int getValue() { return this.value; }
public void print() { Console.WriteLine(“value={0}”, this.value);
public static void printString(string str) { Console.WriteLine(str); }
}
class Program
{
static void main(string[] args)
{
ValueClass c = new ValueClass();
c.setValue(10); // 인스턴스 메소드
c.print(); // 인스턴스 메소드
ValueClass.printString(“test”); // 정적 메소드 (클래스명.정적메소드명)
}
}

C# Array/ArrayList

Person[] pArray = new Person[5];

// 만약 Person 객체를 하나만 생성한 후 for문에서 공유해 사용할 경우
// 마지막으로 입력된 데이터로 모든 데이터값이 치환됨
Person p = new Person();
for (int i = 0; i < 5; i++) {
p.Name = Console.ReadLine();           // 입력정보
p.age = int.Parse(Console.ReadLine()); // 입력정보
pArray[i] = p // 리스트에 들어간 모든 원소는 동일한 p
}

 

Person[] pArray = new Person[5];
// 아래와 같이 for문 안에 Person p = new Person()와같이
// 새로운 객체를 생성해야 각자 다르게 입력된 정보가 들어가게 됨
for (int i = 0; i < 5; i++) {

Person p = new Person();
p.Name = Console.ReadLine();           // 입력정보
p.age = int.Parse(Console.ReadLine()); // 입력정보
pArray[i] = p; // 이때 p는 새로운 Person객체

}

 

0부터 100까지 숫자만 입력받기

int value; // needed for TryParse
string str; // needed for ReadLine

Console.Write(“0부터 100까지 숫자를 입력하세요: “);
str = Console.ReadLine();
while ((!int.TryParse(str, out value)) || (value < 0 || value > 100))
{

Console.Write(“다시 0부터 100까지 숫자를 입력하세요: “);
str = Console.ReadLine();

}
int result = int.Parse(str);
Console.WriteLine(“입력된 숫자=” + result);

ESCAPE 키가 눌린게 아니면 프로그램이 계속 실행되기

static double Add(double a, double b)
{

return (a + b);

}

static void Main(string[] args)
{

do
{

Console.Write(“a를 입력하세요: “);

string str = Console.ReadLine();
double a;
bool result = double.TryParse(str, out a);

Console.Write(“b를 입력하세요: “);
str = Console.ReadLine();
double b;
result = double.TryParse(str, out b);

double c = Add(a, b);
Console.WriteLine(“결과는 {0}”, c);

Console.WriteLine(“다시 하려면 ENTER 키를 누르시고 종료하려면 ESC 키를 누르세요”);


} while (Console.ReadKey().Key != ConsoleKey.Escape);

}