Only Reading a Value

Introduction

When creating a field of a class, one of the decisions you must make is how the field would get its value(s). To create a field so that objects outside the class can only view its value but cannot change it while the value can be changed inside the class, you must indicate to the the compiler that the value will be treated as read-only.

Practical LearningPractical Learning: Introducing Constants

  1. Start Microsoft Visual Studio
  2. Create a new Console App named PlanarCurves3
  3. To create a new folder, in the Solution Explorer, right-click PlanarCurves3 -> Add -> New Folder
  4. Type Models as the name of the folder
  5. In the Solution Explorer, right-click Models -> Add -> Class...
  6. Change the file Name to Circle
  7. Press Enter
  8. Change the document and the class as follows:
    namespace PlanarCurves3.Models
    {
        internal class Circle
        {
            public const double PI = 3.14;
    
            public double Radius { get; set; }
    
            public Circle()
            {
                Radius = 0.00;
            }
    
            public double CalculateDiameter()
            {
                return Radius * 2.00;
            }
    
            public double CalculateArea()
            {
                return Radius * Radius * PI;
            }
        }
    }
  9. In the Solution Explorer, right-click Program.cs and click Rename
  10. Type Geometry (to get Geometry.cs) and press Enter
  11. Read the message in the message box and click Yes
  12. Click the Geometry.cs tab to access it
  13. Change the document as follows:
    using PlanarCurves3.Models;
    using static System.Console;
    
    var round = new Circle();
    
    WriteLine("=====================================");
    WriteLine("Enter the value to process the circle");
    Write("Radius:      ");
    round.Radius = double.Parse(ReadLine());
    
    WriteLine("=====================================");
    WriteLine("Geometry - Circle Summary");
    WriteLine("-------------------------------------");
    WriteLine("Radius:   {0}", round.Radius);
    WriteLine("Diameter: {0}", round.CalculateDiameter());
    WriteLine("Area:     {0}", round.CalculateArea());
    Write("=====================================");
  14. To execute the application, on the main menu, click Debug -> Start Without Debugging:
  15. When requested, type the Radius as 248.73 and press Enter:
    =====================================
    Enter the value to process the circle
    Radius:      248.73
    =====================================
    Geometry - Circle Summary
    -------------------------------------
    Radius:   248.73
    Diameter: 497.46
    Area:     194261.16450599997
    =====================================
    
    Press any key to close this window . . .
  16. To close the window, press Enter and return to your programming environment
  17. Click the Circle.cs tab to access the class

A Read-Only Tuple

You can create a regular tuple but whose value depends on specific objects. This is the case for a read-only tuple. You can create it in the body of a class and initialize it in a constructor. Here is an example:

public class Memory
{
    public readonly (int numberOfSockets, int memoryInGB) partition;

    public Memory()
    {
        partition = (2, 8);
    }

    public Memory(int capacity)
    {
        partition = (2, 16);
    }
}

A Read-Only Field in a Type

To let you create a read-only field, the C# language provides a keyword named readonly. Therefore, to create a read-only field, declare its variable in the body of the class but outside any method or property. Precede its data type with the readonly keyword. Here is an example:

public class Circle
{
    readonly double PI;
}

You can mark the field with an access level such as private or public, depending on your intentions.

To specify the value of a read-only field, use a constructor, such as the default constructor, to initialize the field. Here is an example:

public class Circle
{
    private double r;

    private readonly double PI;

    public Circle()
    {
       	PI = 3.14;
    }
}

The only difference between a constant variable and a read-only field is that a constant variable must be initialized when creating it. On the other hand, you can create more than one constructor in a class, then assign the same or a different value in each constructor to the read-only field. This means that, because you can initialize a read-only field in a constructor, if you have different constructors, you can also have different values for the same read-only field. Here are examples:

public class Circle
{
    private double r;

    private readonly double PI;

    public Circle()
    {
       	PI = 3.14;
    }

    public Circle(double rad)
    {
       	r = rad;
        PI = 3.14159;
    }

    public double CalculateDiameter()
    {
       	return r * 2;
    }

    public double CalculateArea()
    {
       return r * r * PI;
    }
}

Instead of a constant value, the value of a read-only field can come from an expression. If the value held by a read-only field is gotten from an expression, then the field must be initialized in the(a) constructor with the desired expression.

We know that a constant variable must be initialized when it is created. Although a read-only variable seems to follow the same rule, it doesn't. Remember that you don't need to initialize a read-only variable when you declare it since you can do this in the(a) constructor of the class. Also, because a constructor can be overloaded, a read-only field can hold different values depending on the particular constructor that is accessed at a particular time, but the value of a constant variable cannot change: it is initialized once, in the class (or in a method) and it keeps that value throughout the class (or method).

ApplicationPractical Learning: Creating and Using a Read-Only Field

  1. You can initialize a read-only field in the (a) constructor of its class. For an example, change the Circle class as follows:
    namespace PlanarCurves3.Models
    {
        public class Circle
        {
            public readonly double PI;
    
            public double Radius { get; set; }
    
            public Circle()
            {
                PI = 3.14;
                Radius = 0.00;
            }
    
            public double CalculateDiameter()
            {
                return Radius * 2.00;
            }
    
            public double CalculateArea()
            {
                return Radius * Radius * PI;
            }
        }
    }
  2. Click the Geometry.cs tab
  3. Change the code of the event as follows:
    using PlanarCurves3.Models;
    using static System.Console;
    
    var round = new Circle();
    
    WriteLine("=====================================");
    WriteLine("Enter the value to process the circle");
    Write("Radius:   ");
    round.Radius = double.Parse(ReadLine());
    
    WriteLine("=====================================");
    WriteLine("Geometry - Circle Summary");
    WriteLine("-------------------------------------");
    WriteLine("Radius:   {0}", round.Radius);
    WriteLine("PI:       {0}", round.PI);
    WriteLine("Diameter: {0}", round.CalculateDiameter());
    WriteLine("Area:     {0}", round.CalculateArea());
    Write("=====================================");
  4. To execute the application, on the main menu, click Debug -> Start Without Debugging:
  5. For the Side, type 5377.96 and press Enter:
    =====================================
    Enter the value to process the circle
    Radius:   5377.96
    =====================================
    Geometry - Circle Summary
    -------------------------------------
    Radius:   5377.96
    PI:       3.14
    Diameter: 10755.92
    Area:     90816504.811424
    =====================================
    
    Press any key to close this window . . .
  6. To close the window and return to your programming environment, press K
  7. Click the Circle.cs tab to access the class
  8. Because a read-only field can be initialized in a constructor, each constructor can assign a different value to the field. As a result, a read-only field can have different values. When you create an object, the constructor you choose will provide the value of the read-only field. For examples, change the Circle class as follows:
    namespace PlanarCurves3.Models
    {
        public class Circle
        {
            public readonly double PI;
    
            public double Radius { get; set; }
    
            public Circle()
            {
                PI = 3.14;
                Radius = 0.00;
            }
    
            public Circle(double rad)
            {
                Radius = rad;
                PI = 3.14159;
            }
    
            public double CalculateDiameter()
            {
                return Radius * 2.00;
            }
    
            public double CalculateArea()
            {
                return Radius * Radius * PI;
            }
        }
    }
  9. Click the Geometry.cs tab to access the code
  10. Change the code as follows:
    using PlanarCurves3.Models;
    using static System.Console;
    
    WriteLine("=====================================");
    WriteLine("Enter the value to process the circle");
    Write("Radius:   ");
    double rad = double.Parse(ReadLine());
    
    var round = new Circle(rad);
    
    WriteLine("=====================================");
    WriteLine("Geometry - Circle Summary");
    WriteLine("-------------------------------------");
    WriteLine("Radius:   {0}", round.Radius);
    WriteLine("PI:       {0}", round.PI);
    WriteLine("Diameter: {0}", round.CalculateDiameter());
    WriteLine("Area:     {0}", round.CalculateArea());
    Write("=====================================");
  11. To execute the project, on the main menu, click Debug -> Start Without Debugging
  12. For the Side, type 1327.97
    =====================================
    Enter the value to process the circle
    Radius:   1327.97
    =====================================
    Geometry - Circle Summary
    -------------------------------------
    Radius:   1327.97
    PI:       3.14159
    Diameter: 2655.94
    Area:     5540207.539496231
    =====================================
    
    Press any key to close this window . . .
  13. To close the window and return to your programming environment, press K
  14. Click the Circle.cs tab and change the Circle class as follows:
    namespace PlanarCurves3.Models
    {
        internal class Circle
        {
            public readonly double PI;
    
            public Circle() : this(0.00)
            {
                PI = 3.14;
            }
    
            public Circle(double rad)
            {
                Radius = rad;
                PI = 3.14159;
            }
    
            public double Radius { get; set; }
    
            public double CalculateDiameter() => Radius * 2.00;
    
            public double CalculateArea()     => Radius * Radius * PI;
        }
    }
  15. To execute the project, on the main menu, click Debug -> Start Without Debugging
  16. For the Side, type 1003.77
    =====================================
    Enter the value to process the circle
    Radius:      1003.77
    =====================================
    Geometry - Circle Summary
    -------------------------------------
    Radius:   1003.77
    PI:       3.14159
    Diameter: 2007.54
    Area:     3165322.2397045107
    =====================================
    
    Press any key to close this window . . .
  17. To close the window and return to your programming environment, press L
  18. Start a new Console App named ElectricityDistributionCompany2
  19. To create a new folder, in the Solution Explorer, right-click ElectricityDistributionCompany2 -> Add -> New Folder
  20. Type Models as the name of the folder
  21. In the Solution Edplorer, right-click Models -> Add -> Class...
  22. Change the file Name to Meter
  23. Click Add
  24. Change the class as follows:
    namespace ElectricityDistributionCompany2.Models
    {
        public class Meter
        {
            public string? MeterNumber { get; set; }
            public string? Make { get; set; }
            public string? Model { get; set; }
    
            public string Describe() => Make + " " + Model + " (Mtr #: " + MeterNumber + ")";
        }
    }
  25. In the Solution Edplorer, right-click Models -> Add -> Class...
  26. Change the file Name to CounterReading
  27. Click Add
  28. Change the class as follows:
    public class CounterReading
    {
        private Meter mtr;
        public int TotalUse { get; set; }
    
        public CounterReading()
        {
            mtr = new();
            mtr.Make = "Horriander";
            mtr.Model = "CXL 3600";
            mtr.MeterNumber = "M927084";
        }
    
        public Meter Read() => mtr;
    }
  29. In the Solution Edplorer, right-click Models -> Add -> Class...
  30. Change the file Name to Calculations
  31. Press Enter
  32. Change the class as follows:
    namespace ElectricityDistributionCompany2.Models
    {
        public class Calculations
        {
            public CounterReading Useage { get; set; } = new CounterReading();
    
            public const double CustomerCharge = 7.60;
            public const double DeliveryTaxRate = 6.20;
            public const double EnergyChargeRate = 6.2655;
            public const double GridResilienceChargeRate = 12;
            public const double EnvironmentSurchargeRate = 14.90;
    
            public Calculations() => Useage.TotalUse = 1497;
    
            public double CalculateEnergyCharges() => Useage.TotalUse * EnergyChargeRate / 100;
            public double CalculateGridResilienceCharges() => Useage.TotalUse * GridResilienceChargeRate / 100000;
            public double CalculateDeliveryTaxes() => Useage.TotalUse * DeliveryTaxRate / 10000;
            public double CalculateEnvironmentalSurcharge() => Useage.TotalUse * EnvironmentSurchargeRate / 100000;
    
            public double EvaluateAmountDue()
            {
                return CustomerCharge +
                       CalculateEnergyCharges() +
                       CalculateGridResilienceCharges() +
                       CalculateDeliveryTaxes() +
                       CalculateEnvironmentalSurcharge();
            }
    
            public CounterReading Prepare() => Useage;
        }
    }
  33. In the Solution Edplorer, right-click Models -> Add -> Class...
  34. Change the file Name to ElectriBill
  35. Click Add
  36. Change the class as follows:
    namespace ElectricityDistributionCompany2.Models
    {
        public class ElectriBill
        {
            private Calculations values;
    
            public ElectriBill()
            {
                values = new();
            }
    
            public Calculations Prepare() => values;
    
            public string Summarize()
            {
                return values.Prepare()
                             .Read()
                             .Describe();
            }
        }
    }

A Read-Only Referenced Variable

Remember that, to use a referenced variable, you must assign a previously declared and initialized variable to it. For the same reason, you cannot assign a regular value to a referenced variable. If you do, when you execute the program, the compiler would produce an error. This makes a referenced variable is a read-only item. To re-enforce this idea, you can indicate to the compiler that your referenced variable a read-only item. To do this, follow the ref keyword of the referenced variable with the readonly keyword, as in ref readonly. This can be done as follows:

using static System.Console;

double side = 248.57;
    
ref readonly double oneOf4Sides = ref side;
ref readonly double siding = ref side;
ref readonly double coast = ref side;
    
WriteLine("Square Characteristics");
WriteLine("------------------------");
WriteLine("Original Side:   {0}", side);
WriteLine("Referenced Side: {0}", oneOf4Sides);
WriteLine("Referenced Side: {0}", siding);
WriteLine("Referenced Side: {0}", coast);
WriteLine("========================");

Updating a Referenced Variable

Remember that, when you have declared and initialized a referenced variable, it holds the same value as its referent. As a consequence, if you change the value of the original variable, the value of the referenced variable also changes. This can be illustrated as follows:

using static System.Console;

double side = 248.57;

ref readonly double oneOf4Sides = ref side;
ref readonly double siding = ref side;

WriteLine("Square Characteristics");
WriteLine("------------------------");
WriteLine("Original Side:   {0}", side);
WriteLine("One of 4 Sides:  {0}", oneOf4Sides);
WriteLine("Siding:          {0}", siding);
WriteLine("========================");

side = 66.93;

ref readonly double coast = ref side;
ref readonly double quad = ref side;

WriteLine("Square Characteristics");
WriteLine("------------------------");
WriteLine("Original Side:   {0}", side);
WriteLine("One of 4 Sides:  {0}", oneOf4Sides);
WriteLine("Siding:          {0}", siding);
WriteLine("Coast:           {0}", coast);
WriteLine("Quad Side:       {0}", quad);
WriteLine("========================");

This would produce:

Square Characteristics
------------------------
Original Side:   248.57
One of 4 Sides:  248.57
Siding:          248.57
========================
Square Characteristics
------------------------
Original Side:   66.93
One of 4 Sides:  66.93
Siding:          66.93
Coast:           66.93
Quad Side:       66.93
========================

Press any key to close this window . . .

In the same way, you can change the value of a referent as many times as you want and keep in mind that its associated referenced variable is updated. Therefore, if you are planning to use the value of a referenced variable, make sure it is holding the intended value at that time. As a result, you are free to change the value of the original variable any time but use the referenced variable, knowing that its value will automatically be updated. This can be verified in the following code:

using static System.Console;

WriteLine("Square Characteristics");
WriteLine("------------------------");

double side = 248.57;
ref readonly double oneOf4Sides = ref side;

WriteLine("Original Side:   {0}", side);
WriteLine("Referenced Side: {0}", oneOf4Sides);
WriteLine("------------------------");

side = 937.866;

WriteLine("Original Side:   {0}", side);
WriteLine("Referenced Side: {0}", oneOf4Sides);
WriteLine("------------------------");

side = 66.93;

WriteLine("Original Side:   {0}", side);
WriteLine("Referenced Side: {0}", oneOf4Sides);
WriteLine("------------------------");

side = 1057.48;

WriteLine("Original Side:   {0}", side);
WriteLine("Referenced Side: {0}", oneOf4Sides);
WriteLine("========================");

In the above example, notice that only the value of the referent is updated, but every time, the referenced variable is automatically updated. The above code would produce:

Square Characteristics
------------------------
Original Side:   248.57
Referenced Side: 248.57
------------------------
Original Side:   937.866
Referenced Side: 937.866
------------------------
Original Side:   66.93
Referenced Side: 66.93
------------------------
Original Side:   1057.48
Referenced Side: 1057.48
========================

Press any key to close this window . . .

Passing a Primitive Reference to an Object

Since a referenced variable holds a real value, you can use it wherever you would use the original variable. For example, you can pass it as argument. Here is an example where a referenced variable is passed to a constructor of an object:

using static System.Console;

double side = 248.57;
    
ref double oneOf4Sides = ref side; 
Square sqr = new Square(oneOf4Sides);
    
WriteLine("Square Characteristics");
WriteLine("----------------------------");
WriteLine("Side:      {0}", sqr.Side);
WriteLine("Perimeter: {0}", sqr.CalculatePerimeter());
WriteLine("Area:      {0}", sqr.CalculateArea());
WriteLine("============================");
    
public class Square(double side)
{
    public double Side
    {
        get { return side; }
    }
    
    public double CalculatePerimeter()
    {
        return side * 4;
    }
    
    public double CalculateArea()
    {
        return side * side;
    }
}

When it comes to using a referenced variable as argument, whenever you do that, you must let the compiler know so it would update its operation(s). This can be easily done by re-calling the item(s) that use(s) the argument. Here are examples:

using static System.Console;

// Declare a variable
double side = 248.57;
// Create a referenced variable
ref readonly double oneOf4Sides = ref side;
// Pass the referenced variable to an object
Square sqr = new(oneOf4Sides);

WriteLine("Square Characteristics");
WriteLine("----------------------------");
WriteLine("Side:      {0}", sqr.Side);
WriteLine("Perimeter: {0}", sqr.CalculatePerimeter());
WriteLine("Area:      {0}", sqr.CalculateArea());
WriteLine("============================");

// Change the value of the original variable
side = 937.866;
// Let the compiler know that the value passed to the object has changed
sqr = new(oneOf4Sides);

WriteLine("Square Characteristics");
WriteLine("----------------------------");
WriteLine("Side:      {0}", sqr.Side);
WriteLine("Perimeter: {0}", sqr.CalculatePerimeter());
WriteLine("Area:      {0}", sqr.CalculateArea());
WriteLine("============================");

// Update the original variable
side = 66.93;
// Notify the compiler that the value of the object has changed
sqr = new(oneOf4Sides);

WriteLine("Square Characteristics");
WriteLine("----------------------------");
WriteLine("Side:      {0}", sqr.Side);
WriteLine("Perimeter: {0}", sqr.CalculatePerimeter());
WriteLine("Area:      {0}", sqr.CalculateArea());
WriteLine("============================");

// Update the referent
side = 1057.48;
// Let the compiler know that there is a new value for the object
sqr = new(oneOf4Sides);

WriteLine("Square Characteristics");
WriteLine("----------------------------");
WriteLine("Side:      {0}", sqr.Side);
WriteLine("Perimeter: {0}", sqr.CalculatePerimeter());
WriteLine("Area:      {0}", sqr.CalculateArea());
WriteLine("============================");

public class Square(double side)
{
    public double Side
    {
        get { return side; }
    }

    public double CalculatePerimeter()
    {
        return side * 4;
    }

    public double CalculateArea()
    {
        return side * side;
    }
}

This would produce:

Square Characteristics
----------------------------
Side:      248.57
Perimeter: 994.28
Area:      61787.04489999999
============================
Square Characteristics
----------------------------
Side:      937.866
Perimeter: 3751.464
Area:      879592.633956
============================
Square Characteristics
----------------------------
Side:      66.93
Perimeter: 267.72
Area:      4479.624900000001
============================
Square Characteristics
----------------------------
Side:      1057.48
Perimeter: 4229.92
Area:      1118263.9504
============================

Press any key to close this window . . .

A Read-Only Object Type

We already know that if we create a field that is a class type, we must find a way to initialize the field before it. Such an intialization can be done in a constructor. When studying fields created from primitive types, we saw that, to indicate that the field is initialized in a constructor of the class where the field is created, you can mark that field with the readonly keyword. This feature is also available for fields of class type.

ApplicationPractical Learning: Creating a Read-Only Object

  1. To create a read-only field, click the CounterReading.cs tab and make the following change:
    namespace ElectricityDistributionCompany2.Models
    {
        public class CounterReading
        {
            private readonly Meter mtr;
            public int TotalUse { get; set; }
    
            public CounterReading()
            {
                mtr = new();
                mtr.Make = "Horriander";
                mtr.Model = "CXL 3600";
                mtr.MeterNumber = "M927084";
            }
    
            public Meter Read() => mtr;
        }
    }
  2. To create another read-only field, click the ElectriBill.cs tab and make the following change:
    namespace ElectricityDistributionCompany2.Models
    {
        public class ElectriBill
        {
            private readonly Calculations values;
    
            public ElectriBill()
            {
                values = new();
            }
    
            public Calculations Prepare() => values;
    
            public string Summarize()
            {
                return values.Prepare()
                             .Read()
                             .Describe();
            }
        }
    }
  3. In the Solution Explorer, right-click Program.cs and click Rename
  4. Type BillProcessing (to get BillProcessing.cs) and press Enter
  5. Click the BillProcessing.cs tab to access its document
  6. Change the document as follows:
    using static System.Console;
    using ElectricityDistributionCompany2.Models;
    
    var eb = new ElectriBill();
    
    WriteLine("===================================================================");
    WriteLine("Electricity Distribution Company");
    WriteLine("===================================================================");
    
    WriteLine("Meter #:                     {0}", eb.Prepare()
                                                    .Useage
                                                    .Read()
                                                    .MeterNumber);
    WriteLine("Make:                        {0}", eb.Prepare()
                                                    .Useage
                                                    .Read().Make);
    WriteLine("Model:                       {0}", eb.Prepare()
                                                    .Useage
                                                    .Read().Model);
    WriteLine($"Meter Details:               {eb.Summarize()}");
    WriteLine("-------------------------------------------------------------------");
    WriteLine($"Customer Charge:             {Calculations.CustomerCharge:F}");
    WriteLine($"Delivery Tax Rate:           {Calculations.DeliveryTaxRate:F}");
    WriteLine($"Energy Charge Rate:          {Calculations.EnergyChargeRate:F}");
    WriteLine($"Grid Resilience Charge Rate: {Calculations.GridResilienceChargeRate:F}");
    WriteLine($"Environment Surcharge Rate:  {Calculations.EnvironmentSurchargeRate:F}");
    WriteLine("-------------------------------------------------------------------");
    WriteLine($"Total Use:                   {eb.Prepare().Useage.TotalUse:f}");
    WriteLine($"Environmental Surcharge:     {eb.Prepare().CalculateEnvironmentalSurcharge():f}");
    WriteLine($"Delivery Taxes:              {eb.Prepare().CalculateDeliveryTaxes():f}");
    WriteLine($"Grid Resilience Charges.:    {eb.Prepare().CalculateGridResilienceCharges():f}");
    WriteLine($"Energy Charges.:             {eb.Prepare().CalculateEnergyCharges():f}");
    WriteLine("-------------------------------------------------------------------");
    WriteLine($"Amount Due.:                 {eb.Prepare().EvaluateAmountDue():f}");
    WriteLine("==================================================================="); 
  7. To execute, on the main menu, click Debug -> Start Without Debugging:
    ===================================================================
    Electricity Distribution Company
    ===================================================================
    Meter #:                     M927084
    Make:                        Horriander
    Model:                       CXL 3600
    Meter Details:               Horriander CXL 3600 (Mtr #: M927084)
    -------------------------------------------------------------------
    Customer Charge:             7.60
    Delivery Tax Rate:           6.20
    Energy Charge Rate:          6.27
    Grid Resilience Charge Rate: 12.00
    Environment Surcharge Rate:  14.90
    -------------------------------------------------------------------
    Total Use:                   1497.00
    Environmental Surcharge:     0.22
    Delivery Taxes:              0.93
    Grid Resilience Charges.:    0.18
    Energy Charges.:             93.79
    -------------------------------------------------------------------
    Amount Due.:                 102.73
    ===================================================================
    
    Press any key to close this window . . .
  8. To close the window and return to Microsoft Visual Studio, press Enter

Previous Copyright © 2001-2026, FunctionX Sunday 03 May 2026, 19:58 Next