CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 15 of 15

Thread: error CS0118

Threaded View

  1. #15
    Join Date
    Jan 2002
    Location
    Scaro, UK
    Posts
    5,940

    Re: error CS0118

    Actually it does have the same effect as the static keyword in classes in C++. However do you know what effect it has on methods in C++ ? I'm sorry but it doesn't look likely from your questions above.

    A static declaration in a class means that whatever it is applied to is only created once, and without a class instance.

    Therefore this below will give you exactly the same problem as you're seeing above :

    Code:
    class MyClass
    {
        private int m_nValue = 0;
    
        // this is a method which operates on the class instance.
        public void Function()
        {
            StaticFunction();
        }
    
        // this is not attached to an instance
        static public void StaticFunction()
        {
            m_nValue = 0; // this fails because there is no class instance.
    
            // here 'this' has no meaning as the method isnt a part of an instance of the class
        }
    }
    However, static methods and member variables can be accessed without a class instance :

    Code:
    MyClass.StaticFunction();
    // this is ok because it's a static method.
    
    MyClass.Function();
    // this isn't ok because it needs an instance of the class
    
    MyClass myClass = new MyClass();
    myClass.Function(); // this is ok
    Hope this helps. It's not a great explanation : I suggest you read up on statics in MSDN because they are tremendously useful - especially in C# where you can do things like this :

    Code:
    // simple singleton
    public sealed class MyClass
    {
       // instansiated on first call to MyClass
       static private MyClass m_theClass = new MyClass;
    
       static public MyClass Singleton
       {
            get
            {
                return m_theClass;
            }
       }
     
       // ensures you can't 'new' the class  
       private MyClass()
       {
       }
    }
    Darwen.
    Last edited by darwen; February 14th, 2005 at 04:12 PM.
    www.pinvoker.com - PInvoker - the .NET PInvoke Interface Exporter for C++ Dlls.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured