본문 바로가기

.NET/C#

[C#] C# 은 this 를 사용하지 않는가?

this vs _ 

C# 에 입문하여 여러 코드를 읽는와중 독특한 점을 발견해서 글을 남긴다. 

  • 객체지향 언어의 대부분이 this 와 같은 키워드를 통해 자기 자신에 접근한다.
  •  그러나 C# 의 대부분의 코드가 클래스 내부 프로퍼티에 접근할때 this 를 사용하지 않고 바로 접근해서 사용한다.
this.name = name; // JAVA 와 같은 코드 
_name = name; // C# 의 경우

 

결론

  • 두 코드의 차이는 없으며 C# 커뮤니티에서는 전역변수에 언더스코어를 할당하여 선언하는것을 컨벤션으로 한다.
  • 언더스코어 사용시 코드의 간결함이 증가하기 때문이다.
  • this 를 사용하는 것도 당연히 가능하다.

 

in C#, both this.name = name and _name = name are ways to assign a value to a member variable in a class constructor. The choice between them typically depends on the coding style and personal preference of the developer or the conventions followed in the project.

Using this.name = name is an explicit way of indicating that you are assigning the name parameter value to the name member variable of the current instance of the class. This can be useful when there is a naming conflict between the parameter and the member variable. By using this, you explicitly refer to the instance variable.

On the other hand, _name = name directly assigns the name parameter value to the _name member variable without explicitly referencing the instance using this. Some developers prefer this approach when there are no naming conflicts, as it can lead to shorter and cleaner code.

Both approaches achieve the same result in terms of assigning values to member variables. It's mostly a matter of style and readability. The most important aspect is to be consistent within a codebase or project to maintain a coherent and easily understandable code.


There might be incorrect information or outdated content.

'.NET > C#' 카테고리의 다른 글

[C#] Parse 사용시 발생하는 이슈 🔥  (0) 2023.11.23
[C#] First, FirstOrDefault  (1) 2023.09.21
[C#] (delegate) Action & Func & Predicate  (0) 2023.08.18
[C#] delegate  (0) 2023.08.17
[C#] ref & out  (0) 2023.08.04