Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice for C# Auto-Implemented Property and local variable that differ only by case?

Let me give you an example:

public class MyClass
{
    public string MyProperty { get; set; }

    public MyClass(string myProperty)
    {
        MyProperty = myProperty; // bad?
        this.MyProperty = myProperty; // good?
    }
}

I've taken to using this in this scenario, because I have minor paranoia that relying on case alone might be confusing or worse might actually lead to bugs.

What is the "best practice" here?

EDIT:

So far, it sounds like this is a lot more subjective than I thought. I figured people would come down strongly on one side or the other.

like image 832
devuxer Avatar asked Sep 30 '09 17:09

devuxer


2 Answers

Using "this." is redundant in any class. It's totally up to your development shop to set a standard for using it.

The pros of using "this." are that some developers find it easier to associate it in their mind with the class instance when they are reading the code, and as you mention, make it clearer when dealing with similarly named items.

The cons are that some people view it as cluttering up your code file and if you use tools like ReSharper, they mark it as redundant code by default.

like image 145
womp Avatar answered Oct 05 '22 04:10

womp


As womp said. "this" is redundant but it makes the code easier to read. Or rather harder to misread.

like image 43
Sani Singh Huttunen Avatar answered Oct 05 '22 05:10

Sani Singh Huttunen