[ Whitepaper ] Parameter passing in C# (reference types)


(Haso Keric) #1

Good Article: http://jonskeet.uk/csharp/parameters.html#ref

I come from the C++ world and logically this confused me about 2 years ago, I stumbled upon this piece of code again, thought Id post it.

UD01 newRow = new UD01();
Db.UD01.Insert(newRow);
newRow.Company = Session.CompanyID;
newRow.Key1 = "12345";
newRow.ShortChar01 = "abcde";
Db.Validate();
txScope.Complete();

I couldn’t grasp how I can Db.UD01.Insert(newRow); and then assign values after it, Db.Validate() would still accept it just fine. Logically in my mind, I should assign it values, and then call Insert. I certainly never passed it in with the ref keyword, that’s why I was confused. But it didn’t matter. C# by default assumes ref, not in all cases.

I knew about the ref keyword and have been using it, but never assumed .NET by default passed things through as ref.


(Bart Elia) #2

That bit me as well - probably same reason having grown up in the C++ world (among others).

There are a few ‘defaults’ (pun intended) that can bite you as you transition from apprentice to journeyman. I’d throw that on in there.


(Jose C Gomez) #3

I believe this is just object oriented concept. Non primitives (objects) are always passed by reference


(Mark Wonsil) #4

And coming from Pascal, the auto-conversion of C++ argument types bit me in my short time with C++.

Mark W.


(Bart Elia) #5

Transitions are always ‘interesting’ (e.g. - That old saying about may you live in interesting times as a curse). We have an interesting industry that is extremely dynamic. My best summary I have heard of late:

Developers - Those who have decided to do homework everyday for the rest of their lives.