Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I force the use of 'this' keyword in c# .NET?

Is there a way to force the use of the this keyword in Visual Studio when referencing current instance members?

Example with a bug in the constructor:

class MyClass
{
    public object Foo { get; set; }
    public MyClass(object foo)
    {
        Foo = Foo; // this should of course be lowercase but it's easy to miss
    }
}

This code will probably generate the infamous 'object reference not set to an instance of an object' exception somewhere later on.

How to make it work but still It's easy to miss:

class MyClass
{
    public object Foo { get; set; }
    public MyClass(object foo)
    {
        Foo = foo; // Valid syntax but unclear.
    }
}

This is valid syntax but it's easy to miss.

The syntax I'd like visual studio enforce:

class MyClass
{
    public object Foo { get; set; }
    public MyClass(object foo)
    {
        this.Foo = foo; // this is "safe". 
    }
}

If this convention is enforced i would have to type this.Foo = this.Foo to create the same type of bug as in the first example.

I always use the this keyword anyway since it makes my life easier while switching between c# and other languages so there wouldn't be any disadvantages at all.

like image 848
Jonas Stensved Avatar asked Aug 18 '11 09:08

Jonas Stensved


1 Answers

You can fix this simply by enabling "Treat warnings as errors":

Warning 2 Assignment made to same variable; did you mean to assign something else?

(CS1717 if you want to enable it just for this one)

The compiler already tells you about this; you should be reviewing the warnings (and aim for zero warnings).

Re the middle one being unclear:

Foo = foo;

I disagree - that is perfectly clear to me (unless you come from a VB background and have developed case-blindness).

like image 96
Marc Gravell Avatar answered Sep 27 '22 16:09

Marc Gravell