IMPORTANT PLEASE READ!
Website development and design blog, tutorials and inspiration

C# Constants and Read-Only Variables

How to use C# Constants and Read-Only Variables

By , Written on in C#

C# Constants and Read-Only Variables

591 words, estimated reading time 3 minutes.

C# constants are variables that hold static data and should be used anywhere that you would hard code static values. This allows for easier code maintenance and debugging as well as providing a central location for these values.
 
C# Programming Series
  1. Introduction to Programming
  2. What is C#?
  3. Your First Console Application in C#
  4. Introducing Methods and the Main() Function in C#
  5. Introducing C# Classes and Structs
  6. C# Data Types, Variables and Casting
  7. C# Program Flow Control and Entry Points
  8. Passing Parameters to Methods and Return Values in C#
  9. C# Access Modifiers and Scope
  10. C# Interfaces and Classes
  11. Using Namespaces in C#
  12. C# Conditional Statements
  13. Looping and Iteration in C#
  14. Using Arrays and Lists in C#
  15. C# Constants and Read-Only Variables
  16. Error and Exception Handling in C#
  17. Using Recursion in C#
  18. C# Operator List
  19. Class Inheritance in C#
  20. C# Class and Method Attributes Explained
  21. C# Class Constructors and Destructors
  22. C# Generics Variables
  23. XML Serialization and Deserialization
  24. C# String Formatting Examples

C# Constants and Read Only variables perform the same task, the only difference between them is that a constant is given a value at compile time and cannot ever be changed. Read Only variables can be assigned to once at runtime, but thereafter cannot be changed.

Constants

Constants are declared using the const keyword and can be used as class members or as method values and can be marked with any access modifier apart from static. Constants should be used anywhere where you would hard code a value, such as a number of results to return, literal strings, loop control, mathematical constants, fixed costs and so on.

  1. public const decimal pi = 3.14M;
  2. private const int numRows = 10;
  3. private const decimal vatRate = 17.5M;

This will define a value for pi which will never change once the program is compiled; similarly, numRows will be initialised to 10 and will never change. If you try to assign to a const value the compiler will throw an error.

Read Only

Read only values allow one assignment at runtime and can be used to hold information that needs to be read in or processed. Once a read-only value has been assigned to once it cannot be assigned to again until the application is restarted.

  1. public class SomeTestClass
  2. {
  3. private readonly string filePath;
  4.  
  5. public SomeTestClass(string filename)
  6. {
  7. filePath = Path.GetDirectoryName(filename);
  8. }
  9. }

This will initialise the value filePath to the directory of the specified filename. Once the constructor has assigned to filePath it can no longer be assigned to.

Using Consts and Read Only Values

Let's assume you are creating a class to deal with calculations involving circles. You create the class using hard coded values for pi.

  1. public class Circles
  2. {
  3. public double Circumference(double radius)
  4. {
  5. return circumference= 3.14 * (radius * 2);
  6. }
  7.  
  8. public double Area(double radius)
  9. {
  10. return area = 3.14 * Math.Pow(radius, 2);
  11. }
  12.  
  13. public double AnotherTest(double radius)
  14. {
  15. if (radius <= 3.14)
  16. return radius * 3.14 * Math.Pow(3.14, 3);
  17. else
  18. return radius * Math.Pow(3.14, 4);
  19. }
  20. }

You can imagine that this class could contain many more methods and constants. During testing, it has been found that the calculations performed do not have the accuracy required. It is necessary to improve accuracy by changing the value of pi from 3.14 to 3.1415926. How do you accomplish this?

You could do a search and replace, but how do you know that 3.14 is always the value of pi? The AnotherTest method does not use pi, but another fixed value that has the same value. Changing this value could result in undesired results.

It would be much better to have created the class using constants which would have the following benefits:

  1. The value of pi needs only to be changed once.
  2. You can be sure that you haven't missed any values.
  3. The code looks neater, and is easier to understand.
  4. pi value 3.14 is not confused with another value of 3.14
  1. public class Circles
  2. {
  3. private const double pi = 3.1415926;
  4. private const double test = 3.14;
  5.  
  6. public double Circumference(double radius)
  7. {
  8. return circumference= pi * (radius * 2);
  9. }
  10.  
  11. public double Area(double radius)
  12. {
  13. return area = pi * Math.Pow(radius, 2);
  14. }
  15.  
  16. public double AnotherTest(double radius)
  17. {
  18. if (radius <= test)
  19. return radius + test * Math.Pow(pi, 3);
  20. else
  21. return radius * Math.Pow(pi, 4);
  22. }
  23. }

From this, you can see that it is easy to see that the values for test and pi are totally different in the AnotherTest method. Also, to change the value of pi, simply change one line of code at the top of the class.

Of course in the real world, you would use Math.PI for the value of pi as this figure is an even more accurate predefined constant.

Last updated on: Thursday 22nd June 2017

Did you Like this Post? Why not Like us on Facebook?

 

Comments

There are no comments for this post. Be the first!

Leave a Reply

Your email address will not be published.