Posted by: Cirilo Meggiolaro | 11/13/2008

Tip of the day #30 – Readonly modifier

Today’s tip is all about the readonly modifier.

A value or a reference type object can be declared using the readonly modifier keyword, what makes possible a value to be assigned on either declaring the object or within a constructor.

What about the constants?

The two differences between constants and readonly modifiers are:

1. Constants must be initialized only during the declaration;

2. Only literal values must be used to initialize a constant object while readonly objects may be initialized with either literal values or references to other objects.

How to…

The syntax is pretty straightforward:

// Declare the object and initialize with a literal value
readonly int b = 100;

or

// Declare the object and initialize with other object
readonly int b = a;

or

// Declare the object and initialize it on constructor
readonly int b;

/// <summary>
/// Class constructor
/// </summary>
/// <param name=”b”>Parameter</param>
public MyConstructor(int b)
{
a = b;
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

%d bloggers like this: