C # - Difference between automatic property and return of support field?

A simple question, I think, but what is the difference between these lines of code:

Code 1

public int Temp { get; set; } 

and

Code 2

private int temp;
public int Temp { get { return temp; } }

I understand that the automatic property in accordance with code 1 will perform the same function as code 2?

I read Head First C # and it’s hard for me to understand why it uses two different ways to do the same?

+3
source share
5 answers

The main difference between your Code1 and Code2 is that in # 1 the property is configurable.

You can achieve the same by using automatic properties, because the installer may be closed:

public int Temp { get; private set; }

# 3 . , . - , .

+7

.

private int temp;
public int Temp { 
    get { return temp; } 
    set { temp = value; }
}

( , ), .
5 6 - .

,

public int Temp { get; private set; }
+2

"" - "" :

public int Temp { get; set; } 

,

public int Temp 
{   
   get { return _temp; }
   set { _temp = value; } 
}

. "", , .

+2

getter, setter, .

, , . , auto:

public int Temp { get; private set; }

, - . , .

+1

, , - . , , ..

, get set, . , , .

0
source

Source: https://habr.com/ru/post/1783402/


All Articles