C# naming convention for private members [duplicate] - c#

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Naming convention for private fields
I read on msdn about C# naming conventions but they don't talk about naming private fields vs parameters.
public void SetAnimation(int framesX, int framesY)
{
framesX = framesX; // the first one is private class member
framesY = framesY;
}
I must name private field differently than a parameter. I can't do camel case for both.
What do you suggest?

You can have same name. To have it more elegant, you can have:
this.framesX = framesX; // the first one is private class member
this.framesY = framesY;

I generally do:
private int _framesX;
private int _framesY;
That makes it more clear:
public void SetAnimation(int framesX, int framesY)
{
_framesX = framesX;
_framesY = framesY;
}

This really depends on the company you work at. Basically a naming convention is a team rule and for example, Resharper allows you to add a team convention

You can name it the same, but if referring to the private member you have to use
this.framesX;
So for example;
this.framesX = framesX;

I normaly name my private fields (are there others ;) ) with a '_' prefixed. For some people this is a smell others do the same - I guess it's a matter of taste.

I use _framesX for marking private fields.

You could go with the "_" prefix for private members or use "this.framesX" or both "this._framesX".
I'd say it depents on what your team is using.

Your code is fine, you might need to specify this thought.
Well thats how I name my Fields and parameters mostly.
public void SetAnimation(int framesX, int framesY)
{
this.framesX = framesX; // the first one is private class member
this.framesY = framesY;
}

private variables should start with lowercase. so you've got that right.
you can make yr code work by using 'this' keyword to refer back to the instantiated object.
public void SetAnimation(int framesX, int framesY)
{
this.framesX = framesX; // the first one is private class member
this.framesY = framesY;
}

I have a tendency to use only properties starting with a capital, and define the getter and setter public or private
public int FramesX { public get; private set; }
public int FramesY { get; set; }

Related

C#: How to add a class member named "protected"

I'm fairly new to C# but have extensive experience in Objective-C and OOP. I'm using Json.NET to automatically parse API responses to objects. It so happens that one of the objects returned has a property named protected. Obviously this is a problem, because protected is a keyword for class member declaration.
"protected": true
Is it possible to add a member with the name protected at all?
Is it possible to add setters and getters that get triggered, if the parser tries to set the protected property? (but assign the value to a private member named _protected)
Should I modify the parser to behave different when he encounters a property named protected?
Thanks for any advice.
1:
For question #1: You can put an # symbol before it any keyword you want to use as a variable name.
E.g.
public string #protected {get; set; }
I recommend against doing this, however. You should be able to remap the "protected" field in your JSON to a different property in your POCO.
2:
private string _protected;
public string #protected
{
get
{
//any additional code you want
return _protected;
}
set
{
//any additional code you want
_protected = value;
}
}
3:
Up to you!
I implemented this solution:
[JsonProperty("protected")] public bool Protected { get; set; }
Like Daniel Mann suggested in his comment:

Common practice for variables with similar names in constructor parameter and as a property

Is there a "correct" way to name a variable when it is being passed in a constructor to a property? Example (in c#):
public class MyClass
{
private int index;
public MyClass(int i)
{
index = i;
}
}
When the two variables are the "same", is it common to name one more concisely, etc.? I want to be consistent at least, but I'm as to whether there is an accepted way to do this.
public MyClass(int index)
{
this.index = index;
}
This is at least the common way of doing in Java, and I guess it's the same in C#. It makes the name more meaningful than i, and uses the same name as the property to designate the same thing.
Refactor recommends private fields of a class to be camelCase prefixed them with _ (_index in your case). They recommend parameters to be camelCase without the underscore.
As mentioned in comments, there is no MSDN-recommended standard for private fields.
You can use as you wrote
or
below can be another option if the variable names are same
public class MyClass
{
private int index;
public MyClass(int index)
{
this.index = index;
}
}
You can name them the same. Use this to clarify what you're doing.
this.index = index;
If you make a distinction (which I do no recommend) it's better to be most explicit about the parameter name passed to the method instead of your internal name. If other programmers use your class then at least they know what the parameter means. So if you want to distinct:
public MyClass(int index)
{
i = index;
}
I think you should focus on making the "visible" variable more readable (in this case, that's the constructor's parameter). After all, this is what the users of your class will see when typing out.
Yes, there is a correct way to avoid such dilemmas, which is to follow the naming conventions established for your language. For example, in C# it's a convention that private fields begin with an underscore. There's probably something equivalent to Java.
That being said, it's definitely possible to differentiate between fields and local variables by explicitly using this to reference fields (a practice that's appropriate when there's a naming ambiguity).
There are set of coding standards in .NET defined in MSDN.
http://msdn.microsoft.com/en-us/library/ms229002.aspx
but for the total list of guidelines:
http://msdn.microsoft.com/en-us/library/ms229042.aspx
The C# standard would write your code like this:
public class MyClass {
public MyClass(int index) {
Index = index;
}
public int Index {
get { return _index; }
private set { _idex = value; /* Perform other actions triggered by the set */ }
}
private int _index;
}
In cases where no backing field is required the property (and backing field) can and should be simplified to:
public Index { get; private set; }

Is there an equivalent of 'this' in C# for static members?

Is there an equivalent of this in C# for static members?
I like to use this to make my code more readable, but wondered if there was an equivalent for static members.
I suppose if you use this. to reinforce that you are referring to instance members, the equivalent in a static member would be to use ClassName.
But stylistically, why add code that doesn't change meaning?
edit to add various clarifications:
My last sentence above can be illustrated with these examples:
class Example1
{
public int J { get; set; }
public Example1()
{
J = 0;
}
// These two methods have *exactly* the same CIL
public int InstanceMethodLong()
{
return this.J;
}
public int InstanceMethodShort()
{
return J;
}
}
The this. in InstanceMethodLong does not change the meaning as compared with InstanceMethodShort.
Statically:
class Example2
{
public static int K { get; set; }
static Example2()
{
K = 0;
}
// These two methods have *exactly* the same CIL
public int StaticMethodLong()
{
return Example2.K;
}
public int StaticMethodShort()
{
return K;
}
The Example2. in StaticMethodLong does not change the meaning as compared with StaticMethodShort.
In both these cases, adding the qualifier results in the same CIL, the same behaviour, and is more source to write, read, and understand. Stylistically - and I will happily accept that this is a question of code style - I see no reason for it to be there.
With underscore prefixes the situation is slightly different:
class Example3
{
int _j;
public int J
{
get { return _j; }
set
{
_j = value;
// and do something else,
// to justify not using an auto-property
}
}
public Example3()
{
J = 0;
}
public int MethodWithParameter(int j)
{
// Now there is a *difference* between
return j;
// and
return _j;
}
}
Here, in MethodWithParameter, there is a difference between referring to _j and j - so we are deliberately and explicitly expressing different meaning. It's true that the compiler doesn't care what we call our variable names, but it does care what variables we are referring to! So in the body of MethodWithParameter, using or not using an underscore isn't just stylistic, it's semantic. Which isn't the particular issue we're addressing in this question.
As a static member is not meant to belong to any particular instance (as this refers to an instance of an object, with different settings possible per instance), what you would instead want to do is use ClassName.Member instead of this.Member.
public class Orange
{
public static string Tastes = "sweet";
public static string FoodType(){
return "fruit";
}
}
Would be called by:
Console.WriteLine(Orange.Tastes);
Same goes for static methods, as well:
Console.WriteLine(Orange.FoodType()).
Please note this is a contrived example for demonstration only. :)
You may able to use the class name to reference other static properties.
Your code becomes a bit more resistant to copy/paste but that's not always a bad thing.
Unfortunately no, there is no this for static methods. To help differentiate static members from class members I prefix it with the class name.
class Test {
static Regex TextRegex = new Regex(...);
public static bool TestString(string input) {
return Test.TextRegex.IsMatch(input);
}
}
I like "this" as well to realsie from the first look where the state is changing. You may want to consider type's name for static members in this case.

Why can a class not have a static or constant property and an instance property of the same name?

I've never really questioned this before until now. I've got an input model with a number of fields, I wanted to present the string names of the properties through the input model so that my Grid can use them:
public class SomeGridRow
{
public string Code { get;set; }
public string Description { get;set; }
public const string Code = "Code";
}
Obviously, this gives the error:
The type 'SomeGridRow' already
contains a definition for 'Code'
Why can the CLR not cope with two properties of the same name which are, in my eyes, separate?
string code = gridRow.Code; // Actual member from instantiated class
string codeField = SomeGridRow.Code; // Static/Const
I'm now just using a child class called Fields within my inputs now, so I can use SomeGridRow.Fields.Code. It's a bit messy, but it works.
Because you can also access static (or, non-instance in this case) properties in the same way (inside the same class), and it would be a bit confusing, for example:
public class SomeGridRow
{
public string Code { get;set; }
public const string Code = "Code";
public void MyMethod() {
var thing = Code; //what would this reference?
}
}
Because both this:
public class SomeGridRow
{
public string Code { get;set; }
public void MyMethod() {
var thing = Code; //what would this reference?
}
}
And this:
public class SomeGridRow
{
public const string Code = "Code";
public void MyMethod() {
var thing = Code; //what would this reference?
}
}
are valid ways to access properties, static or not. It doesn't answer the "why can't I?" question, but more of the why it's not allowed...it would be far too ambiguous IMO.
It probably could, but the designers of C# wanted to avoid ambiguities that can come from such use (abuse?) of language features.
Such code would end up being confusing and ambiguous to users (did I want the instance or the static method call?, Which one is right?).
In addition to the points already made about ambiguity, i would say that the naming needs to be relooked in such a case.
If two variables / fields having the exact same name in the same context i.e class but different values to me sounds more like a naming issue.
If they are exactly same, you dont need 2 fields.
If they are slightly different, you should have more accurate names.
In some other languages with a similar syntax, one can access a static member through an instance. So you could access both string.Empty and "abc".Empty.
C# doesn't allow this (though it does sort of from inside the class or a derived class, in that you can omit the class name for a static member and can omit this for an instance member), primarily to avoid confusion (I find it more handy than confusion tbh, but that's just me, I like switch fall-through too so what do I know).
Having introduced a stricter rule to allow for less ambiguity, it would be counterproductive to allow a new looser rule on the back of it that allowed for more. Think how many "why must I use this with property X but not property Y?" questions SO would have if it was allowed (we'd have to force this with property X to be clear we meant the instance member).

Basic C# property question

In C# do properties need to reference private member variables, or can I just declare the properties and use them directly in the class code?
If the former is the best practice, then does that rule out using C# property short-hand? I.e.
public string FirstName { get; set; }
Properties, when implemented like this:
public string FirstName { get; set; }
Automatically create a private member variable (the compiler does this for you), so you don't have to worry about it. This will behave exactly the same as if you do:
private string firstName;
public string FirstName {
get { return firstName; }
set { firstName = value; }
}
There is no reason not to use the automatic properties ( { get; set; } ). The provide the same advantages as making your own private member variable.
In addition, if you later decide you need to do extra processing (for example, if you decide to implement INotifyPropertyChanged in your property setter), you can add this without changing your public API, but putting a backing field in manually.
You don't need properties to access private fields but in general it is considered best practice.
And you can use auto-properties (short hand) untill you need to add more functionality to a property, like validation. Changing it to a 'real' property is always a non-breaking change.
Properties created like this
public String Caption{ get; set; }
this will be compiled as
[CompilerGenerated]
private string <Caption>k__BackingField;
public string Caption
{
[CompilerGenerated]
get
{
return this.<Caption>k__BackingField;
}
[CompilerGenerated]
set
{
this.<Caption>k__BackingField = value;
}
}
The above code is extracted after compilation using reflector tool.
They do not need to reference private member variables. You can use them directly in the class.
Properties do not need to reference private member variables. It is best practice, though, to have them do so. You can think of properties as methods if it makes it easier to understand. You can run code inside of them. You can return whatever you want. You can call methods and use private member variables. You can even simply return a constant.
I use private member variables in almost all cases. It allows me to create a readonly property, or to provide some rules to those outside my class of getting or setting properties that my class doesn't have to follow.
To add on to Reed's answer, inside of your code (within the class itself) the member functions should adhere to this and actually use the Property rather then the actual private member. For instance if you had this:
public string FirstName { get; set; }
And you had a strange method called public char GetFirstLetter() that returned the first letter in a person's first name you'd want to do it like this:
public char GetFirstLetter()
{
return FirstName[0];
}
Instead of actually using your private variable. When you set a property a programmer may have written code to set it in a particular manner. So it only makes sense to simply use that property within your class methods.
C# can reference private variables as in:
public class A
{
private string _b;
public string B
{
get { return _b; }
set { _b = value; }
}
}
The get;set; designation is automatic properties which when compiled will generate the private variable for you, as a way to make it easy to setup your code.
Using properties is the best way to provide a method of control and security to the attributes in a class, always keep the attributes private if possible.
if you use like
public string FirstName { get; set; }
compiler will automatically adds getters and setters for this property automatically.it not a bad practice.
Here is the proof
if you declare
private string firstName;
public string FirstName
{
get { return firstName; }
set { firstName = value; }
}
like this also compiler will takes it as
so its not ruled out... :)

Categories