When to use get; set; in c#

前端 未结 9 1219
庸人自扰
庸人自扰 2020-12-29 20:59

I\'m failing to understand what the difference is between initializing a variable, getting its value like this:

 //define a local variable.
   int i;

   i=          


        
9条回答
  •  南笙
    南笙 (楼主)
    2020-12-29 21:21

    Lets forget properties for a second... The real question you're asking (and you might not even know it) is why do you need properties (or getters and setters in some other languages) in the first place?

    It's to promote encapsulation.

    Properties just offer a nicer syntax for getters and setters, aka accessors (and indeed, a property just wraps set() and get() methods under the hood).

    In c# 3 the c# team came up with auto properties, because the vast number of properties don't do anything with the variables (no additional logic), so auto properties are short hand for that scenario.

提交回复
热议问题