Monday, March 31, 2008

C# quiz: 2/?

Continuing on the series of C# and/or .NET Framework short questions:

        private void Foo(List<int> bar) {
bar = new List<int>();
// ...
}

With the method above and the code below:

        List<int> bar = null;
Foo(bar);
if (bar != null) {
Console.WriteLine("populated");
} else {
Console.WriteLine("still null");
}
If or else ?

EDIT: fixed typo in code sample.

2 comments:

Anonymous said...

actually, this has compiler errors because you define 'bar' as the variable and then check 'foo'

List<int> bar = null;
Foo ( bar );
if ( foo != null ) {

but, fixing the error results in the opposite of what I first assumed. Then after thinking about it, it makes since. Value types ( in this case int ) are copied or passed by value, not passed by reference.

If you explicitly indicate to pass the list by reference then the result is 'populated'.

/SiD said...

Oops, thanks for spotting that. Fixed the code.