C# Tutorials and offshore development in India
    Tutorials   Resources   Forum   Communities   Interview   Jobs   Projects   Offshore Development    
Silverlight Tutorials | Mentor | Code Converter | Articles | Code Factory | Computer Jokes | Members | Peer Appraisal | IT Companies | Bookmarks | Revenue Sharing |


Prizes & Awards
My Profile



Active Members
TodayLast 7 Days more...

New Feature: Community Sites: Create your own .NET community website and start earning from Google AdSense ! It's Free !




Understanding concept of "ref" and "out" keyword in Dot Net


Posted Date: 02 Aug 2006    Resource Type: Articles    Category: .NET Framework
Author: DotNetGuts (DNG)Member Level: Diamond    
Rating: Points: 10



ref keyword


Passing variables by value is the default. However, we can force the value parameter to be passed by reference. Note: variable “must” be initialized before it is passed into a method.

Eg: Without Using ref keyword



class Test
{
public static void Main()
{
int a = 3;
DoWork(a);
Console.WriteLine("The value of a is " + a);
}

public static void DoWork(int i)
{
i++;
}
}
The program will result in : The value of a is 3



With the Use of ref keyword



class Test
{
public static void Main()
{
int a = 3; // must be initialized
DoWork(ref a); // note ref
Console.WriteLine("The value of a is " + a);
}

public static void DoWork(ref int i) // note ref
{
i++;
}
}
The program will result : The value of a is 4




out keyword


out keyword is used for passing a variable for output purpose. It has same concept as ref keyword, but passing a ref parameter needs variable to be initialized while out parameter is passed without initialized.
It is useful when we want to return more than one value from the method.

Note: You must assigned value to out parameter in method body, otherwise the method won’t compiled.

Eg:

class Test
{
public static void Main()
{
int a; // may be left un-initialized
DoWork(out a); // note out
Console.WriteLine("The value of a is " + a);
}

public static void DoWork(out int i) // note out
{
i=4;
}
}

The program will result : The value of a is 4


--

DotNet Guts


"Lets Make Programming Easy"



Logon to DotNetGuts.2ya.com




Join us @ DotNetGuts@YahooGroups.com








Responses


No responses found. Be the first to respond and make money from revenue sharing program.

Feedbacks      
Popular Tags   What are tags ?   Search Tags  
(No tags found.)

Post Feedback


This is a strictly moderated forum. Only approved messages will appear in the site. Please use 'Spell Check' in Google toolbar before you submit.
You must Sign In to post a response.
Next Resource: Improving scalability by making Asynchronous Requests
Previous Resource: Abstract Class Concept
Return to Discussion Resource Index
Post New Resource
Category: .NET Framework


Post resources and earn money!
 
Related Resources



dotNet Slackers   BizTalk Adaptors    Web Design


Contact Us    Privacy Policy    Terms Of Use