Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to reference a method in a static class without referencing the class?

Tags:

c#

.net

asp.net

Is there a way to declare a static method within a class/namespace hierarchy such that the method can be addressed directly without having the refer to its classname? For example if I have this namespace and class...

namespace UsefulMethods
{
    public static class DataBaseStuff
    {
        public static DataTable GetDataTable(String command, SqlConnection conn)
        {
            dt = new DataTable();
            dostuff...
            return dt;
        }
    }
}

then I write some code that uses this class and I put statement...

using UsefulMethods;

...at the top of my code, I can get a DataTable returned to me by...

DataTable myDataTable = DataBaseStuff.GetDataTable(command, conn);

I thought maybe I could refer to a static class with a using statement as well like...

using UsefulMethods.DataBaseStuff;

...so that I could just refer to the method without the class name like this...

DataTable myDataTable = GetDataTable(command, conn);

...but this doesn't seem to work. The intellisense doesn't find the static class in the using statement, so I guess that just works for namespaces. So, is there some way for me to have my code to know what static class I'm referring to without referencing it every time I call one of the static methods?

Thank you for reading.

like image 881
Camenwolf Avatar asked Jan 18 '26 06:01

Camenwolf


1 Answers

With C# 6.0 you can do that with static import

using static UsefulMethods.DataBaseStuff;

Until then you can't. You have to use class name with static method.

See: New Language Features in C# 6

Using static

The feature allows all the accessible static members of a type to be imported, making them available without qualification in subsequent code:

using static System.Console;
using static System.Math;
using static System.DayOfWeek;
class Program
{
    static void Main()
    {
        WriteLine(Sqrt(3*3 + 4*4)); 
        WriteLine(Friday - Monday); 
    }
}

This is great for when you have a set of functions related to a certain domain that you use all the time. System.Math would be a common example of that. It also lets you directly specify the individual named values of an enum type, like the System.DayOfWeek members above.

like image 73
Habib Avatar answered Jan 19 '26 18:01

Habib



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!