Page 1 of 1

C# Using Statics And Instances :: When To Use Static?

#1 Sheepings   User is offline

  • Senior Programmer
  • member icon

Reputation: 149
  • View blog
  • Posts: 962
  • Joined: 05-December 13

Posted 25 November 2018 - 09:03 AM

Lets dive into this and take a look at our structure below. We will define some classes and some static/non-static methods inside both static and non-static classes. Since I've seen this topic come up a few times over the last few weeks, I've decided to cover some basic aspects of common questions asked when using static and non static logic. Most of the questions asked are answered in the comments in-line with the code samples. We will go over what works and what doesn't, and at the bottom, I've covered some basic points to note when working with static/non-static classes and instances of those classes.

	public class ClassNonStatic // This is our non-static class
    {
        public static string staticString() // This is our static string method inside the non-static class. We can not create an instance of this method but we can call it directly. - Compilable
        {
            Console.WriteLine("I am allowed to be in non-static and static classes. And Can be used here.");
            return "I am allowed to be in non-static and static classes. And Can be used here.";
        }
        public string nonStaticString() // This is our non-static string method. - Compilable
        {
            Console.WriteLine("I am allowed to be in non-static classes. And Can be used here. Instance methods can also be used here.");
            return "I am allowed to be in non-static classes. And Can be used here. Instance methods can also be used here.";
        }
    }
    public static class ClassStatic // This is our static class
    {
        public static string staticString() // This is our static string method inside the static class. - Compilable
        {
            Console.WriteLine("I am a static string method and am allowed to be here. And Can be used here.");
            return "I am a static string method and am allowed to be here. And Can be used here.";
        }
        public string nonStaticString() // This is our non-static string method. - Not compilable 
        {
            Console.WriteLine("I am not allowed to be here. And Can Not be used here. Instance members have no place here.");
            return "I am allowed to be here. And Can be used here. Instance members have no place here.";
        }
    }


Do you already notice any inconsistencies? If not I will show you in the blow screenshot ::
Attached Image
Instance members such as this nonStaticString can not be declared in a static class.

Lets say for arguments sake, we have a button and a simple windows form. We will put the following code inside a button and execute the below code from a click event. But which code lines are executable?

	        
            ClassNonStatic CallNonStaticInstance = new ClassNonStatic(); // Working logic :: You can create an instance of a non-static class.
            ClassStatic CallToStaticInstance = new ClassStatic(); // Broken logic :: You can not create an instance of a static class.

            CallNonStaticInstance.nonStaticString(); // Working logic :: We can call an instance of the nonStaticString() method.
            CallNonStaticInstance.staticString(); // Broken logic :: We can not call an instance of the staticString() method even though its in a non static class, this is because the method itself is static. You can't create an instance of a static method.

            ClassNonStatic.staticString(); // Working Logic :: We can call the staticString() member of the non-static class directly.
            ClassNonStatic.nonStaticString(); // Broken logic :: We can not call the nonStaticString() method member of the ClassNonStatic directly, as your IDE should tell you an instance of the object/method is required ([url="https://stackoverflow.com/questions/779091/what-does-object-reference-not-set-to-an-instance-of-an-object-mean"]Object reference[/url]).

            // Now lets try the static class and see what is different and how we can utilize its member methods, and what works and what doesn't... Lets start by working with the instance we defined above.
            CallToStaticInstance.nonStaticString(); // Broken Logic :: You can create an instance of the class but can not access the nonStaticString() method, because it has no business being an instance member in a static class.
            CallToStaticInstance.staticString(); // Broken Logic :: You can not create an instance of this staticString() method member of ClassStatic because it is static.

            ClassStatic.staticString(); // Working Logic :: You can call this staticString() method member of ClassStatic directly.
            ClassStatic.nonStaticString(); // Broken Logic :: You can not call this nonStaticString() member of the ClassStatic class, because it has no business being in a static class in the first place.


Attached Image
In this screenshot, the underlying red squiggles under the code are telling you that the logic wrote will cause runtime problems and need addressing and most importantly rewriting. But what is restricting us from writing our code as described above? Simply put; your declaration type. Anything deriving the word static can't be instantiated as new. However, you may call it directly by is class name. Let me explain...

The static keyword in the C# programming language allows you to define static classes and static members appropriately. A static class is similar to a class which is both abstract/sealed. Declaring a class as static, you should define it with the static keyword in the class declaration. When the static keyword is used on a class declaration, it forces the class to have limited functionality and it cannot be instantiated or inherited and all of the members of that class are also static. Under no circumstances would you define or place non-static instance members in a static class. Statics don't offer any behaviour patterns, as I like to say they hold run'n'forget code, and so there is no point in allowing a static class to be inherited.


As you can see, non-static classes can be instantiated by creating a new instance of them.

And static classes cannot be instantiated i.e, ClassStatic CallToStaticInstance = new ClassStatic();.

All non-static classes can have instance method and static methods respectively. If you're creating static classes, you should note; they can only have static methods, and non-static members do not belong inside them. Instance methods must be called by instantiating a new instance of the class, and not the class itself. If you're calling static methods, you must call them on the class itself, and not on the new instances of the class. There are ways you can use delegates on classes to derive a certain functionality from static classes and also to use delegates in-place of interfaces when working with static classes, but we will need to draw up a new article on that one later on. But for this very basic tutorial, I will park this one here and perhaps do a part two of this :: Using delegates instead of interfaces with statics :: Advantages / Disadvantages.

You may also find my other tutorial on multithreading worth glancing over, as it holds some relevance to this topic, in regards; how to access methods, properties which belong to UI threads or classes, and exchanging information between classes.

Is This A Good Question/Topic? 0
  • +

Page 1 of 1