2
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.Specialized;
using System.Configuration;

I am receiving this error

cannot declare instance members in a static class

when writing a Static class. Any idea how to solve it keeping the class static if possible? Thanks

namespace XXX.Helpers
{
    public static class Utility
    {
        public static string GetConfiguration(string section, string key)
        {
            NameValueCollection mySection = (NameValueCollection)ConfigurationManager.GetSection(section);

            return mySection[key];
        }
    }
}
4
  • Where are the instance members? Commented Jan 8, 2014 at 7:51
  • 1
    i tried using your code but it didn't gave me any error.. Commented Jan 8, 2014 at 7:51
  • 1
    Duplicate: cannot declare instance members in a static class in C# Commented Jan 8, 2014 at 7:51
  • I don't see any error in provide code Commented Jan 8, 2014 at 7:51

2 Answers 2

6

You can not define non-static members in a static class. It is not legal to declare an instance member in a static class.

From Static Classes and Static Class Members (C# Programming Guide)

The following list provides the main features of a static class:

  • Contains only static members.

  • Cannot be instantiated.

  • Is sealed.

  • Cannot contain Instance Constructors.

I have to say, I don't see any instance member in your static class by the way :)

Sign up to request clarification or add additional context in comments.

Comments

1

cannot declare instance members in a static class

The reason for this error is because -

Static class should only contains static members

2 Comments

The class doesn't have any members though. Just a static function. Static functions in return CAN have non-static members.
@Eisenhorn ah..you are right, I just jumped to answer with out cheking the code.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.