Is there an equivalent of this
in C# for static members?
I like to use this
to make my code more readable, but wondered if there was an equivalent for static members.
In C you do not have the this keyword. Only in C++ and in a class, so your code is C and you use your this variable as a local method parameter, where you access the array struct. Save this answer.
The ' |= ' symbol is the bitwise OR assignment operator.
The closest thing you can get is a struct .
I suppose if you use this.
to reinforce that you are referring to instance members, the equivalent in a static member would be to use ClassName.
But stylistically, why add code that doesn't change meaning?
edit to add various clarifications:
My last sentence above can be illustrated with these examples:
class Example1
{
public int J { get; set; }
public Example1()
{
J = 0;
}
// These two methods have *exactly* the same CIL
public int InstanceMethodLong()
{
return this.J;
}
public int InstanceMethodShort()
{
return J;
}
}
The this.
in InstanceMethodLong
does not change the meaning as compared with InstanceMethodShort
.
Statically:
class Example2
{
public static int K { get; set; }
static Example2()
{
K = 0;
}
// These two methods have *exactly* the same CIL
public int StaticMethodLong()
{
return Example2.K;
}
public int StaticMethodShort()
{
return K;
}
The Example2.
in StaticMethodLong
does not change the meaning as compared with StaticMethodShort
.
In both these cases, adding the qualifier results in the same CIL, the same behaviour, and is more source to write, read, and understand. Stylistically - and I will happily accept that this is a question of code style - I see no reason for it to be there.
With underscore prefixes the situation is slightly different:
class Example3
{
int _j;
public int J
{
get { return _j; }
set
{
_j = value;
// and do something else,
// to justify not using an auto-property
}
}
public Example3()
{
J = 0;
}
public int MethodWithParameter(int j)
{
// Now there is a *difference* between
return j;
// and
return _j;
}
}
Here, in MethodWithParameter
, there is a difference between referring to _j
and j
- so we are deliberately and explicitly expressing different meaning. It's true that the compiler doesn't care what we call our variable names, but it does care what variables we are referring to! So in the body of MethodWithParameter
, using or not using an underscore isn't just stylistic, it's semantic. Which isn't the particular issue we're addressing in this question.
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