Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't define static abstract string property

Tags:

c#

.net

I've run into an interesting problem and am looking for some suggestions on how best to handle this...

I have an abstract class that contains a static method that accepts a static string that I would like to define as an abstract property. Problem is that C# doesn't doesn't support the following (see the ConfigurationSectionName and Current properties):

    public abstract class ProviderConfiguration : ConfigurationSection
    {
        private const string _defaultProviderPropertyName = "defaultProvider";
        private const string _providersPropertyName = "providers";

        protected static string ConfigurationSectionName { get; }

        public static Configuration Current
        {
            get { return Configuration)ConfigurationManager.GetSection(ConfigurationSectionName); }
        }
    }

I suppose one way to handle this would be to make ConfigurationSectionName NOT abstract and then create a new definition of ConfigurationSectionName in the derived classes, but that feels pretty hackish. Any suggestions would be most welcome.

Gratias!!!

like image 721
goombaloon Avatar asked Dec 31 '10 01:12

goombaloon


People also ask

Why an abstract method Cannot be defined as static?

Declaring abstract method static If you declare a method in a class abstract to use it, you must override this method in the subclass. But, overriding is not possible with static methods. Therefore, an abstract method cannot be static.

Can I declare static method as abstract?

In Java, a static method cannot be abstract. Doing so will cause compilation errors.

Why can't I have abstract static methods in C#?

With static methods you need to go through a class name anyway, so the exact method to call is known at compile time because it can't and won't change. Thus, virtual/abstract static methods are not available in .

Can a static property be abstract?

You can have static methods in abstract classes. If you declare a static method in an abstract class, you must provide its implementation. Static methods are not associated with instances of the class. Therefore, the static method declared in an abstract class should be called using the class name that defined it.


1 Answers

Static members do not have polymorphism, so they can't be abstract. :(

If that's what you need, consider making a Singleton object, and reading the property off that object.

like image 67
user541686 Avatar answered Sep 30 '22 02:09

user541686