Code/C#

[C#] 간단한 Object Initializer 샘플 코드

Hide Code 2008. 2. 11. 17:16
Object Initializer를 이용하는 간단한 샘플코드이다.

아래에서 P1과 P2의 property에 값을 대입하는 방식을 살펴보라.


using System;

namespace Sample
{
   class Program
   {
       static void Main(string[] args)
       {
           Point P1 = new Point();
           P1.X = 2;
           P1.Y = 3;
           Console.WriteLine(P1.ToString());

           // Object Initializers
           Point P2 = new Point { X = 7, Y = 8 };
           Console.WriteLine(P2.ToString());
       }
   }

   public class Point
   {
       int x;
       public int X
       {
           get { return x; }
           set { x = value; }
       }

       int y;
       public int Y
       {
           get { return y; }
           set { y = value; }
       }

       public override string ToString()
       {
           return String.Format("({0}, {1})", X, Y);
       }
   }
}