본문 바로가기
C#

[C#기초] setter/getter 함수

by Meaning_ 2021. 7. 19.
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
반응형

'C#' 카테고리의 다른 글

[C#기초] 가상함수/ 동적바인딩,정적바인딩  (0) 2021.08.14
[C# 기초] 다형성/상속  (0) 2021.07.27
[C#기초] 복사 생성자/ static  (0) 2021.07.27
[C#기초] 클래스와 구조체의 차이  (0) 2021.07.21
[C#기초] 참조  (0) 2021.07.19

댓글