Const versus Readonly

by Sottje 22. February 2010 21:43

Developers often make use of constants to hold static values to use through the class or even through the application.
Sometimes we use de const and sometimes the static readonly. They seem to do the same but aware of the differences.

Const
The const field is a defined and evaluated at compile time and cannot be changed at runtime.
So therefore a const member can only be of a value type, an enumeration a string literal or null.
The initialization of classes and structures is done at runtime with the new keyword os cannot be used with const.

It behaves like a static member but cannot be decalered like one.

public const string OwnerName = "Sottje";

Readonly
The value of a readonly fields can be initialized at runtime by declaration of using the constructor.
When having multiple constructors, readonly fields have different values.
A readonly member is not static by default. Make it explicit by using the static keyword.

public readonly string OwnerName = "Sottje";

or

public class MyClass 
{ 
     public readonly string OwnerName; 

     public MyClass() 
     { 
          OwnerName = "Sottje"; 
     } 
}

Tags: , ,

Professional | c#

Preserve user settings upon installation

by Sottje 21. February 2010 20:00

When a new version of your application is deployed, you need to make sure that the user settings are preserved.
The best way of doing this is to make use of a boolean setting "IsFirstTime" with a initial value of 'True' which is checked at the startup of your application.

// Check if it is the first time the application starts
if (Settings.Default.IsFirstTime)
{
     // Upgrade the settings from the previous version
     Settings.Default.Upgrade();
  
     // Do other initial suff
  
     // Set the IsFirstTime to this code won't run anymore
     Settings.Default.IsFirstTime = false;
}

An alternative could be using the application version instead of the IsFirstTime. This way you can seperate the first time use ever process from the update application version process.

Tags: , , ,

Professional | c#

About me

Jeroen van Gent is a Professional Web, Windows and Surface developer at Qurius.

Currently coordinating 3rd line international support for an accounting company active in over a 100 countries for a WPF/Groove .NET application used by more than 20.000 users on a daily basis.

Husband and Parent with passion for Reading, Star Wars and Lego!

Follow me on twitter: twitter.com/sottje