Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Code Style: Switching from "this." prefix to "underscore" [closed]

I've been using the "this." prefix for about two years (StyleCop SA1102 rule). But now I'm changing my mind and using the "underscore" prefix for static and instance private fields and remove the "this." prefix.

Here my reasons to switch from "this." to "underscore":

  1. Breaks Easily: Nobody in your team will always use "this." prefix so when you see a project which followed this style you will not see "this." prefix for all instance members.
  2. Useless Distinguish: What is the benefit of distinguishing between instance and static fields? Do you ever gain anything of that?
  3. Noise : If you take care of using "this." prefix, you'll see "this" every where. For instance we had 77 times of "this" keyword in a class but after changing our style we just have 9 underscores and I think the code is more readable (you can easily follow the code logic).
  4. Razor: It seems ugly to use "this." prefix in the Razor C# codes. For instance you will have "@this.Html.Something" instead of "@Html.Something". And we like a general rule to apply on all of our C# codes everywhere.

What is your idea?

Is it reasonable to ignore the StyleCop SA1102 rule ("this." prefix) and use the "underscore" prefix to distinguish class fields?

like image 674
Amir Karimi Avatar asked Dec 28 '22 00:12

Amir Karimi


1 Answers

All of you points will apply to underscore as well (it needs to be enforced, not that useful, etc.), and if you changed 77 'this' to 9 _ - you could've gone with 9 'this' as well, I'm sure.

Knowing if this is an instance or static field/property is pretty useful, imo, esp. in multithreaded environment.

However, when I see 'this' - I know exactly what it means; with underscore.. I can guess, but at this point it really depends on how consistent you are.

Personally, I often (not always) use 'this' just to distinguish local variables from class properties, esp. if method is long.

At the end of the day this is just a recommendation, if you and your team feel comfortable with underscore - use that.

like image 74
Evgeni Avatar answered Feb 01 '23 14:02

Evgeni