C#: static keyword

Use the static keyword for members of a type that are so common that there isn’t a need to create an instance of the type. A few notes on on static data:

  • Static members can only operate on other static members.
  • Static data is allocated once and shared among all instances of the same type.
  • A non-static method can make use of non-static and static data. Static data is available to all instances of the type.
  • If you assign a static member in a constructor, every time a new instance is created, the static member gets reset.

C#: Read-only fields

The C# keyword readonly is used when you don’t know a value at compile time, but you want that value to never change once it’s been assigned. Read-only fields aren’t static like constants are; if you’d like to make them static you must include the static keyword.

An interesting fact about readonly fields is that their value can be assigned from within a constructor. An example of this is when you need to read a value from the database.

C#: Constants

A few notes about constants in C#:

  1. Once a constant has been assigned a value, you can’t change it’s value or you’ll receive a compile error.
  2. Constants may not be used as return values.
  3. The value assigned to a constant must be known at compile time.
  4. Constant fields are static and thus need to be prefixed with the type name. However if referencing a constant within the current type or member, you don’t need to prefix it with the type name.

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.