[edit] C# const and readonly Members
Variables that must not be modified must use the const or readonly keywords. readonly variables need not to be initialized when declared. It is optional for readonly members to be initialized when they are declared and readonly members can be initialized only once in a class. Therefore, the constructor is a good place to initialze a readonly variable. The const variable must be initialized when it is declared. So it's a syntax error for a const members value to change. It is assumed that a const member is static. So, a const member has class wide scope.
[edit] C# Const Members
- Must be initialized when declared
- Cannot be on the left side of an expression
- Assumed to be a static member
- Cannot be modified once initialized
- Can be assigned a value only once
public const int one = 1;
[edit] C# readonly Members
- Does not need to be initialized when declared
- If not initialized when declared it must be declared in the class constructor
- Cannot be modified once initialed
- Can be initialized at compile time
public readonly int number;
public readonly int OtherNumber = 92;
[edit] C# Example
This C# example will simply take a number from the user and add one to it. It will print the results to the screen
using System;
class Program
{
public class MyClass
{
public const int one = 1;
public readonly int result;
public MyClass(int x)
{
//one plus a number
result = one + x;
}
}
static void Main(string[] args)
{
Console.WriteLine("Enter an integer: ");
//get a number from user
int number = Convert.ToInt32(Console.ReadLine());
//pass the number to the constructor
MyClass a = new MyClass(number);
Console.WriteLine("");
Console.WriteLine("Result is: " + a.result);
Console.Read();
}
}
As you can see the class constructor will add 1 to the variable result. The user must [enter] any number then the program will simply add one to it. The result variable is public so a class property is unnecessary. Therefore, we can access the result variable directly from the object.
|