65.9K
CodeProject is changing. Read more.
Home

A C# idiom to simulate global functions

starIconemptyStarIconemptyStarIconemptyStarIconemptyStarIcon

1.00/5 (13 votes)

Sep 23, 2001

1 min read

viewsIcon

126730

downloadIcon

372

When what you really want is a global function.

Introduction

Recently I was working on a project using C# when I discovered I had several classes that needed to query the registry to return a string containing a path. The function was non-trivial, so a simple cut and paste would invite maintenance bugs. If I were working in C++, I would simply create a global function, and the classes could call that function. But C# doesn't allow for global functions. I considered:

class foo
{
	public GetString(){ //...
	}
}

then each class would do the following:

foo bar = new foo();
string WhatIReallyWant = bar.GetString();

but that involves creating a new variable, and I thought it was just plain ugly. Then I found a way to simulate having a global function without actually having one. Here is how you do it:

  • Create a class with a name of the "function" you want to call.
  • Give it a member variable of the type you want to return.
  • Create a constructor with the same arguments you want to pass in.  In this constructor, do what you want your function to do and assign the result to the variable you created above.
  • Overload the implicit cast operator for the type you want. Have it return the variable.

Then, in your code, preface the calls to this "function" with the new operator.

Here is the relevant code from the demo project. Here is a simple example that reverses a string: 

class reverser
{
	private string Data;
	public reverser(string toReverse)
	{
		for (int i=toReverse.Length-1; i>=0; i--)
		{
			Data += toReverse[i];
		}
	}

	public static implicit operator string(reverser r)
	{
		return r.Data;
	}
}

As you can see, the name of the "function" is reverser, the variable is named Data, it takes a string argument toReverse, and then we overload the cast to string operator. The casting operator is defined as implicit so we don't have to preface every call with a (string). Then you can call the "function" like this:

string foo = new reverser("foobar");

Which looks almost like a regular function call, except for the new operator.