Since variables declared inside a method are available only within that method, and variables declared private within a class are only available within a class. What is the purpose of the this
key word? Why would I want to have the following:
private static class SomeClass : ISomeClass
{
private string variablename;
private void SomeMethod(string toConcat)
{
this.variablename = toConcat+toConcat;
return this.variablename;
}
}
When this will do the exact same thing:
private static class SomeClass : ISomeClass
{
private string variablename;
private void SomeMethod(string toConcat)
{
variablename = toConcat+toConcat;
return variablename;
}
}
to practice my typing skills?
There can be 3 main usage of this keyword in C++. It can be used to pass current object as a parameter to another method. It can be used to refer current class instance variable. It can be used to declare indexers.
The this keyword refers to the current object in a method or constructor. The most common use of the this keyword is to eliminate the confusion between class attributes and parameters with the same name (because a class attribute is shadowed by a method or constructor parameter).
The this pointer is a pointer accessible only within the nonstatic member functions of a class , struct , or union type. It points to the object for which the member function is called. Static member functions don't have a this pointer.
If your C code program will always be built with a C compiler that is not a C++ compiler, then it makes no difference whether you use this as an identifier in your code. It is not a reserved identifier, so you are free to use it.
There are a couple of cases where it matters:
If you have a function parameter and a member variable with the same names, you need to be able to distinguish them:
class Foo {
public Foo(int i) { this.i = i; }
private int i;
}
If you actually need to reference the current object, rather than one of its members. Perhaps you need to pass it to another function:
class Foo {
public static DoSomething(Bar b) {...}
}
class Bar {
public Bar() { Foo.DoSomething(this); }
}
Of course the same applies if you want to return a reference to the current object
In your example it is purely a matter of taste, but here is a case where it is not:
private string SomeMethod(string variablename)
{
this.variablename = variablename;
return this.variablename;
}
Without this
, the code would work differently, assigning the parameter to itself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With