Readonly, const and yield keyword usage in C#

In this article, we will discuss the usage of Readonly, const, and yield keywords in C#, as well as when to use each of them. Their explanations will assist us in deciding what should be used in our code and with their practical coding examples will help us to simplify our task. At end of this article, you will come to understand the whole concept of these keywords. In C#, you can use a readonly keyword to declare a read-only variable. This readonly keyword shows that you can assign the value to variable only when you declare a variable or in a constructor of the same class in which it is declared.

The Constant fields and constant local are declared in C# using the const keyword. The constant field's value remains constant throughout the program, or in other words, once it has a value assigned, it cannot be modified. A constant in C# can be a number, text, null reference, or a boolean value. Constant fields and locals are not variables.

Whereas The yield keyword facilitates performing unique stateful iterations over a collection. The control switches from the caller function to the source function and vice versa when we employ the yield keyword.


Readonly Keyword in C#:


A variable or object can be designated as readable only by using the readonly keyword. You cannot change the value or reassign a value to a readonly variable or object in any other method except the constructor. In C#, you can use a readonly keyword to declare a read-only variable. This readonly keyword shows that you can assign the value to variable only when you declare a variable or in a constructor of the same class in which it is declared.

When we declare a variable by using the readonly keyword, then it is known as a read-only variable and these variables can’t be modified like constants but after initialization. That means it is not mandatory to initialize a read-only variable at the time of its declaration, they can also be initialized under the constructor. That means we can modify the read-only variable value only within a constructor.

Given below is an example of readonly keyword.



using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;


namespace ReadConstKeyword

{

    internal class Example

    {


            //Readonly Variable

            public readonly int myvar = 100;

            public readonly int myvar2;


  // Values of the readonly variable are assigned using Constructor

            public Example(int b)

            {

                myvar2 = b * 50;


            Console.WriteLine(myvar);

            Console.WriteLine(myvar2);

            }


    }

   

}


 class Program

 {


 using ReadConstKeyword;


 Example objExample = new Example(20);


    Console.ReadLine();

 }




Note: using readonly fields, we can assign values in Declaration as well as in the Constructor part.


Output:


100

1000




const keyword in C#:


Const stands for "constant," a variable whose value is fixed but determined at compile time. Additionally, you must provide it a value. A const variable's value is static by default, and we are unable to change it at any point in the program. If we use the const keyword to declare a variable in C#, it is a constant variable and its value cannot be changed once it has been declared. Therefore, initializing the constant variable must be done only when it is declared in C#, a constant variable whose value won't change throughout the program is defined by the const (read: constant) keyword. Therefore, you must provide a constant variable value at the moment of its declaration.

The Constant fields and constant local are declared in C# using the const keyword. The constant field's value remains constant throughout the program, or in other words, once it has a value assigned, it cannot be modified. A constant in C# can be a number, text, null reference, or a boolean value. Constant fields and locals are not variables.

Given below is an example of a const keyword.


class Program

{

     // const variable

    public const int myconst = 10;

    public const int myconst1;

    public Program()


    {

        myconst = 20; // we can’t change value of const variabl once it is assigned. 

    }


    public static void main(string[] args)

    {

        System.Console.WriteLine(myconst)

    }

}



Note: Using const fields we can assign values in the declaration part only.


Output:

// Error CS0131  The left-hand side of an assignment must be a variable, property or indexer ReadConstKeyword



Difference between readonly and const keyword in C#:


  • In readonly fields, we can assign values in declaration and in the constructor part. Whereas In const fields, we can only assign values in declaration part.


  • ReadOnly keyword is a runtime constant. Whereas Const keyword is a compile time constant.


  • The value of readonly field can be changed in Constructor. Whereas The value of the const field can not be changed.


  • Readonly keyword cannot be declared inside the method. Whereas Const keyword can be declared inside the method.


  • Readonly keyword can be used with static modifiers. Whereas Const keyword cannot be used with static modifiers.



Yield keyword in C#:


In C#, yield is a contextual keyword. Contextual keywords in C# aren't set aside for the entire program. Instead, they are reserved terms for specific areas of the program where they can be used appropriately. Wherever their relevance does not give the compiler any special meaning, these keywords can be used as legitimate identifiers. The keyword yield indicates that an iterator method or accessor is the one containing the keyword. A method or accessor that returns more than one value is called an iterator. Instead, it is called repeatedly and gives back a different value with each call.

Given below is an example of yield keyword.


class Myclass

{

    public static IEnumerable<string> GetMyList()

    {

   


// Creating and adding elements in list

        List<string> my_list = new List<string>() {"David", "jack", "Johnson", "Smith" };


        // Iterating the elements of my_list

        foreach (var items in my_list)

        {

            // Returning the element after every iteration

            yield return items;

        }

    }


    // Main Method

    static public void Main()

    {

        // Storing the elements of GetMyList

        IEnumerable<string> my_slist = GetMyList();


        // Display the elements return from iteration

        foreach (var i in my_slist)

        {

            Console.WriteLine(i);

        }

    }

   

}




Output:


 David

 jack

 Johnson

 Smith




Here is another example program of yield keyword. Let’s look at the implementation of yield keyword.

Example:


using System;

using System.Collections.Generic;

class Program

{

    // define an iterator method

    static IEnumerable<int> getNumber()

    {


        // create a list of integers

        List<int> myList = new List<int> { -1, -4, 3, 5 };

        foreach (var num in myList)

        {


            // returns positive number from myList

            if (num >= 0)

            {


                yield return num;

                // location of the code is preserved

                // so on the next iteration getNumber() is executed from here

                Console.WriteLine("....");

            }

        }

    }


    static void Main()

    {

        // display return values of getNumber()

        foreach (var items in getNumber())

        {

            Console.WriteLine(items);

        }

    }

}




Output:


 3

 ....


 5

 ....




Conclusion:


This article taught us that the C# keyword yield is really useful. It makes the code more comprehensible and aids in condensing difficult issues into the fewest number of lines. To put it plainly, the yield keyword effectively generates a lazy enumeration over collection objects that can be far more effective. This C# journey article was written at an advanced level. To gain some practical experience, it is advised that you attempt to use the keyword in your code.

Hope you enjoyed reading this article and found it useful. Please share your thoughts and recommendations in the comment section below.


Share This Post

Linkedin
Fb Share
Twitter Share
Reddit Share

Support Me

Buy Me A Coffee