简体   繁体   中英

Does a C# static class need to be instantiated?

I am a new .NET developer. I would like to know whether a static class in C# needs to be instantiated? I created a class for a database connection:

public static class ConnectionHelper
{
    public static SqlConnection GetConnection()
    {
        return new SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ToString());
    }
}

I am instantiating this class in my C# application and getting the following error:

The name 'ConnectionHelper' does not exists in the current context

The related code:

using (var cn = ConnectionHelper.GetConnection())
{
    ...
}

Please advise.

No, a static class does not need to be instantiated. It cannot be instantiated, that's the point of the static keyword in class declaration.

You are not instantiating it, either. What you do is call a static method from a static class. And that's fine. But instantiating a class requires the new keyword.

You are probably missing a using -directive at the top of your file to make it compile.

I think you're missing a namespace.

Add the namespace of your ConnectionHelper to your "using"-block. For example:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ConnectionHelperNamespace;

If your static class defined in separate project, then add refernce to it in Project Explorer: http://msdn.microsoft.com/en-us/library/wkze6zky(v=vs.80).aspx and after that add the namespace to "using"-block.

You can try this by removing the satic in "public static class":

public class ConnectionHelper
{
    public static SqlConnection GetConnection()
    {
        return new SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ToString());
    }
}

It will work, but before being added some non-static attributes or methods, the instance can do nothing.

Classes create stateful objects - on which we perform various operations. For this we have to declare and instantiate objects.

static classes / methods are meant to be stateless. Mostly we just want static methods to receive certain parameters , perform operation and return values / status .

They are not supposed to store any intermediate results for which we need class data members.

So, simply-put, static class is not instantiated!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM