Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use static function from a class without naming the class

How can I access functions from a class without having to name that class every time? I know how to use "using" so that I don't have to name the namespace but I was hoping there was a way to do with this static functions so that I can call them the way I would call a function in the same class.

like image 324
Stoopkid Avatar asked Jun 24 '14 02:06

Stoopkid


People also ask

Can we call static method without class name?

Static methods can be called directly - without creating an instance of the class first.

Can we call static method without class name in C#?

Static methods can be called without creating an object. You cannot call static methods using an object of the non-static class. The static methods can only call other static methods and access static members. You cannot access non-static members of the class in the static methods.

Can we call the static method without creating object?

Static methods are the methods in Java that can be called without creating an object of class. They are referenced by the class name itself or reference to the Object of that class.

How do you call a static method from a class?

Qualifying a static call A static method is called by prefixing it with a class name, eg, Math. max(i,j); . Curiously, it can also be qualified with an object, which will be ignored, but the class of the object will be used.


2 Answers

using static yournamespace.yourclassname;

then call the static class method without class name;

Example:

Class1.cs

namespace WindowsFormsApplication1
{
    class Utils
    {
        public static void Hello()
        {
            System.Diagnostics.Debug.WriteLine("Hello world!");
        }
    }
}

Form1.cs

using System.Windows.Forms;
using static WindowsFormsApplication1.Utils;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {

        public Form1()
        {
            InitializeComponent();
            Hello();    // <====== LOOK HERE
        }
    }
}
like image 79
untitled Avatar answered Oct 25 '22 15:10

untitled


I routinely have

static Action<object> o = s => Console.WriteLine(s);

in my code which makes debug output so much less noisy. That way I can call Console's static Writeline() much easier. Would that help?

like image 35
Peter - Reinstate Monica Avatar answered Oct 25 '22 15:10

Peter - Reinstate Monica