-2

Why is vowels not null after call my method? string[] is a reference type, I don't understand?

using System;

class Program
{
  public static string[] vowels = {"A", "E", "I", "O", "U"};

  public static void SetArrayToNull(string[] array)
  {
    array = null;
  }

  public static void Main(string[] args)
  {
    SetArrayToNull(vowels);
    Console.WriteLine(vowels == null); //writes "false"
  }
}
Scath
  • 3,777
  • 10
  • 29
  • 40
bobls
  • 9
  • 2
  • You don't set `vowels` to `null`, but `array`, which is only a parameter - a variable in the local scope of `SetArrayToNull()`, not a reference to the _variable_ passed. – René Vogt Aug 25 '17 at 17:12
  • Because this is a reference of a object not the object as it. – z3nth10n Aug 25 '17 at 17:12
  • Reference types/value types is a different concept than pass-by-reference/pass-by-value. So many people get them confused. – Dennis_E Aug 25 '17 at 17:18

1 Answers1

-2

You should use ref keyword.

As you can see here: https://learn.microsoft.com/en-en/dotnet/csharp/language-reference/keywords/ref

Because, your main problem is that the variable you passed as parameter is only modified in the local scope of the SetArrayToNull method.

But, by using the ref keyword, you will avoid this. Because the changes that you make in the local scope of this method will be updated outside of you call.

As simple as this:

using System;

class Program
{
  public static string[] vowels = {"A", "E", "I", "O", "U"};

  public static void SetArrayToNull(ref string[] array)
  {
    array = null;
  }

  public static void Main(string[] args)
  {
    SetArrayToNull(ref vowels);
    Console.WriteLine(vowels == null); //now, it will writes "true" :)
  }
}
z3nth10n
  • 2,341
  • 2
  • 25
  • 49