“Read-only members are values which are set at compile time or at runtime by using constructor, but cannot be modified later”
Read-only members are initialized in either at
declaration or at constructor. Readonly member can be instance member or
static member.
Syntax:
public const [data type] [
|
public const [data type] [
public Class_name() //
{
[field name] =
}
|
In the below example we will see
- How to initialize readonly member at the time declaration
- Assigning value to readonly member from the instance, parameterized constructor.
- How to initialize static readonly member at the time declaration
- Assigning value to static readonly member from the static constructor.
- What happens if we try to reassign readonly value other than variable initialization and constructor
Example:
class ReadOnlyMember
{
public readonly double
public readonly double
public readonly int
public static readonly
public static readonly
public ReadOnlyMember(
{
root2 = 1.414;
}
public ReadOnlyMember(
{
weekDays =
}
static ReadOnlyMember(
{
yearDays = 365;
Console.WriteLine(
}
}
class ReadOnlyMemberProgra
{
public static void
{
ReadOnlyMember
Console.WriteLine(
Console.WriteLine(
//obj.root2 = 5; /
ReadOnlyMember
Console.WriteLine(
//obj1.weekDays =
Console.WriteLine(
Console.WriteLine(
Console.WriteLine(
Console.Read();
}
}
|
Output:
|
Error:
If
you try to re-assign the value of readonly field other than at variable
initialization and constructor we will get compile time error as “A readonly field can not be
0 Comments:
Post a Comment