Rob Garrett - Blogs

Welcome to Rob Garrett - Blogs Sign in | Join | Help
in Search
Google

Software/Technology Discussion

Software and Technology Tid-bits

Pass by Reference

Contrary to the beliefs of some developers, .Net reference types do not need to be passed as reference parameters (ref in C#, ByRef in VB) when a method is going to alter the contents of an object instance.

Passing a object reference by reference parameter just means the method can reassign the reference to a new object instance. The following reference parameter shown below is unnecessary:

class foo
{
public int i;
}

... void fooMethod(ref foo fooInst)
{
fooInst.i = 10;
}

.Net is smart enough to pass object instances using address - not the whole object across the stack. In C++ land, the parameter should be passed as a pointer or explicit reference (using &).

Share this post: Email it! | bookmark it! | digg it! | reddit!
Published Wednesday, October 25, 2006 12:17 AM by Rob Garrett
Filed under:

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

 

Nathan said:

Perhaps the trickier gotcha is that if foo were a struct instead of a class, you would need to pass it by reference.
October 25, 2006 9:54 AM
 

Rob Garrett said:

Right of course, the surprising thing is the number of developers who do not know the difference between value types and reference types. Ask the same group of developers about boxing and you'll get a blank gaze.

October 25, 2006 10:20 AM

Leave a Comment

(required) 
(optional)
(required) 
Submit

Blurb


Head Shot
Rob Garrett is a British Expat living in Maryland USA. Rob is a trained software engineer and experienced in Windows .NET development.

Rob enjoys listening to Rock music, posting to blogs, driving in the country with the sunroof open, beer (not in conjunction with country driving) and spending time with his family.

This Blog

Syndication

Powered by Community Server, by Telligent Systems