CodeGuru
Earthweb Search
Forums Wireless Jars Gamelan Developer.com
CodeGuru Navigation
Member Sign In
User ID:
Password:
Remember Me:
Forgot Password?
Not a member?
Click here for more information and to register.

jobs.internet.com

internet.commerce
Partners & Affiliates
Shop
Baby Photo Contest
Compare Prices
Promote Your Website
Rackmount LCD Monitor
Career Education
Boat Donations
GPS Devices
Dental Insurance
Domain registration
Best Price
Televisions
Build a Server Rack
Calling Cards


RSS Feeds

RSSAll

RSSVC++/C++

RSS.NET/C#

RSSVB

See more EarthWeb Network feeds

Home >> .NET / C# >> C# >> Miscellaneous >> Design/Techniques

Project Management Guide: Developing a Web Site. Best Practices, Tips and Strategies. Download Exclusive eBook Now.

.NET Tip: Returning Mulitple Objects from a Single Method Call
Rating:

Jay Miller (view profile)
April 24, 2008

Each method can only return a single value from the method call. What happens when you need to return more information? One solution is for your method to return a complex data type. It could return a struct or an object of a class you define. In many situations this makes sense, especially when you want to return a set of related data. In other instances, however, a complex data type may not really fit what you need or may be overly complex. Another option is to return values through the parameters to the method. By default, parameters are passed by value; this means that your method is not able to change the value of the parameter and pass it back to the calling routine. C# has a couple keywords that you can use to change the behavior of how parameters are passed. You can use the ref keyword to indicate that the parameter will be passed by value. This allows your method to modify the value of the parameter and have the calling routine see that change when your method finishes executing. The ref keyword should appear in your method's parameter list before the data type of each parameter that you want to pass by reference. Here is a method that can accept some parameters by reference.

private bool RefParameters(int Input, ref int Output,
                           ref string Message)
{
   Output = Input * 10;
   Message = "Your input value was: " + Input.ToString();
   return true;
}

(continued)



Web Devs:
Moonlight as a Game Developer and Win Cool Prizes by Accepting the RIA Run Challenge

Now, your mission--should you choose to accept: Take your shot at gaming stardom if you think you might have what it takes to build a cool RIA game and you could win an Xbox 360 or other fabulous prizes. Hurry! You only have until May 15, 2008 to enter. »

 
Article:
Leveraging Your Flash Development with Silverlight

You're not giving up Flash any time soon (and we don't blame you.) But if you could get your Flash application working in Silverlight, why wouldn't you? We show you the tools and techniques required to have your rockin' Flash application rolled for Silverlight. Learn more here. »

 
Article:
What Does it Take to Build the Best RIA?

With the proliferation of Rich Interactive Application (RIA) platform choices out there, you no longer have to take a one-size-fits-all approach to developing your next RIA application. Knowing the strengths (and weaknesses) of each platform can help you to decide the best RIA for your next application. »

 

First, notice that this method has a boolean return value. The method call itself will always return a true value. Second, the method expects three parameters. The first parameter is an integer that is passed by value so it cannot be changed by the method. The next two parameters are an integer and string that are each passed by reference. Because both these parameters have the ref keyword, they can be modified during the execution of the method and any changes will be reflected back in the calling routine. The body of the method should be strightforward. It assigns new values to the Output and Message parameters before returning true from the method call. Here is an example of calling the above method.

bool ReturnValue    = false;
int IntInput        = 5;
int IntOutput       = 1;
string StringOutput = "Initial Text";

Debug.Print(String.Format("Initial Values:\r\nReturnValue:
   {0}\r\nIntInput:
   {1}\r\nIntOutput:
   {2}\r\nStringOutput:
   {3}\r\n", ReturnValue, IntInput, IntOutput, StringOutput));
ReturnValue = RefParameters(IntInput, ref IntOutput,
                            ref StringOutput);
Debug.Print(String.Format("New Values:\r\nReturnValue:
   {0}\r\nIntInput:
   {1}\r\nIntOutput:
   {2}\r\nStringOutput:
   {3}\r\n", ReturnValue, IntInput, IntOutput, StringOutput));

A variable to hold the return value of the method is declared and initialized as well as variables to hold the input and output parameters to the method. The call to the method has Debug statements before and after it to print out the values of all the variables. One point to notice is that the ref keyword also must precede all ref parameters in the method call itself. Your code will not compile if you forget to include the ref keyword on a call to a method that has ref paremeters. You can see from the following output that the value of the IntOutput and StringOutput variable have changed after the method call.

Initial Values:
ReturnValue:  False
IntInput:     5
IntOutput:    1
StringOutput: Initial Text

New Values:
ReturnValue:  True
IntInput:     5
IntOutput:    50
StringOutput: Your input value was: 5

If you look at the example calling code, you will notice that the variables passed in as ref parameters have been intialized when they were delcared. The ref keyword requires that any variable passed as a ref parameter be initialized before the method call. As an alternative, you can use the out keyword in the method declaration and method call instead of ref. Parameters that use the out keyword are not required to be initialized before the method call. Other than the initialization requirement, the out and ref keywords have the same behavior.

About the Author

Jay Miller is a Software Engineer with Electronic Tracking Systems, a company dedicated to robbery prevention, apprehension, and recovery based in Carrollton, Texas. Jay has been working with .NET since the release of the first beta and is co-author of Learn Microsoft Visual Basic.Net In a Weekend. Jay can be reached via email at jmiller@sm-ets.com.

Tools:
Add www.codeguru.com to your favorites
Add www.codeguru.com to your browser search box
IE 7 | Firefox 2.0 | Firefox 1.5.x
Receive news via our XML/RSS feed

Work With InterSystems. Not Separate Systems. Rapidly develop and deploy connectable applications.
Guide to Developing a Web Site. Best Practices, Tips and Strategies. Download Exclusive eBook Now.
Developing Intelligent Communications? Visit the Avaya DevConnect Center on DevX.
Flash Demo: Learn how IBM Information Server Blade is easy to manage, highly scalable and efficient.
Whitepaper: XML Processing in Applications--Take the Next Step


RATE THIS ARTICLE:   Excellent  Very Good  Average  Below Average  Poor  

(You must be signed in to rank an article. Not a member? Click here to register)

Latest Comments:
No passing by value takes place - cjard (04/29/2008)

View All Comments
Add a Comment:
Title:
Comment:
Pre-Formatted: Check this if you want the text to display with the formatting as typed (good for source code)



(You must be signed in to comment on an article. Not a member? Click here to register)


JupiterOnlineMedia

internet.comearthweb.comDevx.commediabistro.comGraphics.com

Search:

Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

Jupitermedia Corporate Info


Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

Solutions
Whitepapers and eBooks
Microsoft Article: HyperV-The Killer Feature in WinServer ‘08
Avaya Article: How to Feed Data into the Avaya Event Processor
Microsoft Article: Install What You Need with Win Server ‘08
HP eBook: Putting the Green into IT
Whitepaper: HP Integrated Citrix XenServer for HP ProLiant Servers
Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 1
Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 2--The Future of Concurrency
Avaya Article: Setting Up a SIP A/S Development Environment
IBM Article: How Cool Is Your Data Center?
Microsoft Article: Managing Virtual Machines with Microsoft System Center
HP eBook: Storage Networking , Part 1
Microsoft Article: Solving Data Center Complexity with Microsoft System Center Configuration Manager 2007
MORE WHITEPAPERS, EBOOKS, AND ARTICLES
Webcasts
Intel Video: Are Multi-core Processors Here to Stay?
On-Demand Webcast: Five Virtualization Trends to Watch
HP Video: Page Cost Calculator
Intel Video: APIs for Parallel Programming
HP Webcast: Storage Is Changing Fast - Be Ready or Be Left Behind
Microsoft Silverlight Video: Creating Fading Controls with Expression Design and Expression Blend 2
MORE WEBCASTS, PODCASTS, AND VIDEOS
Downloads and eKits
Sun Download: Solaris 8 Migration Assistant
Sybase Download: SQL Anywhere Developer Edition
Red Gate Download: SQL Backup Pro and free DBA Best Practices eBook
Red Gate Download: SQL Compare Pro 6
Iron Speed Designer Application Generator
MORE DOWNLOADS, EKITS, AND FREE TRIALS
Tutorials and Demos
How-to-Article: Preparing for Hyper-Threading Technology and Dual Core Technology
eTouch PDF: Conquering the Tyranny of E-Mail and Word Processors
IBM Article: Collaborating in the High-Performance Workplace
HP Demo: StorageWorks EVA4400
Intel Featured Algorhythm: Intel Threading Building Blocks--The Pipeline Class
Microsoft How-to Article: Get Going with Silverlight and Windows Live
MORE TUTORIALS, DEMOS AND STEP-BY-STEP GUIDES