C#C
C#2y ago
tama

Best practice for class constructors?

Hello there.
I'm creating a class with one private and one public variable. I am a little unsure how the constructor should work when this is the case. As an example:

C#
public class A
{
  private readonly typeX _var1;
  public typeY var2Something { get; set; }
  
  public A(typeX var1, typeY var2) 
  {
    _var1 = var1;
    var2Something = var2;
  }
}

Does it make sense to declare them first, and then assign them in the initializor? Also, are you supposed to add { get; set; } to the class variable when it's also part of the constructor?
I am also unsure what the best practice is for variable names in C#. Some places I have seen names with capital first letter, other times I see something like exampleVariable. I come from Python, where we use _variable_name for private variables, do you also use the underscore in C#?
Was this page helpful?