C # myths about best practices?

My colleague tells me about the things listed in the comments.

I'm confused. Can someone please demystify these things for me?

class Bar
{
    private int _a;

    public int A
    {
        get { return _a; }
        set { _a = value; }
    }

    private Foo _objfoo;

    public Foo OFoo
    {
        get { return _objfoo; }
        set { _objfoo = value; }
    }

    public Bar(int a, Foo foo)
    {
        // this is a bad idea
        A = a;
        OFoo = foo;
    }

    // MYTHS
    private void Method()
    {
        this.A    //1 -
        this._a   //2 - use this when inside the class e.g. if(this._a == 2)
        A         //3 - use this outside the class e.g. barObj.A
        _a        //4 - 
                  // Not using this.xxx creates threading issues.
    }
}
class Foo
{
    // implementation
}
+5
source share
5 answers

this.is redundant if there is no name clash. You only need this when you need a reference to the current object or if you have an argument with the same name as the field.

Threading . , , , , , (!) this., .

+10

" this.xxx "

- . , , this .

" , , . if (this._a == 2)"

, . , , , . , (, List List, null, ).

+8

" " - . , , , .

+4

, , ? "" , -, .

, "this" , () . , "this", , , / . , , - .

" " "": : setter "A" , , A = a; , _a = a; . , - , .

Finally, the "threading problem" is nonsense - AFAIK "this" has nothing to do with threads.

+3
source

Number 2 is a myth that easily debunks, mentioning automatic properties. Automatic properties allow you to define a property without a support field, which is automatically generated by the compiler. So ask your colleague what his opinion is about automatic properties.

+2
source

All Articles