Search This Blog

2009-09-07

Difference between ref and out

The out keyword causes arguments to be passed by reference. This is similar to the ref keyword, except that ref requires that the variable be initialized before being passed.
you can not use the out paramter to pass a value to the method. With ref you can.
Example:

class OutExample
{

static void SplitName(string fullName, out string firstName, out string lastName)
{
// NOTE: firstName and lastName have not been assigned to yet. Their values cannot be used.
int spaceIndex = fullName.IndexOf(' ');
firstName = fullName.Substring(0, spaceIndex).Trim();
lastName = fullName.Substring(spaceIndex).Trim();
}

static void Main()
{
string fullName = "Yuan Sha";
string firstName;
string lastName;

// NOTE: firstName and lastName have not been assigned yet. Their values may not be used.
SplitName(fullName, out firstName, out lastName);
// NOTE: firstName and lastName have been assigned, because the out parameter passing mode guarantees it.

System.Console.WriteLine("First Name '{0}'. Last Name '{1}'", firstName, lastName);
}
}


//------------------------------
class RefExample
{
static object FindNext(object value, object[] data, ref int index)
{
while (index < data.Length)
{
if (data[index].Equals(value))
{
return data[index];
}
index += 1;
}
return null;
}

static void Main()
{
object[] data = new object[] {1,2,3,4,2,3,4,5,3};

int index = 0;
// NOTE: must assign to index before passing it as a ref parameter
while (FindNext(3, data, ref index) != null)
{
// NOTE: that FindNext may have modified the value of index
System.Console.WriteLine("Found at index {0}", index);
index += 1;
}

System.Console.WriteLine("Done Find");
}
}

No comments: