5

After building my first big project using C# i ran into a problem. My project file is about 7000 lines big atm and fillde with functions and other classes. This is ofcourse a little messy and to find the code that i actually need i sometimes need to scroll around quite a bit so i want to remove all the classes and functions to a different file. I know i can just add a c# class file and then access it by doing

    namespace Namespace
{
    class Functions
    {
        // Example Functions here
    }
}

    namespace OtherNamespace
{
    class OtherClass
    {
        Namespace.Functions.Examplefunction
    }
}

If the example function would actually exist that is. But i would like to get rid of the Namespace.Functions part as it would save me alot of typing and i use these functions often. How would i do that ? Is it even possible?

I know it is achievable in python like this

import math as *

for example, then you wouldnt have to write

math.cos(0)

but instead you can just write

cos(0)
2
  • 5
    You can just add using Namespace; to your other code files. If you're using C# 6 or later you can use using static Namespace.Functions; and then you don't have to reference 'Functions' - see the docs for more - note that using static imports only accessible static members and nested types declared in the specified type
    – stuartd
    Commented Feb 29, 2020 at 20:25
  • 1
    @stuartd thanks for the reply, i know it was a stupid question but i couldnt figure it out... but thanks that fixes it indeed! Commented Feb 29, 2020 at 20:30

1 Answer 1

5

You can use a static import feature of C# if you want to use many static helper functions. I've provided a basic example. You can use this for standard .NET framework classes such as System.Math, System.Console etc.

namespace Utils 
{
    // using static
    using static Utils.Helper;

    public class Program
    {
        public static void Main()
        {
            // no need to type Helper.Pow(2, 2);
            var x = Pow(2, 2);

            Console.WriteLine(x);
        }
    }
}

namespace Utils
{
    public static class Helper
    {
        public static double Pow(int x, int pow) => Math.Pow(x, pow);
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.