2

Especially about the "SA1126: PrefixCallsCorrectly" rule which tells us to use "this." prefix for instance members.

Should I follow these rules in the Razor syntax?

Example:

<span>Name: @this.Model.Name</span>

Or:

<span>@this.Html.DisplayFor(m => m.Name)</span>

You may notice that the "this." is ineffective here (I'm agree). I want to follow a rule which is applicable for all my everyday codes.

And doesn't StyleCop check the Razor files?

Amir Karimi
  • 5,401
  • 4
  • 32
  • 51

2 Answers2

2

Well, the usage of the "this" prefix is kind of a personal (which can be argumented) choice.

You can find an interesting discussion on this point here Why does StyleCop recommend prefixing method or property calls with "this"?

By the way, Resharper, for example, has the inverse rule by default (remove "useless" this - meaning useless for the compiler).

But frankly, in a View, I think it's more noise than help.

Other point : use HtmlHelpers like @Html.DisplayTextFor(m => m.Name) in your case, as they're strongly typed, linked to model, take care of null values, etc.

Community
  • 1
  • 1
Raphaël Althaus
  • 59,727
  • 6
  • 96
  • 122
1

Should I follow these rules in the Razor syntax?

If you have decided that it's worthwhile adding the "this" in your .cs files, why wouldn't you want to apply it to C# code elsewhere, such as embedded in a Razor view file? What if you were to have multiple lines of C# code in a @{ } block? Would the "this" start to seem more useful? (The issue of whether "this" is generally worthwhile is not particularly relevant here since you have presumably already standardized on using it.)

And doesn't StyleCop check the Razor files?

Nope, StyleCop does not check Razor files. The only parser currently included with StyleCop is a C# parser, which only examines files with a ".cs" extension.

Nicole Calinoiu
  • 20,843
  • 2
  • 44
  • 49
  • We are not sure it's worthwhile adding the "this." in our CS files yet. We are struck between choosing "this." or "underscore" prefixes. I used the "this." prefix for about a year but now I'm confused: what is the benefit of distinguishing instance and static members? Just recognizing the fields from parameters and local variables are enough that can be happened with a "underscore" prefix. As you know we like a standard which is applicable on all our C# codes even about the Razor. If it cause noise as Nicole said (I’m agree) so it seems better to remove the “this.” prefix rule at all. – Amir Karimi May 24 '12 at 16:38