August 22, 2008

The ref and out Keywords in C#

In C# all value type parameters (objects that inherit from System.ValueType) are allocated to the stack and passed by value. This means that a copy of these variables is created and passed into the method being called. Since the parameter is a local copy its scope is limited to that method. See the following example below:
protected void Sample()
{
int x = 5;
//Writes 5 to the console
Console.WriteLine(x.ToString());
//Send a copy of x
Increment(x);
//Writes 5 to the console
Console.WriteLine(x.ToString());
}

protected void Increment(int incoming)
{
incoming++;
}
Note that the variable x is not changed by the Increment method. In most cases this behavior is desired. However, there are occasions when we may want to persist changes to a value type parameter beyond the scope of the method. This is where the ref and out keywords come into play. Here's our sample again but with the ref keyword used in the Increment method:
protected void Sample()
{
int x = 5;
//Writes 5 to the console
Console.WriteLine(x.ToString());
//Send a reference of x
Increment(ref x);
//Writes 6 to the console
Console.WriteLine(x.ToString());
}

protected void Increment(ref int incoming)
{
incoming++;
}
Note that this time around x is 6 after the Increment method is executed.

The ref and out keywords operate identically except that ref parameters must be initialized before being passed into the method while out parameters must be initialized by the time the method returns.

August 09, 2008

SQL Server 2005 Finicky with Nested Comments

I found out the hard way that MS SQL Server 2005 is sometimes finicky about nested comments leading up to CREATE PROCEDURE or ALTER PROCEDURE lines. Here's a simple illustration of this phenomenon:

/*
/*Bad comment line*/2
*/
CREATE PROCEDURE [dbo].[GetProduct]
AS

SELECT * FROM Product
This code executes without error...but everything grinds to a halt when you try to modify or script it. Management Studio reports a Syntax error in TextHeader.

I ran into this behavior after working an hour on a fairly complex sproc. I didn't back up my work before I ran it, assuming I could always pull it out of the database to make tweaks if necessary. Needless to say I was miffed to find that I couldn't open the stored procedure and effectively lost my work.

Thankfully, it's possible to retrieve code that's lost in this manner:

SELECT
ROUTINE_DEFINITION
FROM INFORMATION_SCHEMA.Routines
WHERE
ROUTINE_Name = 'GetProduct'