C#

[C#기초] setter/getter 함수

Meaning_ 2021. 7. 19. 00:40
728x90
반응형

 

보통 getter나 setter를 생각하면 get메서드, set메서드를 따로따로 가져오는데

C#의 경우 메서드 하나 만든 후 그 안에 set,get을 써주는 효율적인 방법이 있다!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
 class Student
    {
        private int studnetID;
        private String studentName;
        private int studentAge;
 
        public int StudentAge
        {
            set
            {
                studentAge = value;
            }
 
            get
            {
                return studentAge;
            }
        }
    }
    class program
    {
        
        static void Main(string[] args)
        {
            Student s1 = new Student();
            s1.StudentAge = 20;
            Console.WriteLine($"내 나이는 {s1.StudentAge}살이야!");
 
        }
 
    }
cs

 

728x90
반응형