Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# using the "this" keyword in this situation?

Tags:

c#

oop

this

I've completed a OOP course assignment where I design and code a Complex Number class. For extra credit, I can do the following:

  1. Add two complex numbers. The function will take one complex number object as a parameter and return a complex number object. When adding two complex numbers, the real part of the calling object is added to the real part of the complex number object passed as a parameter, and the imaginary part of the calling object is added to the imaginary part of the complex number object passed as a parameter.

  2. Subtract two complex numbers. The function will take one complex number object as a parameter and return a complex number object. When subtracting two complex numbers, the real part of the complex number object passed as a parameter is subtracted from the real part of the calling object, and the imaginary part of the complex number object passed as a parameter is subtracted from the imaginary part of the calling object.

I have coded this up, and I used the this keyword to denote the current instance of the class, the code for my add method is below, and my subtract method looks similar:

 public ComplexNumber Add(ComplexNumber c)
{
    double realPartAdder = c.GetRealPart();
    double complexPartAdder = c.GetComplexPart();

    double realPartCaller = this.GetRealPart();
    double complexPartCaller = this.GetComplexPart();

    double finalRealPart = realPartCaller + realPartAdder;
    double finalComplexPart = complexPartCaller + complexPartAdder;

    ComplexNumber summedComplex = new ComplexNumber(finalRealPart, finalComplexPart);

    return summedComplex;
}

My question is: Did I do this correctly and with good style? (using the this keyword)?

like image 336
Alex Avatar asked Dec 04 '09 08:12

Alex


2 Answers

The use of the this keyword can be discussed, but it usually boils down to personal taste. In this case, while being redundant from a technical point of view, I personally think it adds clarity, so I would use it as well.

like image 66
Fredrik Mörk Avatar answered Oct 20 '22 21:10

Fredrik Mörk


Use of the redundant this. is encouraged by the Microsoft coding standards as embodied in the StyleCop tool.

like image 25
Steve Gilham Avatar answered Oct 20 '22 20:10

Steve Gilham