Any reason to write the "private" keyword in C#? - c#

As far as I know, private is the default everywhere in C# (meaning that if I don't write public, protected, internal, etc. it will be private by default). (Please correct me if I am wrong.)
So, what's the reason to write that keyword, or why does it even exist for members?
For example, when an event handler is auto-generated it looks like this:
private void RatTrap_MouseEnter(object sender, CheeseEventArgs e)
{
}
But why does it even write private if that's implied and default? Just so that novice developers (who don't know it's the C# default) know that it's private? Or is there a difference for the compiler?
Moreover, is there a case where writing "private" (alone) will change the accessibility of the member?

AFAIK, private is the default everywhere in C# (meaning that if I don't write public, protected, internal, etc. it will be private by default). (please correct me if wrong).
This is not true. Types defined within a namespace (classes, structs, interfaces, etc) will be internal by default. Also, members within different types have different default accessibilities (such as public for interface members). For details, see Accessibility Levels on MSDN.
Also,
So, what's the reason to write that keyword, or why does it even exist?
Specifying this explicitly helps denote your intention to make the type private, very explicitly. This helps with maintainability of your code over time. This can help with other developers (or yourself) knowing whether a member is private by default or on purpose, etc.

AFAIK, private is the default everywhere in C#
Not quite - the default is "the most restricted access available for this declaration". So for example, with a top-level type the default is internal; for a nested type the default is private.
So, what's the reason to write that keyword, or why does it even exist?
It makes it explicit, which is good for two reasons:
It makes it clearer for those who don't know the defaults, as per your question (I've never liked this argument, personally, but I figured it's worth mentioning)
It gives an impression that you've deliberately decided to make it private, rather than just gone with the defaults.
As for your last part:
Moreover is there a case where writing "private" (alone) will change the accessibility of the member?
Yes, for making half of a property more restrictive than the other:
// Public getter, public setter
public int Foo { get; set; }
// Public getter, private setter
public int Bar { get; private set; }
I used to go with defaults everywhere I could, but I've been convinced (partly by Eric Lippert) that making it clear that you've thought about it and decided to make something private is a good idea.
Personally I wish there were a way of doing that for sealed / unsealed, too, for type declarations - possibly not even have a default. I suspect that many developers (myself included if I'm not careful) leave classes unsealed just because it's less effort than making them sealed.

private adds visual clutter. To those who insist that it makes things explicit, I would ask: Do you do this with mathematics, too? For instance:
var answer = a + b / c;
Do you find that unclear without redundant parentheses around b / c?
The rule in C# is very simple: By default, everything is as close to private as it can be. So if you need something to be more visible than the default, add a modifier. Otherwise, don't add needless keywords to your code.

As far as I know, private is the default everywhere in C#
Explicitly declaring private, means you know it is private. Not just think it is, because as far as you know, it is the default. It also means that someone else who looks at the code knows what it is.
There is no "I think it is", "I'm pretty sure it is", etc. It just is. And everyone is on the same page.
I am not a C# developer. If I had to work with some code that wasn't explicitly declared private, I would probably assume it was internal.
I dislike when things are implicitly set. It's never as clear as when they are explicitly set.

Readability - Not everyone may know that private is the default behaviour.
Intent - Gives a clear indication that you have specifically declared the property private (for whatever reason).

Readability, demonstration of intent are two great reasons I can think of.

One good reason for explicitly specifying the visibility is so that you don't have to think about what is the default for the context you are in.
Another good reason is because FxCop tells you to do it.

A lot of people (people like me!) regularly program in a handful of different languages. Being explicit with things like these prevents me from needing to remember all the arcane details of all the languages I program in.

I'd say for consistency with the readability of the scope of the rest of the class.

I like to explicitly add the private keyword so that I know it's private. Plus, private isn't always the default access specifier everywhere. Also, you can use private set in properties to effectively make a read-only property that can only be set by the class it was declared in.

Related

Is there a need for this. and me. on properties [duplicate]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
Locked. This question and its answers are locked because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
I was curious about how other people use the this keyword. I tend to use it in constructors, but I may also use it throughout the class in other methods. Some examples:
In a constructor:
public Light(Vector v)
{
this.dir = new Vector(v);
}
Elsewhere
public void SomeMethod()
{
Vector vec = new Vector();
double d = (vec * vec) - (this.radius * this.radius);
}
I don't mean this to sound snarky, but it doesn't matter.
Seriously.
Look at the things that are important: your project, your code, your job, your personal life. None of them are going to have their success rest on whether or not you use the "this" keyword to qualify access to fields. The this keyword will not help you ship on time. It's not going to reduce bugs, it's not going to have any appreciable effect on code quality or maintainability. It's not going to get you a raise, or allow you to spend less time at the office.
It's really just a style issue. If you like "this", then use it. If you don't, then don't. If you need it to get correct semantics then use it. The truth is, every programmer has his own unique programing style. That style reflects that particular programmer's notions of what the "most aesthetically pleasing code" should look like. By definition, any other programmer who reads your code is going to have a different programing style. That means there is always going to be something you did that the other guy doesn't like, or would have done differently. At some point some guy is going to read your code and grumble about something.
I wouldn't fret over it. I would just make sure the code is as aesthetically pleasing as possible according to your own tastes. If you ask 10 programmers how to format code, you are going to get about 15 different opinions. A better thing to focus on is how the code is factored. Are things abstracted right? Did I pick meaningful names for things? Is there a lot of code duplication? Are there ways I can simplify stuff? Getting those things right, I think, will have the greatest positive impact on your project, your code, your job, and your life. Coincidentally, it will probably also cause the other guy to grumble the least. If your code works, is easy to read, and is well factored, the other guy isn't going to be scrutinizing how you initialize fields. He's just going to use your code, marvel at it's greatness, and then move on to something else.
There are several usages of this keyword in C#.
To qualify members hidden by similar name
To have an object pass itself as a parameter to other methods
To have an object return itself from a method
To declare indexers
To declare extension methods
To pass parameters between constructors
To internally reassign value type (struct) value.
To invoke an extension method on the current instance
To cast itself to another type
To chain constructors defined in the same class
You can avoid the first usage by not having member and local variables with the same name in scope, for example by following common naming conventions and using properties (Pascal case) instead of fields (camel case) to avoid colliding with local variables (also camel case). In C# 3.0 fields can be converted to properties easily by using auto-implemented properties.
I only use it when absolutely necessary, ie, when another variable is shadowing another. Such as here:
class Vector3
{
float x;
float y;
float z;
public Vector3(float x, float y, float z)
{
this.x = x;
this.y = y;
this.z = z;
}
}
Or as Ryan Fox points out, when you need to pass this as a parameter. (Local variables have precedence over member variables)
Personally, I try to always use this when referring to member variables. It helps clarify the code and make it more readable. Even if there is no ambiguity, someone reading through my code for the first time doesn't know that, but if they see this used consistently, they will know if they are looking at a member variable or not.
I use it every time I refer to an instance variable, even if I don't need to. I think it makes the code more clear.
I can't believe all of the people that say using it always is a "best practice" and such.
Use "this" when there is ambiguity, as in Corey's example or when you need to pass the object as a parameter, as in Ryan's example. There is no reason to use it otherwise because being able to resolve a variable based on the scope chain should be clear enough that qualifying variables with it should be unnecessary.
EDIT: The C# documentation on "this" indicates one more use, besides the two I mentioned, for the "this" keyword - for declaring indexers
EDIT: #Juan: Huh, I don't see any inconsistency in my statements - there are 3 instances when I would use the "this" keyword (as documented in the C# documentation), and those are times when you actually need it. Sticking "this" in front of variables in a constructor when there is no shadowing going on is simply a waste of keystrokes and a waste of my time when reading it, it provides no benefit.
I use it whenever StyleCop tells me to. StyleCop must be obeyed. Oh yes.
Any time you need a reference to the current object.
One particularly handy scenario is when your object is calling a function and wants to pass itself into it.
Example:
void onChange()
{
screen.draw(this);
}
I tend to use it everywhere as well, just to make sure that it is clear that it is instance members that we are dealing with.
I use it anywhere there might be ambiguity (obviously). Not just compiler ambiguity (it would be required in that case), but also ambiguity for someone looking at the code.
Another somewhat rare use for the this keyword is when you need to invoke an explicit interface implementation from within the implementing class. Here's a contrived example:
class Example : ICloneable
{
private void CallClone()
{
object clone = ((ICloneable)this).Clone();
}
object ICloneable.Clone()
{
throw new NotImplementedException();
}
}
Here's when I use it:
Accessing Private Methods from within the class (to differentiate)
Passing the current object to another method (or as a sender object, in case of an event)
When creating extension methods :D
I don't use this for Private fields because I prefix private field variable names with an underscore (_).
[C++]
I agree with the "use it when you have to" brigade. Decorating code unnecessarily with this isn't a great idea because the compiler won't warn you when you forget to do it. This introduces potential confusion for people expecting this to always be there, i.e. they'll have to think about it.
So, when would you use it? I've just had a look around some random code and found these examples (I'm not passing judgement on whether these are good things to do or otherwise):
Passing "yourself" to a function.
Assigning "yourself" to a pointer or something like that.
Casting, i.e. up/down casting (safe or otherwise), casting away constness, etc.
Compiler enforced disambiguation.
You should always use it, I use it to diferantiate private fields and parameters (because our naming conventions state that we don't use prefixes for member and parameter names (and they are based on information found on the internet, so I consider that a best practice))
I use it when, in a function that accepts a reference to an object of the same type, I want to make it perfectly clear which object I'm referring to, where.
For example
class AABB
{
// ... members
bool intersects( AABB other )
{
return other.left() < this->right() &&
this->left() < other.right() &&
// +y increases going down
other.top() < this->bottom() &&
this->top() < other.bottom() ;
}
} ;
(vs)
class AABB
{
bool intersects( AABB other )
{
return other.left() < right() &&
left() < other.right() &&
// +y increases going down
other.top() < bottom() &&
top() < other.bottom() ;
}
} ;
At a glance which AABB does right() refer to? The this adds a bit of a clarifier.
In Jakub Šturc's answer his #5 about passing data between contructors probably could use a little explanation. This is in overloading constructors and is the one case where use of this is mandatory. In the following example we can call the parameterized constructor from the parameterless constructor with a default parameter.
class MyClass {
private int _x
public MyClass() : this(5) {}
public MyClass(int v) { _x = v;}
}
I've found this to be a particularly useful feature on occasion.
I got in the habit of using it liberally in Visual C++ since doing so would trigger IntelliSense ones I hit the '>' key, and I'm lazy. (and prone to typos)
But I've continued to use it, since I find it handy to see that I'm calling a member function rather than a global function.
I tend to underscore fields with _ so don't really ever need to use this. Also R# tends to refactor them away anyway...
I pretty much only use this when referencing a type property from inside the same type. As another user mentioned, I also underscore local fields so they are noticeable without needing this.
I use it only when required, except for symmetric operations which due to single argument polymorphism have to be put into methods of one side:
boolean sameValue (SomeNum other) {
return this.importantValue == other.importantValue;
}
[C++]
this is used in the assignment operator where most of the time you have to check and prevent strange (unintentional, dangerous, or just a waste of time for the program) things like:
A a;
a = a;
Your assignment operator will be written:
A& A::operator=(const A& a) {
if (this == &a) return *this;
// we know both sides of the = operator are different, do something...
return *this;
}
this on a C++ compiler
The C++ compiler will silently lookup for a symbol if it does not find it immediately. Sometimes, most of the time, it is good:
using the mother class' method if you did not overloaded it in the child class.
promoting a value of a type into another type
But sometimes, You just don't want the compiler to guess. You want the compiler to pick-up the right symbol and not another.
For me, those times are when, within a method, I want to access to a member method or member variable. I just don't want some random symbol picked up just because I wrote printf instead of print. this->printf would not have compiled.
The point is that, with C legacy libraries (§), legacy code written years ago (§§), or whatever could happen in a language where copy/pasting is an obsolete but still active feature, sometimes, telling the compiler to not play wits is a great idea.
These are the reasons I use this.
(§) it's still a kind of mystery to me, but I now wonder if the fact you include the <windows.h> header in your source, is the reason all the legacy C libraries symbols will pollute your global namespace
(§§) realizing that "you need to include a header, but that including this header will break your code because it uses some dumb macro with a generic name" is one of those russian roulette moments of a coder's life
'this.' helps find members on 'this' class with a lot of members (usually due to a deep inheritance chain).
Hitting CTRL+Space doesn't help with this, because it also includes types; where-as 'this.' includes members ONLY.
I usually delete it once I have what I was after: but this is just my style breaking through.
In terms of style, if you are a lone-ranger -- you decide; if you work for a company stick to the company policy (look at the stuff in source control and see what other people are doing). In terms of using it to qualify members, neither is right or wrong. The only wrong thing is inconsistency -- that is the golden rule of style. Leave the nit-picking others. Spend your time pondering real coding problems -- and obviously coding -- instead.
I use it every time I can. I believe it makes the code more readable, and more readable code equals less bugs and more maintainability.
When you are many developers working on the same code base, you need some code guidelines/rules. Where I work we've desided to use 'this' on fields, properties and events.
To me it makes good sense to do it like this, it makes the code easier to read when you differentiate between class-variables and method-variables.
It depends on the coding standard I'm working under. If we are using _ to denote an instance variable then "this" becomes redundant. If we are not using _ then I tend to use this to denote instance variable.
I use it to invoke Intellisense just like JohnMcG, but I'll go back and erase "this->" when I'm done. I follow the Microsoft convention of prefixing member variables with "m_", so leaving it as documentation would just be redundant.
1 - Common Java setter idiom:
public void setFoo(int foo) {
this.foo = foo;
}
2 - When calling a function with this object as a parameter
notifier.addListener(this);
There is one use that has not already been mentioned in C++, and that is not to refer to the own object or disambiguate a member from a received variable.
You can use this to convert a non-dependent name into an argument dependent name inside template classes that inherit from other templates.
template <typename T>
struct base {
void f() {}
};
template <typename T>
struct derived : public base<T>
{
void test() {
//f(); // [1] error
base<T>::f(); // quite verbose if there is more than one argument, but valid
this->f(); // f is now an argument dependent symbol
}
}
Templates are compiled with a two pass mechanism. During the first pass, only non-argument dependent names are resolved and checked, while dependent names are checked only for coherence, without actually substituting the template arguments.
At that step, without actually substituting the type, the compiler has almost no information of what base<T> could be (note that specialization of the base template can turn it into completely different types, even undefined types), so it just assumes that it is a type. At this stage the non-dependent call f that seems just natural to the programmer is a symbol that the compiler must find as a member of derived or in enclosing namespaces --which does not happen in the example-- and it will complain.
The solution is turning the non-dependent name f into a dependent name. This can be done in a couple of ways, by explicitly stating the type where it is implemented (base<T>::f --adding the base<T> makes the symbol dependent on T and the compiler will just assume that it will exist and postpones the actual check for the second pass, after argument substitution.
The second way, much sorter if you inherit from templates that have more than one argument, or long names, is just adding a this-> before the symbol. As the template class you are implementing does depend on an argument (it inherits from base<T>) this-> is argument dependent, and we get the same result: this->f is checked in the second round, after template parameter substitution.
You should not use "this" unless you absolutely must.
There IS a penalty associated with unnecessary verbosity. You should strive for code that is exactly as long as it needs to be, and no longer.

Why do members of a static class need to be declared as static? Why isn't it just implicit?

Obviously there can't be an instance member on a static class, since that class could never be instantiated. Why do we need to declare members as static?
I get asked questions like this all the time. Basically the question boils down to "when a fact about a declared member can be deduced by the compiler should the explicit declaration of that fact be (1) required, (2) optional, or (3) forbidden?"
There's no one easy answer. Each one has to be taken on a case-by-case basis. Putting "static" on a member of a static class is required. Putting "new" on a hiding, non-overriding method of a derived class is optional. Putting "static" on a const is forbidden.
Briefly considering your scenario, it seems bizarre to make it forbidden. You have a whole class full of methods marked "static". You decide to make the class static and that means you have to remove all the static modifiers? That's weird.
It seems bizarre to make it optional; suppose you have a static class and two methods, one marked static, one not. Since static is not normally the default, it seems natural to think that there is intended to be a difference between them. Making it optional seems to be potentially confusing.
That leaves making it required, as the least bad of the three options.
See http://blogs.msdn.com/b/ericlippert/archive/2010/06/10/don-t-repeat-yourself-consts-are-already-static.aspx for more thoughts on these sorts of problems.
Because by definition, all of their members must be static. They decided not to give some confusing syntactic sugar.
I would go one step further and ask: Why does C# have static classes at all? It seems like a weird concept, a class that's not really a class. It's just a container, you can't use it to type any variables, parameters or fields. You also can't use it as a type parameter. And of course, you can never have an instance of such a class.
I'd rather have modules, like in VB.NET and F#. And then, the static modifier would not be necessary to avoid confusion.
It could be implicit, but also it would complicate code reading and lead to confusions.
Richard,
Hmmmm... I'd guess that the language designers decided that it would be better to be very, very explicit... to avert any possible confusion when a maintainer, who doesn't know the code, jumps into the middle of a static class, and presumes that they are in a "normal" instance context.
But of course, that's just a guess. Most IDE's help you out there anyway, by adding the static modifier "automagically"... or at least highlighting your mistake at "write time", as apposed to "compile time".
It's a good question... unfortunately not one with a "correct" answer... unless someone can turn up a link from a C#-language-designers blog (or similar) discussing this decision. What I can tell you is: "I'd bet $1,000 that it's no accident."
Cheers. Keith.
Explicit coding makes things maintainable
If I want to copy a method from one class to another, so that code is better organized, then I would have to keep cheking a lot of things all the time, just in case the destination class is or is not static.
By declaring the member as static, you also have a visual indication of what the code is, when you see it.
It is also less confusing. Imagine a class that is static, and inside it has got members marked as static, and others not marked.
I can see lots of reasons, and many other reasons exist.
One reason I would think it is important to explicitly state it is a static is because in a multi-threaded programming model, these static variables are shared by multiple threads. When doing code review or code analysis, it is much easier to pick up this importance from reading the variable, instead of looking up the class declaration, and determine if the variables are static or non-static. It can get pretty confusing when reading variable during code review if you don't know if the class is static or non-static.
This is because copy-paste would be more complicated.
If you copy a method from a static class to a non-static class then you would have to add the static keyword.
If you copy a method from a non-static class to a static class you would have to remove the static keyword.
Moving methods around is the primary thing developers do ('I need to refactor this code, it will take a week at least'), and by making it easier Eric and his team allowed us to save hours of work.

FxCop - CA1034 error - WHY?

I am running static code analysis with FxCop 1.36 and I keep getting warning CA1034: NestedTypesShouldNotBeVisible.
I would understand if the parent class were declared as internal or private, but it is public. Why would it be bad for TimerReset to be declared public?
Am I missing something, or is this something that can be ignored?
Thanks for any input!
Here is an excerpt of the code causing this warning:
namespace Company.App.Thing
{
public partial class Page : XtraPage
{
public delegate void TimerResetDelegate(object sender, EventArgs e);
private TimerResetDelegate _timerReset;
public Page()
{
InitializeComponent();
}
public TimerResetDelegate TimerReset
{
set
{
if (null != (_timerReset = value))
{
checkBox.Click += new EventHandler(_timerReset);
textField.Click += new EventHandler(_timerReset);
textField.KeyDown += new KeyEventHandler(_timerReset);
TimeField.Click += new EventHandler(_timerReset);
TimeField.KeyDown += new KeyEventHandler(_timerReset);
}
}
}
}
}
Generally speaking, Nested Types are harder to 'discover'.
E.g. To use your nested type, I will have to write following
Page.TimerResetDelegate timer = new Page.TimerResetDelegate();
Even though above is valid C# code, it doesn't read like the usual type usage.
Nested Types are generally used when you want to define a type to be used internally and you would avoid code like above. This is the reason why FxCop is giving you warning. If you want, you can ignore it. Personally, I would keep my Nested types as private. If I expect caller to make use of the type, I will move them to a proper namespace.
Why would it be bad for TimerReset to be declared public?
Exactly as the description states:
Nested types are useful for encapsulating private implementation details of the containing type. Used for this purpose, nested types should not be externally visible.
Since you're exposing TimerResetDelegate publically with TimerReset, I guess it's not an implementation detail.
Do not use externally visible nested types for logical grouping or to avoid name collisions; instead, use namespaces.
Which makes it look like you're using a nested type for grouping. As FxCop states, use a namespace instead.
Nested types include the notion of member accessibility, which some programmers do not understand clearly.
Since TimerResetDelegate is a delegate, this doesn't really apply.
Move TimerResetDelegate to it's own TimeResetDelegate.cs file, and put it in your Company.App.Thing namespace. Then, it's no longer nested.
Of course, it'd be even better to just go with EventHandler instead of defining your own delegate type.
It is because your delegate is a type, but it is defined within the Page class. I would just define it in the Company.App.Thing namespace, but it is not a problem really. If you were writing an API it would just make it a bit messy, that's all.
Also, it is a bit odd to return the delegate like that, but I guess I don't really know what you are trying to accomplish.
IMHO, this is an FxCop rule that can be ignored.
There is nothing wrong from a CLR level with having a nested class. It is just a guideline rule added to FxCop because the authors felt it was less usable or a poorer design than making the class non-nested.
Apparently it doesn't like the idea of nested classes, when they might be used outside the context of your Page class.
I personally agree with that in principle, though I can imagine some exceptions where it might be desirable.

Should you always refer to local class variables with "this"

In C# you can refer to values in a class using the 'this' keyword.
class MyClass
{
private string foo;
public string MyMethod()
{
return this.foo;
}
}
While I presume the answer will likley be user preference, is it best practice to use the this keyword within a class for local values?
In the spirit of DRY, I would say this is not a particularly useful practice in general. Almost any use of this can be shortened to an equivalent expression by just removing the this.
One exception is if you have a local parameter which happens to have the same name as another class member; in that case you must distinguish between the two with this. But this is a situation you can easily avoid, by simply renaming the parameter.
I use the this keyword almost only when some member is hiding another, and when I need to pass the current class instance to a method for example:
class Employee
{
private string name;
private string address;
// Pass the current object instance to another class:
public decimal Salary
{
get { return SalaryInfo.CalculateSalary(this); }
}
public Employee(string name, string address)
{
// Inside this constructor, the name and address private fields
// are hidden by the paramters...
this.name = name;
this.address = address;
}
}
I would say it depends on personal preference for your own coding and on the team/company coding standards for your code at work. Personally, I try to keep both personal and "professional" coding standards the same--it reduces confusion, etc.
I prefer to use "this" on all class-level functions and variables. By using "this" you can immediately tell if the item is a class member or not. Also,I prefer to use "base" on members belonging to any base classes. It's not necessary, but it helps readability, esp if someone unfamiliar with your code is reading it.
I prefer this syntax. As the classes get larger and the functions get more complex, it is convenient to be able to read a variable name and know whether or not its an instance var without having to reference another part of the code.
Edit: I realize that if one is having trouble keeping track of variables, then it is probably time to refactor. This is fine in the abstract. So then to clarify: in the case where classes and their relationships aren't simple (and surely they exist) or in code where people have not refactored or followed good guidelines for keeping parameter names different from instance vars, I'll say (imho!) that using 'this' isn't a bad idea for clear code.
You're right - it's very much a preference thing. Of course, many companies enforce a set of coding style guidelines that either require this before any instance member, or require that it not appear. (Does anyone know what the Microsoft FxCop rules for the .NET framework are?)
Personally, I prefer to have this appear before any property, method or field that belongs to an instance. It makes it easier for me to distinguish where it belongs:
A member of an instance of the class (prefixed with this)
A static class member (which I prefix with the name of the class)
A local scope variable (no prefix)
It's more important to me to be able to read my code less ambiguously, than it is to save the 5 characters of this.. For instance, I immediately know that I need to dispose() all the local-scope items that were opened in this scope, and I won't confuse them with the instance-members that shouldn't be disposed. Heck, just for extra laziness points, I use this. as a quick way to access the intellisense list of member of the instance members.
In JavaScript, yes! In languages where it's not necessary, no. Some people do it to make the "memberness" visible to someone reading the code - but your IDE should be able to take care of that by highlighting it.
When VS 2010 comes out, my plan for world peace is to write an extension for the WPF code editor that displays this. in front of every reference to a member variable than doesn't already have that prefix. Then those who need that reminder will no longer need to type it, and those who don't like it can simply not install my extension and can freely delete any unnecessary this. prefixes they see.
I never use it. Mostly, it doesn't matter if a variable is a member or not. Keep your methods small enough that it's no problem to remember which variables are locals, and you won't mave so much trouble remembering which are members.
I use "_" as a prefix for member variables, as it is easy to ignore. But this means there will never be a collision with a local or parameter, so this. is not necessary.
My attitude may be "colored" by the fact that I use ReSharper, whose "color identifiers" mode makes it easier for me to see what's what.
I think that you should always include it if you are specifically referring to the class variable.
The reason for this is if you later on add in a local variable of the same name, you will need to rename all the class variables with this. so why not save your future self some time and hassle?

Have trivial properties ever saved your bacon?

There's a lot of advice out there that you shouldn't expose your fields publically, and instead use trivial properties. I see it over & over.
I understand the arguments, but I don't think it's good advice in most cases.
Does anyone have an example of a time when it really mattered? When writing a trivial property made something important possible in the future (or when failing to use one got them in to real trouble)?
EDIT: The DataBinding argument is correct, but not very interesting. It's a bug in the DataBinding code that it won't accept public fields. So, we have to write properties to work around that bug, not because properties are a wise class design choice.
EDIT: To be clear, I'm looking for real-world examples, not theory. A time when it really mattered.
EDIT: The ability to set a breakpoint on the setter seems valuable. Designing my code for the debugger is unfortunate: I'd rather the debugger get smarter, but given the debugger we have, I'll take this ability. Good stuff.
It may be hard to make code work in an uncertain future, but that's no excuse to be lazy. Coding a property over a field is convention and it's pragmatic. Call it defensive programming.
Other people will also complain that there's a speed issue, but the JIT'er is smart enough to make it just about as fast as exposing a public field. Fast enough that I'll never notice.
Some non-trivial things that come to mind
A public field is totally public, you can not impose read-only or write-only semantics
A property can have have different get versus set accessibility (e.g. public get, internal set)
You can not override a field, but you can have virtual properties.
Your class has no control over the public field
Your class can control the property. It can limit setting to allowable range of values, flag that the state was changed, and even lazy-load the value.
Reflection semantics differ. A public field is not a property.
No databinding, as others point out. (It's only a bug to you. - I can understand Why .net framework designers do not support patterns they are not in favour of.)
You can not put a field on an interface, but you can put a property on an interface.
Your property doesn't even need to store data. You can create a facade and dispatch to a contained object.
You only type an extra 13 characters for correctness. That hardly seems like speculative generality. There is a semantic difference, and if nothing else, a property has a different semantic meaning and is far more flexible than a public field.
public string Name { get; set; }
public string name;
I do recall one time when first using .net I coded a few classes as just fields, and then I needed to have them as properties for some reason, and it was a complete waste of time when I could have just done it right the first time.
So what reasons do you have for not following convention? Why do you feel the need to swim upstream? What has it saved you by not doing this?
I've had a trivial property save me a couple of times when debugging. .Net doesn't support the concept of a data break point (read or write). Occasionally when debugging a very complex scenario it was important to track read/writes to a particular property. This is easy with a property but impossible with a field.
If you're not working in a production environment, it's simple to refactor a field -> property for the purpose of debugging. Occasionally though you hit bugs that only reproduce in a production environment that is difficult to patch with a new binary. A property can save you here.
It's a fairly constrained scenario though.
I used to think the same thing, Jay. Why use a property if it's only there to provide direct access to a private member? If you can describe it as an autoproperty, having a property at all rather than a field seemed kind of silly. Even if you ever need to change the implementation, you could always just refactor into a real property later and any dependent code would still work, right?. Well, maybe not.
You see, I've recently seen the light on trivial properties, so maybe now I can help you do the same.
What finally convinced me was the fairly obvious point (in retrospect) that properties in .Net are just syntactic sugar for getter and setter methods, and those methods have a different name from the property itself. Code in the same assembly will still work, because you have to recompile it at the same time anyway. But any code in a different assembly that links to yours will fail if you refactor a field to a property, unless it's recompiled against your new version at the same time. If it's a property from the get-go, everything is still good.
I'll answer your question with another one: have you ever really benefited from not making all your types and members public? I suspect I haven't directly prevented any bugs by doing so. However, I've encapsulated my types properly, only exposing what's meant to be exposed. Properties are similar - good design more than anything else. I think of properties as conceptually different from fields; they're part of the contract rather than being fundamentally part of the implementation. Thinking about them as properties rather than fields helps me to think more clearly about my design, leading to better code.
Oh, and I've benefited occasionally from not breaking source compatibility, being able to set breakpoints, log access etc.
Part of the idea is that those properties may not be trivial in the future - if you bound external code to a field and later wanted to wrap that in a property, all of the dependent code would have to change, and you may not be able to do that, especially in the case where you are a control designer or have libraries that you can't control, etc.
Not to mention there are certain .NET practices that will not allow you to use a field - databinding particularly.
I am sure there are other good reasons as well. Why does it matter to you? Use an automatic property and be done with it. Seems like something not worth being concerned about to me...
It's much easier to debug a problem involving a field if it is wrapped by a property accessor. Placing breakpoints in the accessor can quite quickly help with finding re-entrancy and other issues that otherwise might not be caught. By marshaling all access to the field through an accessor, you can ascertain exactly who is changing what and when.
In .NET, from my understanding, you cannot databind to public fields; but only to properties. Thus, if you want to do databinding, you have no choice.
I once had fields that I wanted to expose from a windows from project which allowed the stats for the program (TotalItems and SuccessfulItems).
Later I decided to display the stats on the form and was able to add a call in the setter that updated the display when the property changed.
Obviously, if you're not creating a shared class library, and you're not using DataBinding, then using a field will cause you no problems whatsoever.
But if you're creating a shared class library, you'd be foolish IMHO to do otherwise than follow the guidelines, for the usual three reasons:
consumers of your shared class library may want to use DataBinding.
consumers of your shared class might want binary compatibility, which is not possible if you switch from a field to a property.
the principal of least surprise implies you should be consistent with other shared class libraries including the .NET Framework itself.
IMHO there is no such thing as a trivial property as people have been calling them. Via the way things such as databinding work, Microsoft has implied that any bit of data that is a part of the public interface of an object should be a property. I don't think they meant it merely to be a convention like it is in some other languages where property syntax is more about convention and convenience.
A more interesting question may be: "When should I use a public field instead of a property", or "When has a public field instead of a public property saved your bacon?"
Fields which are of structure types allow direct access to the members thereof, while properties of such types do not. Consequently, if Thing.Boz were a field of type Point, code which wants to modify its X value could simply say Thing.Boz.X += 5;; if Thing.Boz were a mutable property, it would be necessary to use var tmp = Thing.Boz; tmp.X += 5; Thing.Boz = tmp;. The ability to write things more cleanly with the exposed field is often, but not always, a blessing.
If it will always be possible for Boz to be a field, modifying its members directly will be cleaner, faster, and better than copying it to a temporary variable, modifying that, and copying it back. If the type of Boz exposes its mutable fields directly (as structures should) rather than wrapping them in trivial wrappers, it will also be possible to use things like Interlocked methods on them--something that's simply impossible with properties. There's really only one disadvantage to using fields in that way: if it's ever necessary to replace the field with a property, code which relied upon the thing being a field will break, and may be hard to fix.
In short, I would posit that in cases where one isn't concerned about being able to swap in different versions of code without having to recompile any consumers, the biggest effect of using properties rather than fields is to prevent consumers of the code from writing code which would take advantage of (and rely upon) the semantics of exposed fields which are of structure types.
Incidentally, an alternative to exposing a field of a structure type would be to expose an ActOnXXX method. For example:
delegate void ActionByRef<T1>(ref T1 p1);
delegate void ActionByRef<T1,T2>(ref T1 p1, ref T2 p2);
delegate void ActionByRef<T1,T2,T3>(ref T1 p1, ref T2 p2, ref T3 p3);
// Method within the type that defines property `Boz`
void ActOnBoz<T1>(ActionByRef<Point, T1> proc, ref T1 p1)
{
proc(ref _Boz, ref p1); // _Boz is the private backing field
}
Code which wanted to add some local variable q to Thing.Boz.X could call Thing.ActOnBoz((ref Point pt, ref int x) => {pt.X += x;}, ref q); and have the action performed directly on Thing._Boz, even though the field is not exposed.

Categories