Undocumented C# Types and Keywords
By Peter A. Bromberg, Ph.D.
Printer - Friendly Version
Peter Bromberg

The C# language has a few interesting and undocumented (or in some cases, poorly so) Types and Keywords. One interesting set that I came across recently is the TypedReference type. This represents data by containing both a reference to its location in memory as well as a runtime representation of the type of the data.

Only local variables and parameters can be of the TypedReference type - fields cannot be. The TypedReference type, as you would guess from the above description, is not CLS complaint and the undocumented keywords that go with it appear nowhere in the ECMA C# Specification.

__makeref : You can create a typed reference from a variable by using the __makeref keyword:

int i = 21;
TypedReference tr = __makeref(i);

The original type of the variable represented by the typed reference can be extracted using the __reftype keyword:

int i = 32;
TypedReference tr1=__makeref(i);
Type t= __reftype(tr1);
Response.Write( t.ToString());

__refvalue:   Lastly, the value can be extracted from the TypedReference using the __refvalue kyeword:

int q = __refvalue(tr, int);

Typed references come in handy when you want to represent method arguments in variable argument lists (varargs). These argument lists (in a manner similar to the params keyword) can be passed into methods and accessed with the also undocumented __arglist keyword:

<script runat="server" language="C#">
protected void Page_Load(Object sender, EventArgs e)
	{
		int x=85;
		string y = "a stringy thingy";
		double d=19.45; 
		WriteToPage(__arglist(x,y,d));
	}
public  void WriteToPage(__arglist)
{
	ArgIterator ai = new ArgIterator(__arglist);
	while(ai.GetRemainingCount() >0)
	{
		  TypedReference tr = ai.GetNextArg();
		  Response.Write(TypedReference.ToObject(tr)+"<BR>");
	}
}
</script>

Curious users should note that since the above code examples use undocumented keywords, they aren't guaranteed to work in future versions of C#. The params keyword is, of course documented and you can accomplish a similar task using it. I found at least one tech-talk sponsored by Microsoft where a user asked about whether MS planned to document any of these. The answer was "Why should we?". Go figure.

 

 

 


Peter Bromberg is a C# MVP, MCP, and .NET consultant who has worked in the banking and financial industry for 20 years. He has architected and developed web - based corporate distributed application solutions since 1995, and focuses exclusively on the .NET Platform.