Blog for Junior Developers C#/.NET

Tuesday, May 14, 2024

I know that many of my readers are just looking for their first job and taking part in job interviews, so it is probably worth discussing topics that you may be asked about during your job interview. Unfortunately, there are many such questions, in subsequent articles I will introduce you to more, but today I will show you how in C# you can pass a variable of a simple type to a method using references. Of course, for this purpose we will have to use the ref or out keywords and this article will show you how to use them and what the basic differences are between them.

ref-vs-out-examples-in-csharp.jpg

What problem do we want to solve?


Let's assume we have a simple console application. In the Main method, we first initialize an int variable called myNumber, and then we call the IncrementValue method three times, which should increase the value of our variable by 1 each time. The code may look like this:

using System;

namespace Demo
{  
    class Program
    {
        static void Main()
        {
            int myNumber = 0;
            IncrementValue(myNumber);
            IncrementValue(myNumber);
            IncrementValue(myNumber);
            Console.WriteLine(myNumber);//0
        }

        public static void IncrementValue(int value)
        {
            value++;
        }
    }
}


Unfortunately, our variable was not incremented and still has the value 0. Why did this happen? The variable myNumber is of type int, and int is a simple type (value type), and therefore the value of the variable itself was passed to the IncrementValue method. In this case, the value of the myNumber variable is still the same. So how can we increase the value of the myNumber variable using the IncrementValue method? We need to pass the myNumber variable by reference to the IncrementValue method. To do this we need to use the ref or out keyword.


How to use the ref keyword?


In the signature of the IncrementValue method, you must mark the parameter with the word ref and when calling it, you must also add the ref keyword.

using System;

namespace Demo
{  
    class Program
    {
        static void Main()
        {
            int myNumber = 0;
            IncrementValue(ref myNumber);
            IncrementValue(ref myNumber);
            IncrementValue(ref myNumber);
            Console.WriteLine(myNumber);//3
        }

        public static void IncrementValue(ref int value)
        {
            value++;
        }
    }
} 


How to use the out keyword?

using System;

namespace Demo
{  
    class Program
    {
        static void Main()
        {
            int myNumber;
            IncrementValue(out myNumber);
            IncrementValue(out myNumber);
            IncrementValue(out myNumber);
            Console.WriteLine(myNumber);//11
        }

        public static void IncrementValue(out int value)
        {
            value = 10;
            value++;
        }
    }
}


 As you can see, out doesn't make much sense in this case, but you can use it similarly to ref. This means that when you want to use the out keyword, you must mark the parameter in the signature with this word and when calling the method you must also precede the argument with the out keyword. Since initialization before passing to the method is unnecessary, you can also call the method this way:

static void Main()
{
    IncrementValue(out int myNumber);
    Console.WriteLine(myNumber);
}


ref vs out – what is the difference between ref and out?


As you have probably noticed, both methods are slightly different from each other, because each of them will be more suited to a different situation. Basic differences between them:

  • A variable marked with the word ref must be initialized before being passed as a parameter. In our case: "int number = 0;".
  • A variable marked with the word out does not have to (but can) be initialized before being passed as a parameter. With us: "int number;". There may also be initialization before transfer, but this does not make any sense.
  • A variable marked by ref does not need to be initialized in the method. In our case, only the following entry was allowed: "value++;".
  • A variable marked with out must be initialized in the method. In our case, apart from incrementing, the variable had to be initialized first: "value = 10; value++;".


Which method should be used in which situation?


A variable marked with ref tells us that the variable has already been initialized and can be read and/or changed in the method, and all changes will be visible outside the method as well. A variable marked with out tells us that the variable has not been initialized yet, it has no value. Its value will be initialized inside the method and we usually use it in cases where we want the value of some variable to be changed outside the method.


SUMMARY


So as you can see, even though ref and out seem to have the same purpose, each of them will be useful in a different situation. We use ref when we are interested in both the value of the variable that was assigned before passing to the method and the value after exiting this method, and out when we are only interested in the value after exiting the method (as the name suggests). As I mentioned at the beginning, such a question may appear during your interview for the position of a junior C#/.NET programmer, if you are interested in other such questions, let me know in the comment. You can also take a look at the article where you will find the most common 100 questions with answers that I had during job interviews when I was looking for a job as a junior C# programmer.

Author of the article:
Kazimierz Szpin

KAZIMIERZ SZPIN
Software Developer C#/.NET, Freelancer. Specializes in ASP.NET Core, ASP.NET MVC, ASP.NET Web API, Blazor, WPF and Windows Forms.
Author of the blog CodeWithKazik.com

Previous article - Do You Really Know the Differences Between First vs FirstOrDefault vs Single vs SingleOrDefault?
Next article - 100 Interview Questions (and Answers!) for Junior Developers C#/.NET (Part 1/10)
Dodaj komentarz

Search engine

© Copyright 2024 CodeWithKazik.com. All rights reserved. Privacy policy.
Design by Code With Kazik