C# Ref Keyword

C# Code Snippets Ref Keyword
Share:

About

In this code snippet, we’ll take a look at what the ref keyword does in C#.

Variables can be passed either by value or by reference.

Usually, we do it by value meaning you pass just the value and not the variable itself. So, any changes made locally inside the method scope won’t be seen outside of the method scope. 

Meanwhile, if we pass a variable as a reference is essentially like passing in the variable itself. Any changes made locally inside the method to the variable will occur outside of the method scope as well. 

Let’s see the code example below.

Code:

using System;

namespace PassByReference
{
    class Program
    {
        static void Main(string[] args)
        {
            string a = "Hello ";
            string b = "Hello ";

            Console.WriteLine("String a before being passed in to the method: " + a);
            writeToConsole(a);
            Console.WriteLine("String a after being passed in to the method: " + a);

            Console.WriteLine("");

            Console.WriteLine("String b before being passed in to the method: " + b);
            writeToConsole(ref b);
            Console.WriteLine("String b after being passed in to the method: " + b);

            Console.ReadLine();
        }

        public static void writeToConsole(ref string inputString)
        {
            //Prompt user for name.
            Console.WriteLine("Enter your name: ");
            //Read user input.
            string consoleInput = Console.ReadLine();

            //Combine strings.
            inputString = inputString + consoleInput;

            //Write to console.
            Console.WriteLine(inputString);
        }

        public static void writeToConsole(string inputString)
        {
            //Prompt user for name.
            Console.WriteLine("Enter your name: ");
            //Read user input.
            string consoleInput = Console.ReadLine();

            //Combine strings.
            inputString = inputString + consoleInput;

            //Write to console.
            Console.WriteLine(inputString);
        }
    }
}

Resulting output:

Share:

Leave a Reply

Your email address will not be published. Required fields are marked *

The following GDPR rules must be read and accepted:
This form collects your name, email and content so that we can keep track of the comments placed on the website. For more info check our privacy policy where you will get more info on where, how and why we store your data.

Advertisment ad adsense adlogger