Don’t use „this.“ to address your object attributes

Veröffentlicht von

In my actual customer project, we’re using the „this“ convention to address our object attributes. There are other conventions to mark your object attributes like

  • the „_“-prefix, or
  • the „m“-prefix

I didn’t bother using which convention since I was always the opinion it is more a style related issue. Yesterday my opinion changed. What happened? During some system integration tests, I had to do some code refactorings. Since time was short I hadn’t an appropriate unit test for the class I was refactoring … After I had done the refactorings I tested the new software via an integration test and realized a NullReferenceException that can’t be caused by my refactoring. After attaching to the software via the remote debugger (which is always a clear sign that a lot of things went wrong …), I wasn’t a step closer why the exception was raised. So, I decided to diff my working copy and check if there are some changes that I was not aware of. Diffing the working copy lead me to a CTOR code that was similar to this code snippet:



public class Person
   public Person (
        string firstName,
        string secondNam)
        this.firstName = firstName;
        this.secondName = secondName;


So what is the problem with this code?

The problem relies in the assignment of secondName. Well, secondName is null. But why? It is assigned to the value given by parameter secondName, right?. It is not! During my refactoring I (misleadingly) removed the last character of the parameter. So secondName became secondNam. And thats a huge problem, because now we’re assigning this.secondName to (this.)secondName, which of course is initialized to null!

And now we see why the „this“-convention is not only a style thing. If I had used a „_“- or „m“-prefix for my object attributes I could detect this problem at compile-time, because the assignment changes to „_secondName = secondName„. Since secondName is not defined as parameter the compiler throws an error.

Personal lessons learned: NEVER use this to address your object attributes, ALWAYS use a „_“- or „m“-prefix!


Kommentar hinterlassen

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert.