Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to "import" a static class in C#?

Tags:

c#

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 ?

like image 289
programmernovice Avatar asked Sep 14 '09 20:09

programmernovice


People also ask

How do you import a static variable?

In Java, static import concept is introduced in 1.5 version. With the help of static import, we can access the static members of a class directly without class name or any object. For Example: we always use sqrt() method of Math class by using Math class i.e. Math.

What is static import in C#?

This modifier was introduced in C# 10. The static modifier imports the static members and nested types from a single type rather than importing all the types in a namespace. This modifier was introduced in C# 6.0.

How do you declare a static class?

We can declare a class static by using the static keyword. A class can be declared static only if it is a nested class. It does not require any reference of the outer class. The property of the static class is that it does not allows us to access the non-static members of the outer class.


6 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?

like image 55
Jon Skeet Avatar answered Oct 05 '22 23:10

Jon Skeet


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.

like image 45
Robert Venables Avatar answered Oct 05 '22 23:10

Robert Venables


With C# 6, you can now use static imports (see msdn) For example,

using static Utils;
like image 32
Frank Ibem Avatar answered Oct 05 '22 23:10

Frank Ibem


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(); 
like image 38
Charles Bretana Avatar answered Oct 06 '22 00:10

Charles Bretana


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.

like image 25
Tinister Avatar answered Oct 06 '22 01:10

Tinister


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.

like image 40
David V. Corbin Avatar answered Oct 06 '22 01:10

David V. Corbin