Friday, October 19, 2007

Method Parameters in C# (2)

Using out with value types:


public sealed class Program

{

public static void Main()

{

Int32 x; // x is uninitialized

GetVal(out x); // x doesn't have to be initialized.

Console.WriteLine(x); // Displays "10"

}

private static void GetVal(out Int32 v)

{

v = 10; // This method must initialize v.

}

}


Using ref with value types:



public sealed class Program

{

public static void Main()

{

Int32 x = 5; // x is initialized

AddVal(ref x); // x must be initialized.

Console.WriteLine(x); // Displays "15"

Console.ReadLine();

}

private static void AddVal(ref Int32 v)

{

v += 10; // This method can use the initialized value in v.

}

}

blog comments powered by Disqus