Reputation:
I'm creating a Windows Forms based application in C#. My form's constructor takes parameter string title
, and it then saves that value to string this.Title
attribute, and finally I create a windows label Label this.Title
.
The problem is obvious: My Label
and string
have the same name, and I'm curious about naming conventions in C#. What should I do?
Here's the full code:
// BNForm.cs
public partial class BNForm : Form
{
public string Title;
public BNForm(string title)
{
this.Title = title;
InitControls();
}
}
// BNForm.Designer.cs
partial class BNForm
{
private Label Title;
private InitControls()
{
this.Title = new Label();
this.Title.Text = this.Title; // Trying to access the string here
this.Title.AutoSize = true;
this.Title.Location = new Point(15, 15);
this.Controls.Add(this.Title); // Trying to access the Label here
}
}
I first called my label variable label_Title
, but later I have to add a new variable: Button[] Buttons
which should then be called buttonArray_Buttons
, which sounds stupid to me.
What should I name my variables? Is there even a rule for this kind of naming?
Upvotes: 2
Views: 1913
Reputation:
Well now that I know much more of C#
(and "Antonijn" mentioned it already in the comments) I am aware that private
member variables should begin with small letter and public
properties start with a capital letter.
This in mind, my public string Title;
stays as it is, but the label turns into private Label title;
which lets me separate these two from each other. Thanks everyone for the answers, even when none of them helped me with this exact problem (good suggestions, I just don't like lblTitle
etc.), they gave me much more knowledge of C#.
Upvotes: 0
Reputation: 2002
Here are several dos and donts in variable naming as well as other prefix guidelines for different controls.
DOs
DON'Ts
Variable naming suggestions. Just prefix all variables depending on the object type:
Hope this helps.
Upvotes: 0
Reputation: 120400
Don't use prefixes because they're considered bad practice. Just use common sense. How about calling your label field titleLabel
instead? "Does what it says on the tin"... i.e. it's unambiguous.
Upvotes: 3
Reputation: 20320
Well first I'd stay well clear of variable names that only differ by case, generally that's a huge comprehensibility issue. I tend to prefix my arguments in a method with arg, some people don't like that though.
LblTitle or some equivalent hungarian notation is a fairly standard approach. I try to avoid that though. What if you want to diplay the title in say a textbox for instance, rename everything or enable confusion mode.
In this case I'd rename the Title Property to DisplayTitle or the the label to TitleDisplay.
The other option is to create a struct or class to hold the title Property then you can do
[this.]Title.Text = [this.]Setup.Title;
Whatever you do pick one standard and stick to it, is about the only rule.
Upvotes: 1