nordwindranger

my microsoft visual c# 2005 step by step book states that "when you pass an argument to a method, the corresponding parameter is initialized with a copy of the argument".

Before I read this, I assumed that if I did not use "new" when creating variables, and then setting these variables equal to parameters I was creating references to the parameters. The book however, seems to suggest that if I don't pass parameters in with the word "ref", they will always just be copies.

I frantically checked through my project fearing that I would have to rewrite a lot of code. However I found that when I passed a list of objects (list<ship> ships) into a new instance of a class, it definitely acted as a reference (changes passed both ways). Are generic lists an exception to this rule Are there any other exceptions

thanks

Andrew




Re: Visual C# Language parameters and "ref"

Marcelo Guerra - MSFT

Hi,

That rule only applies to value types. Reference types like Lists are always passed by reference.

You can find more about this on the C# spec http://download.microsoft.com/download/a/9/e/a9e229b9-fee5-4c3e-8476-917dee385062/csharp%20language%20specification%20v1.0.doc chapter 5.

As a summary: basic types (int, float, bool, etc.) and structs are value types, all the others are reference types.





Re: Visual C# Language parameters and "ref"

micvos

Without the ref keyword, all parameters are copied to the stack when they are passed to a method. This means that for value types, the value is copied and for reference types it means that the reference is copied. But the copy of the reference points to the same object so you get the illusion that the real object is copied. But this is not true because if you change the reference of the parameter to another object within your method, you'll not find any difference outside the method. This is because you only changed the copy of the reference.




Re: Visual C# Language parameters and "ref"

micvos

for instance this won't work:

public static void Swap(string a, string b)

{

string c = a;

a = b;

b = c;

}

But this will:

public static void Swap(ref string a, ref string b)

{

string c = a;

a = b;

b = c;

}






Re: Visual C# Language parameters and "ref"

nordwindranger

thanks for all the help guys. Clearly this is something that I'm going to have to get pretty familiar with