-6

In C#, ref and out keyword.

How to it affect memory management? Is there any difference in memory management for ref and out keyword?

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
Sujeet Singh
  • 165
  • 3
  • 13

1 Answers1

8

Even though the mechanism used behind the scene is the same, the difference between the two keywords is in what the compiler must verify about each parameter:

  • If you pass a parameter with ref keyword, the compiler checks that you have initialized it before making the call
  • If you pass a parameter with out keyword, the compiler checks that the method that you call has made an assignment to the corresponding argument before exiting.

This difference allows for the out var construct, which has been added to C# 7.0. This feature would not be possible with ref alone because of the initialization requirement.

There is no difference between the two as far as the memory management is concerned: in both cases the reference itself is passed by value, and the code using the reference is adding an extra level of dereference.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • How do memory management happen in case of "ref" and "Out" keyword? Is there any difference? – Sujeet Singh Jul 21 '18 at 16:04
  • 1
    Nothing special is happening as far as the memory management is concerned: the reference is passed by value, and the code uses an additional level of dereference to get or set the actual value. – Sergey Kalinichenko Jul 21 '18 at 18:56