Ken Kopczyk

Hurdles in .NET Development

Archive for the ‘Programming Languages’ Category

Fun With the “ref” Keyword

Posted by Ken on February 3, 2009

By default, parameters are passed by value in C#.  Passing by reference requires the “ref” or “out” keywords to precede the parameter in both the method declaration and the call to the method.  Using “ref” or “out” is fairly straight forward…..or so I thought.

I recently came across two cases where parameters are valid if passing by value, but result in compilation errors after adding “ref”. Consider the following member and method:

// SuperDataTable inherits from DataTable
// Indexing a SuperDataTable yields a SuperDataRow 
// which inherits from DataRow.
private SuperDataTable mySuperDataTable = new SuperDataTable();

public void DoSomethingSuper(ref DataRow myDataRow)

Now examine the following three scenarios:

// #1 You receive a compiler error "A property or indexer 
// may not be passed as an out or ref parameter"
DoSomethingSuper(ref mySuperDataTable[0]);

// #2 You receive a compiler error "Cannot convert from 
// 'ref SuperDataRow' to 'ref DataRow'
SuperDataRow mySuperDataRow = mySuperDataTable[0];
DoSomethingSuper(ref mySuperDataRow);

// #3 Only does it work in the following manner, when you 
// explicitly "upcast" the row to the exact type in the 
// signature of the method
DataRow myDataRow = mySuperDataTable[0];
DoSomethingSuper(ref myDataRow);

Try it again, this time passing by value. No compiler errors! I probably am just lacking an intimate understanding of “ref”, but this came out of left field for me and I haven’t seen it documented online. Can anybody fill me in as to why scenarios #1 and #2 don’t work?

Bookmark and Share

Posted in Programming Languages | Tagged: | 4 Comments »