• Profile
  • Resume
  • Portfolio
  • Blog
Avatar

Nelson Silva

A human. Being. Coffee lover.

Blog

I Write My Thoughts Here

ref and out in C#

December 9, 2021 C#

In this post, you will learn how to work with ref and out so that you can use that same knowledge and thus evolve.

  • the ref and the out do pretty much the same thing (they create a link with the argument sent to the given function);
  • if the content of that same argument changes, both change (inside and outside the function);
  • the only difference that exists between ref and out is just for the compiler, the ref transmits to the compiler that the argument was initialized before entering the function while the out transmits that the argument will be initialized inside the function.
using System;

namespace Base {
  class RefAndOut {
    public void Run() {
      int number = 0;

      Console.WriteLine($"Number before function: {number}");
      Out(out number);
      Console.WriteLine($"Number after function: {number}");
    }

    public void Normal(int number) {
      number = 1;
    }

    public void Ref(ref int number) {
      number = 2;
    }

    public void Out(out int number) {
      number = 3;
    }
  }
}

/*
  Number before function: 0
  Number after function: 3
*/

Don’t forget to watch the video and you can always read this post in Portuguese.

Happy coding!

Previous Next

Categories

  • Announcements
  • Python
  • C#
  • Java
  • Go

Latest Posts

  • for Loop in Go
    May 5, 2022
  • Switch in Go
    May 4, 2022
  • Comparison Operators in Go
    May 3, 2022
+351913416022
contact@nelsonsilvadev.com
Porto, Portugal
Nelson Silva © 2022 All Rights Reserved