I have created a public static class utils.cs I want to use it in other classes without prefixing method with utils, what's the syntax to do this ?
-
9Be aware, the Utils class is a common anti-pattern. – John Kraft Sep 14 '09 at 20:50
-
13And it's a common reality. I wind up with a Utils class in just about every project and I don't think there's anything wrong with putting functionality in there that would otherwise make for an awkward one-method instance class. – Josh Sep 15 '09 at 02:06
-
5@John Kraft: OOP is great for many things, but sometimes you actually do just need a global function and it doesn't make sense to group them all in one class. I really don't think that global functions are any different than creating a static class that contains a single function (or even a few unrelated function). Josh +1 – Ed S. Oct 16 '09 at 16:55
-
HtmlHelper in the ASP.NET MVC framework is a good example of this anti-pattern – Chris S Apr 20 '10 at 19:56
-
I think it depends how big the program is. – Nigiri Feb 04 '13 at 07:03
10 Answers
There's no way of doing this in C# - no direct equivalent of Java's static import feature, for example.
For more information about why this is the case, see Eric Lippert's post on the topic and a similar SO question.
In certain circumstances, however, it may make sense to write extension methods which live in non-nested static classes but "pretend" to be instance methods of a different class. It's worth thinking carefully before you introduce these, as they can be confusing - but they can also improve readability when used judiciously.
What sort of utility methods were you thinking of?
-
+1 It's hard not to like answers like this: provides the correct answer, has a link to a post proving it and explaining its history, and suggests an alternative solution. – Robert Harvey Sep 14 '09 at 20:52
-
1Well let's say I'm coding a Financial Math Lib, it seems daunting to me to always have to put MathLib in front of each Function whereas the context is MathLib nothing else. – programmernovice Sep 14 '09 at 22:14
-
1But only if you hack the type system and use reflection. I wouldn't count that as a global method call. – Matthew Whited Oct 16 '09 at 16:35
-
3In particular, it's not a global method call from the point of view of the *language itself*. The language just thinks you're calling an extension method on a string... that's really not the same as what was being asked for, IMO. – Jon Skeet Oct 16 '09 at 16:56
-
My answer is a functionally close approximation of what the OP is asking for (although I obviously don't recommend it - or even using top level methods at all for that matter). Global methods are supported by the CLR and it is possible to put together, using reflection, various ways of accessing them indirectly without too much of a hassle. That said, I grudgingly acknowledge that your answer is clearly the most practical and should be the selected answer. – Robert Venables Oct 17 '09 at 14:56
-
Could it be that either [static imports C# 6](https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-version-history#c-version-60) or the [global-modifier](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/using-directive#global-modifier) which was added in [C# 10 - see global-using-directives](https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-10#global-using-directives) allows this for a static clas? For example `global using static System.Math;` – surfmuggle Dec 21 '22 at 16:27
What Jon Skeet is not telling you is that you can have global static members in c#. Your utility class can indeed become a reality in c#.
Unfortunately, Microsoft has determined that the very process of constructing such members as above mere "normal" development, and requires that you forge them from raw intermediate language. Such a powerful pattern is above common syntax highlighting and friendly icons).
Here is the requisite sequence of utf-8 characters (guard it carefully):
.assembly globalmethods {}
.method static public void MyUtilMethod() il managed
{
ldstr "Behold, a global method!"
call void [mscorlib]System.Console::WriteLine(class System.String)
ret
}
(You could compile this example by invoking ilasm.exe from the SDK command prompt, remembering to use the /dll switch)
ilasm.exe output:
Microsoft (R) .NET Framework IL Assembler. Version 2.0.50727.4016 Copyright (c) Microsoft Corporation. All rights reserved. Assembling 'globalmethods.msil' to DLL --> 'globalmethods.dll' Source file is ANSI
global.msil(7) : warning -- Reference to undeclared extern assembly 'mscorlib'. Attempting autodetect
Assembled global method MyUtilMethod
Creating PE file
Emitting classes:
Emitting fields and methods: Global Methods: 1;
Emitting events and properties: Global Writing PE file Operation completed successfully
Once you have compiled your newly created assembly (as "globalmethods.dll" for example), it's just a matter of adding a reference in Visual Studio. When that is complete, you better be sitting down, because it will be time to write some real code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
namespace TestGlobalMethod
{
class Program
{
static void Main(string[] args)
{
"MyUtilMethod".Call();
Console.ReadKey();
}
}
/// <summary>
/// Reduces the amount of code for global call
/// </summary>
public static class GlobalExtensionMethods
{
public static void Call(this string GlobalMethodName)
{
Assembly.Load("globalmethods")
.GetLoadedModules()[0].GetMethod(GlobalMethodName)
.Invoke(null,null);
}
}
}
Yes, you just called a Global method in c#.
*Please don't use this, it's for example only :-) Also, you could probably write your global methods in another language that support them, such as VB.NET.

- 5,943
- 1
- 23
- 35
-
4Other than a level of pain there is no point in this if you have to call the .Call() extension method to reflect into the assembly to invoke your method. Just make the MathLib a static class and all of the methods into extension methods. (And as a bonus you get intellisence and type safety) – Matthew Whited Oct 16 '09 at 16:38
-
@Matthew Whited, using extension methods is unarguably the best solution in this case. My point was just to illustrate that global methods are fully supported by the CLR and are even accessible through languages that (deliberately) don't support them. – Robert Venables Oct 17 '09 at 14:31
-
You're clearly cheating, you are calling a global function using reflection, and not C# method call syntax ;) – Pop Catalin Apr 19 '10 at 22:59
-
1You could call your class "Call", wouldn't that use the same amount letters? – Chris S Apr 20 '10 at 19:54
-
1
With C# 6, you can now use static imports (see msdn) For example,
using static Utils;

- 828
- 1
- 11
- 19
As a minimum, you have to specify at least the class name. All the using directive does is allow you to leave off the namespace. You can also use the using directive to specify an alias Instead of the entire namespace.class name, but then you have to use the alias...
using MyClassName = Namespace.MySubNS.OtherNameSpace.OriginalClassname;
MyClassName X = new MyClassName();

- 143,358
- 22
- 150
- 216
-
1Tiny correction: you're talking about using directives, not using statements. – Jon Skeet Sep 14 '09 at 20:47
I suppose you could make all of your methods in utils.cs as extension methods to the object class, but you'd still have to prefix your methods with "this.", which is probably not what you want.

- 11,097
- 6
- 35
- 36
The "proper" (from an OO point of view of bringing a member into scope, is to IMPLEMENT it within the scope:
static class MySpecialStuff
{
public static int MySpecialValue { get {...} }
}
class MyWorkingClass
{
private static int MySpecialValue { get { return ySpecialStuff.MySpecialValue; } }
}
Now in the remainder of MyWorkingClass
(or in derived classes if you change the private to protected) you can reference MySpecialValue
thousands of times without any additional qualifications.

- 222,467
- 53
- 283
- 367

- 344
- 1
- 10
-
Excellent. This way proved suitable for one of my projects where I am translating a massive stack of Classic ASP code into VB.net. I already have the static classes re-written, but require a way to access the methods "shorthand" in a Page class derived from Web.UI.Page to avoid too much re-writing of the Classic VBScript. – Awerealis Apr 11 '14 at 06:24
I'm not sure what you're trying to accomplish by omitting the Utils
prefix from the method calls. But if it's just to save space or make the code a little easier to read, you could alias the import to a shorter name:
using U = Utils;

- 11,918
- 5
- 42
- 52
I have never really cared for the "global method" concept. Additionally, it seems that it makes much more readable / maintainable code to not have classes called 'Util' that contain helper methods of any type. Instead something like MathLib which at least documents what kind of method is being operated on.
In the case of a financial library I could kind of see it where you may not want to always have to do MathLib.Sum() or whatever. Maybe you could introduce operator overloading to your types so that you could perform calculations on them with more simplified syntax when manipulating business your business objects?
I may be a little biased(grumpy) after reading VB6 code over the last few weeks where global methods are all over the place. That being said this is just my two cents :)

- 3,341
- 1
- 20
- 20
In this thread there are some questioning and argumenation about not using global methods, but I would like to add that there is another kind of scenario when static imports are desirable, i.e. when you want to bring some constants into scope. For example, if I want to construct SQL statements, I would prefer to not use duplicated string literals, as in this code example (using dynasql):
DBQuery.Select()
.Field("CustomerID")
.Count("OrderID")
.From("Orders")
.GroupBy("CustomerID")
.OrderBy("CustomerID")
.WhereField("OrderDate", Compare.GreaterThan, DBConst.DateTime(ordersAfter))
I would prefer doing this:
public class OrderTable {
public const string Orders = "Orders";
public const string CustomerID = "CustomerID";
public const string OrderID = "OrderID";
public const string OrderDate = "OrderDate";
}
...
DBQuery.Select()
.Field(OrderTable.CustomerID)
.Count(OrderTable.OrderID)
.From(OrderTable.Orders)
.GroupBy(OrderTable.CustomerID)
.OrderBy(OrderTable.CustomerID)
.WhereField(OrderTable.OrderDate, Compare.GreaterThan, DBConst.DateTime(ordersAfter))
If I would be using the suggestion by Loadmaster (Oct 16 at 16:49) then I could do this:
using O = TestingDynasql.OrderTable;
...
DBQuery.Select()
.Field(O.CustomerID)
.Count(O.OrderID)
.From(O.Orders)
.GroupBy(O.CustomerID)
.OrderBy(O.CustomerID)
.WhereField(O.OrderDate, Compare.GreaterThan, DBConst.DateTime(ordersAfter))
However, I would prefer to bring the constant into scope without any repeated but needed name and dot qualifer at all (as you can do with Java's static imports) i.e. do this:
DBQuery.Select()
.Field(CustomerID)
.Count(OrderID)
.From(Orders)
.GroupBy(CustomerID)
.OrderBy(CustomerID)
.WhereField(OrderDate, Compare.GreaterThan, DBConst.DateTime(ordersAfter))
But it is not possible to use this kind of syntax with C# ?
By the way, does anyone know of a better .NET library for creating SQL than dynasql, which does not seem to be designed for being independent of the SQL execution (as the problem described here: http://dynasql.codeplex.com/Thread/View.aspx?ThreadId=81988) ?
/ Sven

- 511
- 5
- 14
How to avoid class prefix when using a method defined in another class
Declare a new class member "VerifyNoXMovementBetweenCommands" by using the method (with the same name) defined in another class "CollisionControlUtils.cs":
using namespaceOf.CollisionControlUtils;
public class example
{
private static bool VerifyNoXMovementBetweenCommands(
string firstCommand,
string followingCommand,
IReadOnlyList<string> sentMessages) =>
CollisionControlUtils.VerifyNoXMovementBetweenCommands(
firstCommand,
followingCommand,
sentMessages);
var result = VerifyNoXMovementBetweenCommands(...);
}
class "CollisionControlUtils.cs":
internal static class CollisionControlUtils
{
public static bool VerifyNoXMovementBetweenCommands(
string firstCommand,
string followingCommand,
IReadOnlyList<string> sentMessages)
{
var indexFirstCommandPlusOne = GetTracedCommandIndex(
sentMessages, firstCommand) + 1;
var indexFollowingCommand = GetTracedCommandIndex(
sentMessages, followingCommand);
var relevantTraces = sentMessages
.ToArray()[indexFirstCommandPlusOne..indexFollowingCommand];
return !relevantTraces.Any(m => Regex.IsMatch(m, "(xp|xa)"));
}
}

- 1
- 1