Coding Challenge 2004125-1

Question: What is going on here and WHY?

 

using System;

using System.Collections;

 

class Hello {

    private string[] _stuff = new string[] {"Hello", "World"};

    public string[] SomeProperty {

        get{return this._stuff;}

    }

}

 

class App {

    public static void Main() {

        Hello h = new Hello();

        string[] retValue = h.SomeProperty;

 

        //print values of retValue

        foreach(string s in retValue) {

            Console.WriteLine(s); //works as expected

        }

 

        SomeOperation(retValue);

 

        foreach(string s in h.SomeProperty) {

            //Nothing prints here - why !!!

            Console.WriteLine(s);

        }

 

    }

 

    public static void SomeOperation(string[] s) {

        Array.Clear(s, s.GetLowerBound(0), s.Length);

    }

}

 

The array is passed by reference, so when you send it to SomeOperatrion and clear it, it's actually clearing the private array in your class?

You mean the array is passed by reference to SomeOperation?

If that were the case, you'd have to use the "ref" keyword" in both the function call and function signature:

public static void SomeOperation(ref string[] s)
  • and -

SomeOperation(ref retValue);

Nope, the array is being passed by value (default in C#).

because Bill Gates hates me.

because arrays are reference type variables (they don't store the data itself, just a reference to it).

JCT is correct. The reference all along is to the private field _stuff. Because _stuff is a reference type, you need to copy it before returning it. Otherwise your class is not "immutable"

Thats what I meant, your variable is a reference to the array, not a copy. I guess passed was the wrong word, I should have said assigned or something.

If that's what you meant, then you got it right. :-)

I misunderstoon your answer.

Excellent. This is going on my resume. With a footnote.

Solved Coding challenge #1*

*Complained until the decison was overturned

ttt