"Brett Romero" wrote...
I'd like to know when exactly the this. keyword is needed.
For example:
public class Combination
{
private long n = 0;
private long k = 0;
private long[] data = null;
public Combination(long n, long k)
{
if (n < 0 || k < 0) // normally n >= k
throw new Exception("Negative parameter in constructor");
this.n = n;
this.k = k;
this.data = new long[k];
for (long i = 0; i < k; ++i)
this.data[i] = i;
}
}
In the above code, I can see how this. may differentiate my class
scoped vars vs. parameters. If the class vars would have been nn and
kk instead of n and k, would this. still have been needed?
Not needed, but...
I've always viewed this. as useful for intelliparse but ultimately just
additional parsing. So I remove it.
If there are name conflicts between instance variables on one hand and local
variables on the other hand, you'll need "this" to differentiate between
them.
In such a short example as you provided you can't see the obvious benefit of
using "this", but as a system grows larger, you'll probably need more
descriptive names on both instance variables and local variables.
When that occurs it might be very handy to just use the same names for
variables with the same "meaning" regardless whether it's a local or
instance variable, and voila, the need for "this" occurs...
I wouldn't remove it, as it gives important information for other developers
that might look at your code. With the "this" keyword it's always obvious
that it's referring to an instance variable.
Without it, it may be more difficult to spot in large methods.
There's also other uses of the this keyword, such as when you're passing a
reference to the instance itself:
otherObject.SomeThing(this);
It's also used as a keyword when declaring indexers:
public long this [int index]
{
get
{
return this.data[index];
}
set
{
this.data[index] = value;
}
}
// Bjorn A