Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

A C# idiom to simulate global functions

0.00/5 (No votes)
22 Sep 2001 1  
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.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here