C#: Default Values for member variables

5 simple rules to remember for the default values that class member variables get:

  1. Numeric data is set to 0 or 0.0
  2. char types are set to ‘\0’
  3. bool types are set to false
  4. string types are set to null
  5. Reference types are set to null

This is at the class level. When within method scope, you must assign an initial value before using a variable as they don’t receive a default assignment. The only exception is when using a variable as an output parameter (out keyword).

If you’d like to override the default values, you can assign a type’s member variable at the time of declaration:

Be aware that members are assigned before the constructor gets called. That means that if you give a member a default value but then assign it in the constructor, it cancels out the initial assignment.

Leave a Reply

Your email address will not be published. Required fields are marked *