Underscores for private local variables? [closed] - c#

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 13 years ago.
It seems to be the case with the BCL to use underscores for private local variables. I never use them, but get away like this:
int count = 0;
this.Count++;
public int Count
...
public ClassName ( int count )
{
this.Count = count;
}
What are your thoughts on this? Are they are problems with my approach?

This is basically something you'll have to decide upon yourself, just find or make a style guide and follow it.
Personally, I use _ as a prefix for private fields of the class.

The simple rule we use here is: Private implementation details of a class, including variable names, are completely up to the developer who makes it. Public/protected method names, properties, class names, and so on, are subject to best practice guidelines. Internal types can even be considered to be part of this, since they are not publically visible.
When someone else needs to use your library, it will never have to work with internal or private types, will not see if you used underscores, etc. In other words, this is really up to you....
Just keep in mind that if someone else has to maintain your code later that it should not be too obfuscated...

It's not required to use the underscore to denote private variables. It's all personal preference. I use them only so I know I'm using the local variable rather than having Intellisense accidentally use my public Property instead.

IMO, you should never name a private member variable the same as the name of a property, method, or anything else, for that matter. It should be clear which named item you are working with. This will make your code easier to understand and maintain, and will reduce programming errors by yourself, or other developers who need to maintain your code.
Also, if you ever wanted to port the code to VB, that particular naming would not work. Not sure why you would want to switch to VB, but it happens.

I use underscores. It helps me keep variable scope in check and reduce the possibility naming collisions.

Underscores make more sense for languages that are not case sensitive (like VB.Net). In languages like C#, it comes down purely to personal preference.
If you have an aversion to putting this. in the front of some ambiguous assignments, then underscores are for you. Without them, you can occasionally accidentally do things like this:
private int that;
public void AssignThat(int that)
{
that = that; // assigns to method scope variable, not instance scope
}
FXCop or R# should catch this for you, and I believe you get a compiler warning, but it is possible.

There is a practical reason to use a prefix, IntelliSense. ATM it is braindamaged in the way that it does not really distinguish between current instance variables and inherited properties/variables. So using '_' for private variables makes it easier to locate variable within intellisense list and function/variable list in VS code editor. So in a way it is wider-scope hungarian notation.

Related

Why generated code in C# uses underscore? [closed]

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 10 years ago.
I know this might be a stupid question, but here it goes.
I always wrote my private members like privateMember and I've been reading a lot about naming conventions in C# because I noticed that a lot of the automatic generated code in visual studio use _variableName for private members. Everywhere I read, even in Microsoft documents, that you should use privateMember.
So, my question is, if the good practices says that I should write privateMember, as I do now, Why the heck Visual Studio generates classes with private members using underscore (_privateMember)?
Microsoft Code Conventions actually recommend against using underscores altogether. It is really personal preference. I would not use generated code as inspiration for my coding convention standard.
Do not use underscores, hyphens, or any other nonalphanumeric characters.
Maybe it's because it's generated code and not intended to be read by humans. ;-)
Not so long time ago when C# was raising to the market there was a concept that local variables should be leaded by a prefix _. This concept was not accepted by the community as in pure C the _ leads system variable/functions and the metadata are lead by __. So after few years, they now discourage to use that. But still you will find some believer that use this notation not because it is a fanatic but a lot of old C# applications contain this convention.
Why this is in VisualStudio ?
This might be related to the time gap it was designed. In those time this approach was suggested by language designers. So it is probably that no one changed that in the configuration for latest version.
Naming conventions aren't 100% agreed upon. This is one of those that some people like, some people are indifferent to, and some people hate. Certain people consider it better for instance variables to stand out, via their name, and this is one way to do that. Other people use this.instanceVariable rather than instanceVariable all of the time so that instance variables stand out, other people prepend something other than a '_' character, and some people just don't go out of their way to use any special distinction.
At the end of the day what's important is that you, and the other members of your team agree on a standard and are consistent with it. What the rest of the world chooses to do doesn't need to affect you.
It's also worth mentioning that the code snippets generated by Visual Studio, in most cases, can be configured to be in line with your team's coding practices.
It's just a convention they use, I do it too. You can ultimately name your private fields whatever you want. Prefixing it with an underscore just makes it easier to read IMO.
As a convention private fields were/is used as with underscore e.g. string _name;
The link will give you more info on guidelines for naming coventions by MS http://msdn.microsoft.com/en-us/library/ms229045.aspx
It's just the C# language convention so that in constructor you can use _varable instead of this.variable, when the constructor and field name is the same.
there are all c# naming conventions in
http://msdn.microsoft.com/en-us/library/ms229002.aspx
It's a mather of you if you follow the convention of the generated code.
Besisdes the recomendations many programmers use the same convention as the generated code.
Some programs that help you refactor the code also sugests you to follow that name convention for field names.
The underscore at the beginning is VS's way of showing that it is a privateMember. We keep the underscore at the beginning as a rule, but it is really a personal preference as to what naming convention you use. Just pick one and stick with it so you don't confuse yourself or anyone else that might look at your code.

Would you make this method Static or not? [closed]

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 10 years ago.
During a code review I presented a method quickly to the team that I had made static and one person agreed that there was no reason for it to not be static and a person disagreed saying that he would not make it static because it wasn't necessary and just to be on the safe side for future modifications and testing.
So I did quite a bit of research and obviously it's a specialized case but I would like to know what you would do in this situation and why?
(Its basically a helper method I call from a few different methods, a very low traffic page. More for my knowledge and learning on Static.)
private IEnumerable<Category> GetCategoryByID(int id, Context context)
{
var categoryQuery = from selectAllProc in context.SelectAll_sp()
where selectAllProc.CategoryID == id
select selectAllProc;
return categoryQuery;
}
Making private methods static is a form of micro-optimization; the method call is slightly faster. But the difference is almost too small to be meaningful.
Generally speaking, you should mark a method static when it:
Doesn't interact in any way with instance members, and
You would like to have the ability to call it without instantiating the class, as in Class.Method()
Ordinarily, methods like your example would go into their own static helper class, if they are used in more than one place.
If I were you I would ask my self the following questions.
Is it something which is related to type or instance of type?
If the answer is yes, I would be slightly inclined to make it static else, make it non static.
If you can give us some more information, the community can come up with some good options.
The first remark that comes to my mind is that by declaring this method static and possibly using it in multiple places in your code you are introducing a Service-locator kind of dependency.
As far as I know the main problem with it is that implicit dependencies are introduced, i.e. they can't be inferred by looking at method signatures.
As a consequence it can be much harder to assess the impact of a modification of your static method on the rest of your system.

Foo() vs this.Foo() [closed]

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.
I have a co-worker who uses a C# refactoring tool. The tool for some reason perfers:
this.Foo()
over
Foo()
Now we've asked him to turn it off simply because it's annoying to have all the code re-written automatically, but that's not the point.
Am I missing something, or is this just wrong? Why on earth would I want this.Foo()?
As other answers here point out, this is largely a matter of style.
Many times a call to Foo() would be unambiguous without the this., but there are times where it might add clarity. For example:
EventHandler foo = GetEventHandlerFoo();
EventHandler baz = GetEventHandlerBar();
foo();
this.Bar();
baz();
In this case, the this. prefix helps to make the method invocation stand out from the delegate invocations.
Is this necessary? No, and Lasse V. Karlsen correctly points out that the this. is just a surrogate for a naming convention that makes it unambiguous.
But I find that I will frequently use the this.Foo prefix on local properties for a similar reason, where again it is more a matter of style.
If you want to use it, use it.
If you don't want to use it, don't use it.
There's no right answer here.
If for some reason you have a naming convention where the name alone isn't enough to determine whether you're looking at a local variable, a method parameter, an instance field, a property, or a method, you should fix the naming convention, instead of prefixing local fields with this. to distinguish them from local variables.
I think this comes down to a question of syntax vs. semantics. The argument for this.Foo() is it very explicitly denotes exactly what Foo() is and where it came from. There's no wondering if it was an argument passed in to a method, or a static class declared who-knows-where. It's a method on the current object, period. Anything less and you're giving up clear semantics in favor of tighter syntax.
The obvious argument against it: Mouse-over and ctrl+click.
It's a style thing. Sometimes people think it makes the code more clear -- apparently some people find it helpful to be explicit about the target of a method invocation. Personally, I find the spurious use of this to be distracting.
This example demonstrates how the this keyword can be used to explicitly describe a variable's scope:
class Item
{
int id;
public Item (int id)
{
this.id = id;
}
}
I always use this. since it explicitly shows where the thing is. I don't even use a refactoring tool to do it. I type it by hand.

Why VS uses "this" so often? [duplicate]

This question already has answers here:
When do you use the "this" keyword? [closed]
(31 answers)
Closed 9 years ago.
I know what "this" keyword serves for but do not udnerstand why VS uses it nearly always, like this.Invalidate. If the call is placed within the class and there is no problem with identifier, what is it good for?
It is not VS who uses it but the developers who do. If you use a tool like Resharper, it always points out where "this" is unnecessary or redundant.
I think it's mainly a question of style. Using the this reference makes it 100% clear what you intend to reference.
You say there is no problem with the identifier (in that there is no clash of names in scope), but that doesn't mean there won't be in the future.
Additional names or classes could be added to an outer scope. It's unlikely and probably wouldn't cause a problem anyway, but it helps to remove any possibility of ambiguity.
It explicitly shows that this variable or method belongs to this class. It more readable. Its not mandatory though. Its up to the developer and the team to decide whether they want to use it this way or not. It's just another code style.
If the call is placed within the class and there is no problem with identifier, what is it good for?
I assume your talking about autogenerated code, from e.g. the forms designer. It could
a) be written to analyse the code it's already emitted, decide whether the identifier is ambiguous, and then based on that, decide whether to use this. to properly qualify the name, or,
b) just use this. for all class-scoped identifiers.
It may seem redundant in many cases, but the exact same IL code will be produced whether or not you use this. in an unambiguous context, so it's not as if it's causing any harm to always include it.
Adding this, in unnecessary cases, reduces your code's complexity and makes it more readable.
Hahaha, because if you use "this." then Intellisense pops up and you have all your class members at your disposal and don't have to type so much (or make so many typos, whatever...)

Best practice for getting app name/id [closed]

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 10 years ago.
What's the best way for a common library to know what context - a.k.a. the calling app - it is in? I'm in a very controlled enterprise environment... is there a better way for the library to know what application it is getting called from than reading a setting in the config file? What do you use for this type of thing?
//the rest of the story
I work on the Intranet team for a Fortune 500 manufacturing company. I have created a common library that all of our new .Net applications will make use of. It queries a common database for information about the application and a bunch of other things that are irrelevant to the question. As you can imagine, the common library needs to know what application is calling it. I could just force every application to set a property on some static class or something, but instead I wanted to make it a little more behind the scenes. Currently it requires the developer to put a setting in the app.config or web.config with a key of ApplicationName and a value of - you guessed it - the application name (which is a unique non changing id for us). It then uses Currently it uses ConfigurationManager.AppSettings["ApplicationName"] to pull this in.
There may be a way to do it. I will most likely get down votes for this since I don't plan to answer your actual question at all, but I just couldn't move on without saying something. To me this is an example of the worst sort of coupling possible. Your actually has to look at a DB and behave differently depending on the application that is calling it?
You could also just call Assembly.GetEntryAssembly within the common library class.
Then use the .Name property from the returned assembly.
That means those, that your appsettings table (or whatever it is) needs to be keyed by the assembly name, and that if assembly name should change it'd all break. It means you're slightly less flexible on your naming/key choices here.
getenv() will get you environment variables, which in turn should should give you what you want. But generally, having different behavior depending on the name of the calling program is not considered a best practice. An exception would be if you wanted to print out the calling program's name in a log message. There are of course other exceptions, and your situation may be one of them.
You can also probably get the information via the process id (w/ getpid()).
I'm agreeing with EBGreen here. This is a red flag question to me.
That said, I suggest to do exactly the opposite of what you're suggesting, and simply pass the key (application name or whatever) as a parameter to the function you're calling. You could bake it into the program as public static property on whatever you're entry point is, and make a little helper function that basically overloads the call to the repository. That would hide it and reduce error prone repetition..
Better yet, you could also make your entry point classes implement an interface that has a method to get the application name (it just returns a string constant) and methods for setting the values returned from the database.. Call it "IIntranetApp" or something. Then you just pass "this" to a function expecting "IIntranetApp", and it magically fills in the blanks needed from your central repo.
Something like:
public interface IIntranetApp
{
string GetApplicationName();
void SetConnectionString(string connectionString);
// etc... add methods as necessary
}

Categories