Windows Phone Developers

Tuesday, November 25, 2008

Readonly Fields in C# / Readonly Properties in C#

Read-only fields can be declared with a readonly modifier.

class Company

{

public static readonly string CompanyName = "VBADUD Inc";

}

Assignment to a readonly field can only occur as part of the field’s declaration or in a constructor in the same class.

class Company

{

// Assignment of Readonly value in Field declaration

public static readonly string CompanyName = "VBADUD Inc";

// Assignment of Readonly value in a static constructor

static Company()

{

CompanyName = "My Name";

}

}

Assigning the value to a readonly field outside the class will throw the following error:

Company.CompanyName = "My Company";

A static readonly field cannot be assigned to (except in a static constructor or a variable initializer)


Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon

No comments:

Post a Comment