Tuesday, October 20, 2009

C# Pass By Reference

C# like Java passes parameters by value for value types and reference for reference types. However, you can override pass-by-value in C# for value types using the ref and out keywords. The difference between the two is that out does not require the parameter to have been initialized before being passed to your method.

Sample:

public void assignToRefForValueType(ref int refValType, out int outValType) {
refValType = 2;
outValType = 4;
}

public void testAssignToRefForValueType() {
int valueType = 0;
int outValueType;
assignToRefForValueType(valueType, outValueType);

//Prints 2, 4
System.Console.WriteLine("New values for ref and out: {0}, {1}",
valueType, outValueType);
}

Tuesday, October 6, 2009

Case Statement Superiority

C# allows you to switch on enums and strings in addition to the types supported by Java (char, int)!

Unlike Java, you have to explicitly specify fall-through if you have any logic in your statement.

Sample Java:
switch(myInt)
{
case 1:
callSomething();
case 2:
//this will still be executed for case one
callSomethingElse();
}

Equivalent C# Code:
switch(myInt)
{
case 1:
callSomething();
goto case 2;
case 2:
callSomethingElse();
}