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");
}
}

difference between Constant And Readonly

What is the difference between constant and readonly?

'const':
Can't be static.
Value is evaluated at compile time.
Initiailized at declaration only.

'readonly':
Can be either instance-level or static.
Value is evaluated at run time.
Can be initialized in declaration or by code in the constructor.

You can't use the static keyword with a const because it would be redundant. You can think of const as a subset of static.

Consts are static, not instance members.

public class Constant
{
public const int C = 12345;
}

------------
public class ReadOnly
{
private readonly int r = 1; //variable initialization upon declaration is possible for readonly variables

public ReadOnly()
{
r = 2; //assignment to a readonly variable is possible in the constructor
}

public int R
{
get { return r; }
set { r = value; } //this line won't compile because r is declared a readonly
}
}