And if I should, when do I add the _s?
2 Answers
2I don’t think you “should” but “may want to” do that. It’s a matter of writing style - totally up to you (project owner/lead) choice.
I myself use this underscore prefix _ to visually and alphabetically distinct private fields from public ones, property accessors and local variables - to make them immediately distinguishable mid busy code blocks.
public int publicProperty { get; set; } = 1;
public int publicField = 1;
public int _privateField = 1;
public int PublicMethod ()
{
int localVariable = 1.
return publicField + publicProperty + _privateField + localVariable + PrivateMethod();
}
int PrivateMethod () => 1;
Many people (myself included) also use the Microsoft coding conventions, which do include the _ prefix for private members. But unlike what Andrew posted, all public members are PascalCase.
Using Andrew’s example that would be:
public int PublicProperty { get; set; } = 1;
public int PublicField = 1;
private int _privateField = 1;
public int PublicMethod(int parameter)
{
int localVariable = 1;
return PublicField + PublicProperty + _privateField + localVariable + PrivateMethod();
}
private int PrivateMethod() => 1;
There are plenty of different styles out there, so find a pre-existing one (for C#/Unity) that you like and be aware that you may have to switch if you join someone else’s project.
AMAZING! THANK YOU VERY MUCH! I think I'll use this then.
– Superturkey77