C# Inheritance, Static Methods

Dear experts

I want to have several static NameValueCollections in my application that
serve as containers for some constant values that belong to a certain topic.

All of them have to implement the same two methods, one to get a value by
key, the other to return the whole NameValueCollection.

It works fine, it's just a question of design. I would like to inherit from a base
class that implement the methods. All I want to do, when I make a new NVC
is to fill it inside the constructor of the derived class.

I want to use the static methods inherited from the base class, but
want to use the NVC that's defined in the derived class. I don't need
any instances of the derived class.

Here's the pseudo code for that:

class myBase {

public static GetAll() {...}
public static Get(string key) {...}

}

class myDerived : myBase {
   NameValueCollection nvc;

   myDerived() {
     nvc.Add("somekey", "somevalue");
     ...
   }
}


Thanks for suggestions !
maxomedia







maxomediaAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

InteractiveMindCommented:
If the NVC is declared in the derived class, then the base class cannot access it.

What you could do however, is create an interface (instead of a base class):

   interface myBase
   {
      public static string GetAll() ;
      public static string Get( string key ) ;
   }
InteractiveMindCommented:
Or just define the NVC as null in the base class, such that it must be defined in the derived class..
maxomediaAuthor Commented:
Hello InteractiveMind

Thank you very much for your help. I tried your second hint, but it doesn't work yet.
Here is my latest version:

            class myBase
            {
                  protected static NameValueCollection nvc = null;

                  public static NameValueCollection GetAll()
                  {
                        return nvc;
                  }
      
                  public static string Get(string key)
                  {
                        return nvc[key];
                  }

                  public static bool Exist(string key)
                  {
                        return (nvc[key]==null ? false : true);
                  }
            }

            /* Sort List for Search Results*/

            sealed class SortList : myBase
            {
                  private static NameValueCollection nvc = new NameValueCollection();

                  static SortList()
                  {
                        nvc.Add("1","price");
                        nvc.Add("2","quality");
                        nvc.Add("3","resort");
                  }
            }

Cheers !
maxomedia
OWASP Proactive Controls

Learn the most important control and control categories that every architect and developer should include in their projects.

maxomediaAuthor Commented:
There's a runtime error:
Object reference not set to an instance of an object when I try
to access the NVC in my code.

I think it's still the NVC in the Base class that is accessed.
InteractiveMindCommented:
Your problem is this line:

   private static NameValueCollection nvc = new NameValueCollection();

you cannot redeclare a variable--you can only change it's value (e.g. instantiate it).

So what you'd need to do, is in your methods, add the following line at the very beginning:

   if ( this.nvc == null )
   {
      this.nvc = new NameValueCollection() ;
   }

(Alternatively, you could create a constructor to do this--but this probably won't work, as your members are static, and therefore do not *need* instantiation).


I've never mixed static and inheritance before (that I remember)--so I'm hoping this will work, but I do ponder...
InteractiveMindCommented:
Uh oh... I was right to question what static+inheritance would result in...

Take this example:

using System ;

namespace T
{
      class MainClass
      {
            public MainClass()
            {
                  D.abc = "hey" ;
                  Console.WriteLine( E.abc ) ;
            }
            
            public static void Main(string[] args)
            {
                  new MainClass() ;
            }
      }
      
      public class myBase
      {
            public static string abc = null ;
            
            public static string Get()
            {
                  return abc ;
            }
      }
      
      public class D : myBase
      {
            
      }
      
      public class E : myBase
      {
            
      }
}


It outputs "hey". Because both D and E are running off the same instance (that of the base class)..

****************************************************
So because you're using static members, you cannot use inheritance. :-(
****************************************************

I would suggest one of the following:

   • Use an interface;
   • Do not have the methods as static, and do not define the NVC member in the base class;
TribmosCommented:
might you be wanting a 'virtual' method?

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/csspec/html/vclrfcsharpspec_10_5_3.asp

or possibly an abstract?
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/csspec/html/vclrfcsharpspec_10_5_3.asp

the virutal is like this : Define a function and have it perform x. child classes can override this function

the abstract is like this : define a function which all child classes MUST implement
Djranga2003Commented:
Hi maxomedia,
After few reserch work.. , i found a answer (actually a trick ;-) )  to your problem..so..
 
lets go to the begining... the problem with ur initial code is ur accessing a variable (nvc) from the base which is intialized by the deriverd class. If ur aware about the behaviour of static constructors, u will see that the static constructor of derived class is not called until u access a member of that class.
so .. the code should be somthing like this
first add a static constructor to the base

protected static NameValueCollection nvc;
            static myBase()
            {
                  if (nvc == null)
                  {
                        nvc = new NameValueCollection() ;
                  }
            }

then add a dummy initializer to the detived class
     public static void  Init()
            {
                  // no implementation needed
            }

now all u have to do is, before use any static function of derived class just call the init() method of derived class. this will call the derived class's constructor for u..

the complete code is here

      class myBase
      {
            protected static NameValueCollection nvc;
            static myBase()
            {
                  if (nvc == null)
                  {
                        nvc = new NameValueCollection() ;
                  }
            }
            public static NameValueCollection GetAll()
            {
                  return nvc;
            }
     
            public static string Get(string key)
            {
                  return nvc[key];
            }
            public static  bool Exist(string key)
            {
                  return (nvc[key]==null ? false : true);
            }
      }

      /* Sort List for Search Results*/

      sealed class SortList : myBase
      {
            static SortList()
            {
                  nvc.Add("1","Aprice");
                  nvc.Add("2","quality");
                  nvc.Add("3","resort");
            }
            public static void  Init()
            {
            }
      }

when using the sortlist's static members...do somethin like this..
    SortList.Init() ;
    MessageBox.Show( SortList.Get("1") );

hope this will solve ur problem..


Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
maxomediaAuthor Commented:
Thanks very much InteractiveMind and Djranga2003 for
spending time to solve my problem.

Although Djranga2003 was providing exactly the solution I was
looking for, I am very thankful for the input of InteractiveMind.

Therefore, I go for a point split.

Cheers,
maxomedia

InteractiveMindCommented:
Thank you :)
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Visual Basic Classic

From novice to tech pro — start learning today.