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 there is a debate/opinion about using this keyword or underscore in regards to private fields/properties (and I'll mention, I'm stuck on .NET 2.0)
Personally, I prefer this, but there are times you can't use it, for example when you need to reference a global variable from within a static method. Well, then we are forced to use the underscore (assuming we only have 2 choices, this or underscore). This means if my class uses any static methods I can't use this throughout the document.
Now, I've read the naming guidelines and used StyleCop, both would rather I don't use the underscore, but my Resharper pretty much insists on using _.
I don't feel it is right to have one class use the _ and the next class use this simply to accommodate for when the classes mixes non-static and static methods! The advice here on SO is to keep to one implementation/style but I don't know if that means I should ignore Microsoft (and I know MS don't always follow their own rules)!
It has been suggested to prefix with something else, similarish to Hungarian but prefix with globVariableName where glob indicates global. I hate this idea, it's too bespoke and won't be obvious to any other developer outside my team.
So, my question is, what is the best way to define global variables consistently? Since they are naming guides, may be I can just ignore (at least _ can be used consistently but it feels wrong to ignore the advice from the language creators).
Just use the class name in the same way you'd use "this", in a static class. Example follows:
public static class MyStatic
{
public static object Global;
public static void SomeMethod()
{
var theGlobal = MyStatic.Global;
}
}
public class MyNonStatic
{
public object Global;
public void SomeMethod()
{
var theGlobal = this.Global;
}
}
Note: I can't actually think of any other way to do it.
By global variables, I assume you mean const or static fields
I thing StyleCop used to encourage you to use ClassName.staticField for static and const fields, but it seems to have dropped that rule, at least by default. That is still a nice way to do it though.
Also, you can configure Resharper to play nicely with StyleCop.
I always use underscore for both static and instance variables.
For instance variables i use this.variable
For static variables i , sometimes, prefix them with the name of class, e.g., ClassName.variable
this is just my personal opinion;
I believe using this for every private variable is very useful; it has a positive effect on readability of the code. Also, when you are employing some DI constructor injection method, it enables you to use same variable without any confusion, which seems very proper.
public void SomeMethod(int someVariable)
{
this.someVariable = someVariable;
}
I prefer this instead of underscore; underscore seems pretty at first glance; but refering to the previous examples it has negative effect on readability.
I name static variables with the same way I name class variables; usage of this keyword lowers the risk of confusion between private and static variables.
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
Is there a standard or accepted code style for whether public or private members / functions come first in a class?
I expected to find a lot on Google regarding this but have found nothing.
Take a look at this SO question. It has the StyleCop Rules Documentation's requirements.
Fairly well used standard.
ASIDE: There is a free plugin for C#. Makes following the rules much simpler when you know what you are doing wrong. It will tell you if you violate the rules and can be set to run during the build step.
There are ordering rules with StyleCop which are useful to follow as a point of standardisation.
No this is simply a matter of personal preferences. Just follow your company one if that applies.
As people are saying, the order generally doesn't matter. However, there is one important exception, and that's initializing static fields. You can initialize static fields based on the value of other static fields - it all ends up getting compiled into the static constructor, but in the order that it's written in the code.
For example:
class Program {
private static int j = 4;
private static int i = Program.j;
static void Main(string[] args) {
Console.WriteLine(Program.i); // 4
}
}
But:
class Program {
private static int i = Program.j;
private static int j = 4;
static void Main(string[] args) {
Console.WriteLine(Program.i); // 0
}
}
So keep this case in mind if you decide to re-shuffle your members around. To be totally safe, you can put the initializations in the static constructor, like:
class Program {
private static int i;
private static int j;
static Program() {
Program.j = 4;
Program.i = Program.j;
}
}
There are rules enforced by StyleCop that I have seen many people use as a standard.
Frankly, they make sense1, but I don't think it's the best way.
I think things should be grouped by functionality, not by type, or accessibility, or static, etc. I would argue that a scheme that is organized by functionality requires the least amount of navigation when trying to read or maintain a code base. Any other ordering scheme (or *rules) would leave you navigating all over the class as you try to work with it. A conceptual ordering that places things together that make sense will minimize that jumping around. It's about making it easier to understand and work with it. It's a practical perspective, rather than forming rules for the sake of having rules that can be enforced.
1: They make sense in that they are a rule, they appeal to the OCD among us, and they can be enforced by a machine, but who cares if the machine can enforce them? But code is not for the machine, it is for the humans. When I need to understand the code, I don't think to myself "if only I could first understand all the constant fields, and then all the fields, etc." I take a very different approach. I want to see the big picture first, and one thing that is going to assist with that is seeing the code organized by functionality.
Here is the Microsoft C# Coding Conventions (C# Programming Guide)
It makes no mention of ordering for public, protected or private functions or members in a class.
I know in my past experience that FxCop had "suggested" that I put my public functions before my private functions, but again not necessarily a standard.
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 have been writing C# code for 10 years, but I am woefully weak on knowing exactly when to use an interface vs. using a Func or Action. It seems to me that in many places where a method on an interface is called, a Func or Action would work just as well. So, I guess my question is this. If I have an interface with just a single method, or perhaps a couple methods, is there any disadvantage to using a Func or Action instead? Using a Func or Action seems cleaner to me.
Thanks very much.
I guess you can compare an Action or Func with an interface containing one method, with the difference that you can supply any Action or Func that meets the parameter / return value requirements, where when using interfaces, the supplied object must implement that interface.
Perhaps you could call Action and Func "anonymous single method interfaces".
If you look at the design perspective though, your class model would be a drawing of blocks without any lines between them.
You should use delegates and lambda expressions if the implementations are expected to be very short (one or two lines), and especially if the implementations are expected to need local variables (closures).
I have to admit, I was a bit confused by this question. Like #deepee, I agree that a code example would have been good here to show why you think you would use one approach over the other.
The reason for my confusion is that I wouldn't have thought to ask this question since they serve different purposes. Interfaces are used mainly for polymorphism; so that one can treat different implementations all in the same way.
Jon Skeet has a good example of using Func and Action.
Interfaces allow you to do this:
IAnimal animal = AnimalFactory.GetAnimal();
animal.Run();
Using the above code, you don't know or care what kind of animal it is. You just know it can run and you want it to run. More importantly, the caller doesn't know how the animal runs. That's the difference between an Action and interfaces/polymorphism. The logic for doing something is in the concrete class.
An Action will allow you to do the same thing for each instance, when the actual logic is known by the caller, instead of having each concrete instance do something:
animals.ForEach(x => x.Run());
Or:
animals.ForEach(x => /* do something completely different here */);
The above line of code is action that only the caller decides what should happen, instead of delegating the logic to the actual instance by simply calling a method on it.
They solve different problems, so I'm curious to see how folks think they're interchangeable in certain situations.
You would use an Interface when you don't really care what kind of object you're working with...
Let's go with the textbook example
public class Animal;
public class Dog : Animal, IRunningAnimal { }
public class Cheetah : Animal, IRunningAnimal { }
public class Fish : Animal, ISwimmingAnimal { }
public class Gator : Animal, ISwimmingAnimal, IRunningAnimal { }
public interface IRunningAnimal
{
public void Run();
}
public interface ISwimmingAnimal
{
public void Swim();
}
public abstract class Animal
{
/// ...
public abstract void Move();
}
then somewhere in code...
RunningAnimal runner = getAnimal();
//make him run
runner.Run();
each running animal might run in a different way but they all can run.
or better
if(getAnimal() instanceof RunningAnimal) getAnimal().Run();
else getAnimal().Move();
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 is the general consensus towards a separate class in the business layer to store the definition of enums? Is this bad practice? Does this conform to good n-tier design? At the moment my enum definitions are dotted around different, what I would deem as, relevant classes - but I feel as though they should be in one place. Is this, in fact, a subjective question and relative to how I've structured the rest of the solution?
I don't really understand why you would place an enum in a class - perhaps you meant file?
Personally I have a separate file for each enum with the name of the enum.
I place this file close to where the enum is being used and namespace it accordingly.
If an enum is to be shared across assemblies/namespaces, I will use the lowest shared namespace, so it is visible to the using namespaces.
Having enums close to where they are used will make separating code out into projects that little bit easier (if needed).
I don't see the point in having them all in one file - navigation wise, Visual Studio has more than enough navigation capabilities that this is not needed.
Keeping enums in separate class
In this case you're tossing unrelated definitions into one class, for almost no benefits.
Defining enum as nested type for class it relates to
When you hold enums within a class, you may run into naming troubles:
class Foo
{
public enum SomeType { /* ... */ }
public SomeType SomeType { get; set; }
}
This would give an error that SomeType is already defined.
It probably just boils to personal taste, but most often I put my enums along with the class that they are related to, without nesting them:
public enum SomeType { }
public class Foo { }
I was tempted many times to have them nested (we're talking about public enums of course), but the naming issues weren't worth it, for example:
class Foo
{
public enum Enumeration { }
}
Then I can use such enum outside of Foo class, as: Foo.Enumeration, but following declaration (in same namespace):
enum FooEnumeration { }
class Foo { }
gives similar result as you just don't have to type '.' when you are referencing enum: FooEnumeration. Moreover, the latter allows you for this:
class Foo
{
public FooEnumeration Enumeration { get; set; }
}
which would cause aforementioned naming conflicts in previous case.
Summary
When using IDE with powerful GoTo capabilities, it seems to me that naming issues are far more important than 'physical' localization of the enum definition.
I would prefer having separate classes for all constants and Enums in my projects.It improves readability of the code. You should do it especially if you have a Comman proj you are referencing in your business layer and other layers. But if you'd be adding unnecessary references just for the sake of a Constant/Enum class then having them inside the same project makes more sense.
public class Enumerations
{
public enum Gender{
Male = 0,
Female = 1,
Unknown = 2
}
}
And when you consume you could do it like
GetPerson(Enumeration.Gender gender)
{
}
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.
Is there any convention for naming session variables in ASP.NET?
Options that come to my mind:
Session["myValue"] = "value";
Session["MyValue"] = "value";
Session["my_value"] = "value";
Session["MY_VALUE"] = "value";
There aren't any formal naming conventions but you could consider using an enum so that you don't have any string literals which 1) makes it easier to remember the names of your keys and 2) makes it impossible to have a runtime error because you can't have a typo in your key name.
e.g.
public enum SessionKey
{
FirstName,
LastName,
BusinessId
}
then do:
Session[SessionKeys.FirstName.ToString()] = "Rob";
or create yourself a SessionHelper class that that makes the whole process a lot tidier:
public static class SessionHelper
{
public static void SetSessionKey(SessionKey sessionKey, object value)
{
HttpContext.Current.Session.Add(sessionKey.ToString(), value.ToString());
}
public static String GetSessionKey(SessionKey sessionKey)
{
return HttpContext.Current.Session[sessionKey.ToString()] as string;
}
}
}
IMO, it is important to apply the DRY principle:
public class SessionVariables
{
public const string MyStoredSessionVariable = "MyStoredSessionVariable";
...
}
and then:
Session[SessionVariables.MyStoredSessionVariable] = ...
I don't think it matters much which string literal you use, as long as it is unique enough and you do it in a consistent way, like others have mentioned.
There is nothing like a convention. Its a convention which is shared by developers or framed by the project team so that it becomes easy for everyone.
Like you have mentioned, my organisation uses upper case with underscores.
Usually these conventions are decided by the team to keep consistency through out the code, but if suppose you are extending or customizing existing code then its better to follow that existing written code is being following.
Another thing is that, if you want to decide which convention to follow, so usually for Constants capital naming convention is followed, and else Camel notation is followed for better readability.
CamelCase is a good option.
Session["MyValue"] = "value";
CamelCase reference:
http://en.wikipedia.org/wiki/CamelCase
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
There are a few questions on this, but they all seemed to be targeting a specific part of the language;
What are the most common naming conventions in C#? - Asking specifically about getters/setters.
C# naming conventions for acronyms - Asking more specifically about short uppercase suffixes.
I'm just starting out in C# with a friend on a venture to create games for XBOX Live Arcade. I've developed a number of games using ActionScript 2 and 3 but want to start exploring more powerful languages and devices.
I want to ensure that I don't peeve people that I start working with (if I get to that) or even just people on here when I run into trouble and ask a question with seriously disturbing / "incorrect" naming of methods, etc.
I've found it confusing in the example code that I've seen because there seems to be from my current point of view some flaws. I doubt that a flawed naming convention would be used, so I realize that I'm just having trouble understanding.
As far as I can tell so far, there are these conventions:
public Type SomeMethod()
private Type SomeMethod() - no underscore or anything?
public static Type SomeMethod()
private static Type _SomeMethod() - this one just seems odd..
public Type someProperty - switching it up to camel casing for properties?
public static Type SomeProperty - and then going back to pascal casing for static..
In ActionScript 3, I have developed and strictly stick to these conventions:
private var _someVar
public var someVar
private function _someMethod()
public function someMethod()
public static var SomeStaticVar
public static function SomeStaticMethod()
public const SOME_CONSTANT
Is there a complete list of naming conventions with reasoning behind each so that I can get my head around them? The reversal of syntax (i.e. public Type method() instead of AS3's public function method():Type) is throwing me out enough at the moment that I know I need to keep an eye on how I'm naming things, otherwise I'll forget and develop bad habits, which I'd rather nail and avoid now.
The two main Capitalizations are called camelCase and PascalCase.
The basic rules (with lots of variations) are
Types use PascalCase
properties and methods always use PascalCase
public members (fields, consts) use PascalCase
local variables use camelCase
parameters use camelCase
And although the documentation states that "Internal and private fields are not covered by guidelines" there are some clear conventions:
private fields use camelCase
private fields that back a property prefix a _
There is the All-In-One Code Framework Coding Standards from Microsoft which contains a complete set of rules and guidelines. (also used to be available here)
This document describes the coding style guideline for native C++ and .NET (C# and VB.NET) programming used by the Microsoft All-In-One Code Framework project team.
There are a whole lot of naming conventions advocated by Microsoft for .Net programming. You can read about these here.
As a rule of thumb, use PascalCase for public property, method and type name.
For parameters and local variables, use camelCase.
For private fields, choose one: some use camelCase, other prefix _camelCase with an _.
A commonly seen convention is also to name constants with ALLCAPS.
C# prefers PascalCasing for classes, properties, and methods.
As far as I can tell so far, there are these conventions:
public Type SomeMethod() <-- yes
private Type SomeMethod() <-- correct, no underscore
public static Type SomeMethod() <-- correct
private static Type _SomeMethod() <-- this seems odd to me too. underscore should not be there
public Type someProperty <-- no, a public property should be PascalCased (SomeProperty)
public static Type SomeProperty - and then going back to pascal casing for static..
If you are using Visual Studio, or XNA Game Studio (which I think is a fork of Visual Studio), I highly recommend springing for a ReSharper license (from jetbrains software). They will tell you, in your code editor, how to conform to common C# conventions.
Addition:
You should use camelCasing for private fields and method arguments. For private fields, I usually prepend them _withAnUnderscore.