C# coding guidelines: use "this." or not when referring to member fields/properties within the obje

D

Dave

I'm never quite sure whether to use "this." or not when referring to fields
or properties in the same class. It obviously works just fine without it
but sometimes I wonder if using this. consistently may make the code easier
to understand for someone else, etc. Using "this." makes it immediately
clear, for example, that the variable being referred to is a member of the
same class and is not declared in the method as a local variable.

Not a big deal but this has been on my mind since I've been coding C#.

Also, while I'm thinking about it: should a class internally reference
properties by the property name or by the private variable that stores the
value? I've done both. I suppose the main thing is if the property does
more than just set the value of the private variable then the class code
should use the property name instead of the private variable.

Does Microsoft's C# coding guidelines cover either of these questions?
Where can I find the most up-to-date copy of their C# coding guidelines?
 
S

sloan

I use this. Its just easier to maintain. Its not easier to type everytime,
but easier to come back to later.
Because I know when I'm authoring the code ... that its a member variable.
Editing,maintaining ...sometimes you might forget.

Go and google "brad abrams" "naming conventions".

...

On occasion,,, when I wrote vb.net code. I use the "Me." keyword. It looks
like crap, but its the same mentality as this.
vb'ers don't understand it... and I'm just like "its like java and c# with
the this word"

I dislike vb.net.... its just not as clean to me.

I do not like when people use the same names for their parameter/arg list...
and the member variable

public class Emp
private int empid;

public Emp ( int empid )//constructor
this.empid = empid;


I hate that crap. I also dont like

Exception exception = new Exception("bad");

when the only difference between the object and the variable is the case.

Anyways..... there are my thoughts.

I use m_empid ... I dont' really like the _empid .. but to each his own.

There are no 100% right answers all the time. One time I emailed Brad..and
he was just like "pick one and go with it".

...
 
M

Mythran

Dave said:
I'm never quite sure whether to use "this." or not when referring to
fields or properties in the same class. It obviously works just fine
without it but sometimes I wonder if using this. consistently may make the
code easier to understand for someone else, etc. Using "this." makes it
immediately clear, for example, that the variable being referred to is a
member of the same class and is not declared in the method as a local
variable.

Not a big deal but this has been on my mind since I've been coding C#.

Also, while I'm thinking about it: should a class internally reference
properties by the property name or by the private variable that stores the
value? I've done both. I suppose the main thing is if the property does
more than just set the value of the private variable then the class code
should use the property name instead of the private variable.

Does Microsoft's C# coding guidelines cover either of these questions?
Where can I find the most up-to-date copy of their C# coding guidelines?

I use a prefix for member variables so that I know by sight that the
variable I'm referencing is a member variable and not a local.

public class SomeClass
{
private int mMyInt;
public SomeClass() {
mMyInt = 5;
}
public int MyInt {
get {
return mMyInt;
}
set {
mMyInt = value;
}
}

public int Add(int Value)
{
return mMyInt + Value;
}
}

For the "this" keyword, I use when I "need" to use the property instead of
the member. For example, I create properties for non-member variables (such
as values stored in the Request property in web-based applications).

....
public int RecordId {
get {
object o = Request("id");
if (o == null) {
return 0;
} else {
return (int) o;
}
}
}
....

By doing this, I don't have to write code to perform the check. Heck, I
don't even have to remember the "id" key, just this.RecordId. Now, this is
where the "this" comes in for us. We use "this" when we access properties,
but not members. Because the "m" prefix for members allows us to identify
the variable as a member, we don't need "this" to further identify it. For
local variables, our shop-standards require they be camelcased while
parameter names are pascalcased.

This is our standard for our shop, not everyones choice (and the parameter
being pascal cased instead of camel cased is against the Capitalization
Conventions for the .Net Framework....)

See: http://msdn2.microsoft.com/en-US/library/ms229002(VS.80).aspx

HTH :)

Mythran
 
B

Bruce Wood

I use "this." everywhere for clarity. It just helps me know what is a
field of the current class and what isn't, particularly when I'm
staring at paper printouts on the bus. :)

The second question is one of functionality, as you pointed out.
Usually you want to work directly with the field, since it's part of
your private state. However, sometimes you want the property, because
you want extra functionality that it provides. It all depends upon your
design and what's going on in your class.
 
D

Dave

Good point about printouts. I think I'm convinced. I'll start using this.
everywhere.

As the other guy said, as with most coding conventions, the most important
thing is to be consistent.
 
M

Mehdi

I'm never quite sure whether to use "this." or not when referring to fields
or properties in the same class. It obviously works just fine without it
but sometimes I wonder if using this. consistently may make the code easier
to understand for someone else, etc. Using "this." makes it immediately
clear, for example, that the variable being referred to is a member of the
same class and is not declared in the method as a local variable.

If you follow Microsoft coding guidelines, member variables, local
variables and function parameters will have the same naming convention
making it impossible to differentiate between them at first sight. When i
started coding in C#, i followed these conventions and hence always used
"this" in order to make it clear that i was accessing a member variable.

I then got tired of it and reverted to prefixing all my member variables
with "m_". It's ugly but at least it makes it immediately obvious to
anybody that a member variable is being involved and it removes the need
for the "this" (that you can far too easily forget to type).

Whether or not you're using "this" in your programs really depends on the
naming conventions you've chosen to follow.
 
J

Jon Skeet [C# MVP]

Mehdi said:
If you follow Microsoft coding guidelines, member variables, local
variables and function parameters will have the same naming convention
making it impossible to differentiate between them at first sight.

Where does MS specify the local variable and non-public member variable
guidelines?

I'm aware of http://tinyurl.com/2cun but that doesn't include member
variables or local variables.
 
K

Kevin Spencer

It makes no difference to the compiler. Use it to make your code easier to
read, and when it will do so.

--
HTH,

Kevin Spencer
Microsoft MVP
Professional Numbskull

Hard work is a medication for which
there is no placebo.
 
M

Mehdi

Where does MS specify the local variable and non-public member variable
guidelines?

I'm aware of http://tinyurl.com/2cun but that doesn't include member
variables or local variables.

There's this <http://msdn2.microsoft.com/en-US/library/ms229012.aspx> but
it indeed only mentions public and protected fields. I might have read the
naming convention documents a bit to quickly at the time. But i'm pretty
sure that most sample .NET code and applications i've seen from Microsoft
used camel casing without any prefix for private variables (i agree that
this does not mean that this is a general convention).
 
J

James Park

I prefer an underscore prefix to using "this." for fields. The problem I had
was that I'd forget to use it consistently, and I'd see a field and think it
was a local variable.
 
M

Martijn Mulder

this is silly. I only use it to direct all constructor to one
'master'-constructor.

In the book Programming .NET Components from O'Reilly, Appendix E gives a C#
coding standard. A quick scan over it didn't reveal any use of this.
 
G

Guest

I use the "this" keyword extensively. Especially since if I am having a
Senior Moment and I type "this." Intellisense gives me a wonderful
recuperative experience.
;-)
 
M

Michael C

Dave said:
Also, while I'm thinking about it: should a class internally reference
properties by the property name or by the private variable that stores the
value? I've done both. I suppose the main thing is if the property does
more than just set the value of the private variable then the class code
should use the property name instead of the private variable.

You should do whatever is appropriate for each situation but favour the
private variable for sure. There is no point repeatedly calling a property
to do the same thing unless there is a good reason.

Michael
 
K

Kevin Spencer

Hey, I do that too!

--
:-D,

Kevin Spencer
Microsoft MVP
Professional Numbskull

Hard work is a medication for which
there is no placebo.
 
J

Jon Skeet [C# MVP]

Michael C said:
You should do whatever is appropriate for each situation but favour the
private variable for sure.

I completely disagree.
There is no point repeatedly calling a property
to do the same thing unless there is a good reason.

For me, a good reason is: "there may not be any validation now, but I
suspect there might be in the future".

If all your code accesses the data via the property, you know there's
only one place where it's set, so you can always put the validation
there. You can also add a normal breakpoint to find out when it's set.
(IIRC in VS 2005 there are breakpoints for when variables change value
- I haven't tried to use them yet. I suspect they're not quite as easy
as just clicking on the bar on the appropriate line though :)

This is why I've got a feature request in for variables which are
compiled to normal private fields, but from C#'s point of view are
private to the property:

public int Foo
{
int foo;

public get { return foo; }
public set { foo = value; }
}

void DoSomething()
{
// This wouldn't work
// foo = 20;

// This would be fine
Foo = 20;
}

For serialization purposes and some other special cases, you might need
some way (an attribute?) of overriding this restriction for certain
methods. (Constructors would almost certainly have to have access to
the raw variables.)
 
M

Michael C

Jon Skeet said:
For me, a good reason is: "there may not be any validation now, but I
suspect there might be in the future".

It all depends on the situation but I think it is rare that the class itself
needs to access the variable though the property. There is no point turning
a high speed variable access into a slower function call every time just in
case something might change in the future. If it does change and it becomes
appropriate to use the property then modify the code.

Michael
 
J

Jon Skeet [C# MVP]

Michael C said:
It all depends on the situation but I think it is rare that the class itself
needs to access the variable though the property.

Whereas I believe it's rare that it would need any potential speed
increases of *not* accessing the variable through the property.
There is no point turning
a high speed variable access into a slower function call every time just in
case something might change in the future.

What makes you think that the property access would be slower? The JIT
is quite capable of inlining property access - and if the property
setter does significant work which would prevent inlining, then chances
are you want that validation etc to take place on every set anyway. I
believe that bypassing the property for the sake of micro-optimisation
is a bad idea.

The time when it makes sense to bypass the property is when you really
*want* to bypass validation, for instance if you want to set multiple
interdependent variables, and changing any one of them alone to the new
value would be invalid. That should be the exception, not the rule.
If it does change and it becomes appropriate to use the property then
modify the code.

Why store up work for later? It's just as *easy* to use the property as
the variable when you first write the code, and gives immediate
advantages in terms of simplicity of debugging, IMO.
 
B

Bruce Wood

There is no point turning a high speed variable access into a slower function call every time just in case something might change in the future.

Only in debug mode. One of Bruce's Laws is "never try to
micro-optimize... the compiler is much smarter than you are!" :)

In this case, somewhere in the compiler / JITter sequence the call to
the property getter is reduced to a simple variable access, so there is
no difference in performance whatsoever for release-compiled code.

That said, I'm not sure I agree with Jon. The property setter may
include functionality that you explicitly *don't* wan't to invoke from
within the class, like raising ...Changed events and things like that.
It all depends upon what you're doing and why, and how you want to
timing of things to work out. I have plenty of classes that want to
manipulate their state in some way and _only then_ determine which
....Changed events to raise as a result. I have other classes that
always set their own fields through the property setters specifically
in order to invoke additional behaviour such as ...Changed events.

It all depends upon what the setter does and what your class is trying
to do.
 
N

Nick Hounsome

Forget senior moments - intellisense elliminates tyops.... I mean typos!
Also, with forms, I often forget what everything is called (this is why I
like prefixes for fields).
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top