Results 1 to 6 of 6

Thread: Non Static vs Static

  1. #1

    Thread Starter
    Fanatic Member steve65's Avatar
    Join Date
    Jun 2000
    Posts
    610

    Non Static vs Static

    I must admit I am still trying to determine the best way of using statics. I have the following code:
    Code:
    using System;
    using System.Windows.Forms;
    
    namespace WindowsApplication1
    {
    	internal class Class1
    	{
    		internal Class1(){}
    
    		internal static void Main()
    		{
    			Class2.TestString = "";
    		}
    	}
    }
    Code:
    using System;
    using System.Windows.Forms;
    
    namespace WindowsApplication1
    {
    	public class Class2
    	{
    		string myTestString = null;
    
    		public string TestString
    		{
    			get {return myTestString;}
    			set {myTestString = value;}
    		}
    	}
    }
    When I try to run the code I get: An object reference is required for the nonstatic field, method, or property 'WindowsApplication1.Class2.TestString' at the line Class2.TestString = "";

    If I change Class2 and the TestString property to a static I am able to compile the code. In VB I was able to add properties to any of my public classes without any problems.

    I can use static but I am not sure why I should and why it worked and what repercussions it has on my code. Would somebody be able to explain this to me?
    This space for rent...

  2. #2
    Retired G&G Mod NoteMe's Avatar
    Join Date
    Oct 2002
    Location
    @ Opera Software
    Posts
    10,190

    Re: Non Static vs Static

    When you are dealing with static for classes, you can think about functions and variables decleared as static as shared between all objects derived from that class. If you have a stativ variable in a class, then all objects will share the same variable, in stead of having one each as they normaly would.

    Static functions, is functions that doesn't work on member variables. You do not need to have an object to call a static function. But if it is not a static function, then you need to have an object to be able to call it:

    MyObjectName.UsingANonStaticFunction();

    MyClassName.CallingAStaticFunction();



    Hope that cleared up a bit. If I missunderstood what you ment. Then please ask again, and I will try to explain a bit furuther.


    - ØØ -

  3. #3

    Thread Starter
    Fanatic Member steve65's Avatar
    Join Date
    Jun 2000
    Posts
    610

    Re: Non Static vs Static

    OK I think I have it figured out what C# is looking for and what you are trying to explain to me. I recoded my first class to look like this:
    Code:
    	internal class Class1
    	{
    		internal Class1(){}
    
    		internal static void Main()
    		{
    			Class2 MyLocalClass2 = null;
    			MyLocalClass2 = new Class2();
    			MyLocalClass2.TestString = "";
    		}
    	}
    When I issue the line: Class2 MyLocalClass2 = null; I am now creating a local object of class2 in class1. I then can access all of the methods, properties, etc for that instance of class2, same as VB.

    If I set class2 as static then all classes that call class2 are calling the same object, method, property, etc. so then this will work:
    Code:
    	public class Class1
    	{
    		public Class1(){}
    
    		public static void Main()
    		{
    			SetTestString("Hello");
    			WriteTestString();
    		}
    
    		private static void SetTestString(string Input)
    		{
    			Class2.TestString = Input;
    		}
    
    		private static void WriteTestString()
    		{
    			System.Console.WriteLine(Class2.TestString);
    		}
    	}
    Can you explain to me why SetTestString and WriteTestString have to be static in order for this code to work?
    This space for rent...

  4. #4
    Retired G&G Mod NoteMe's Avatar
    Join Date
    Oct 2002
    Location
    @ Opera Software
    Posts
    10,190

    Re: Non Static vs Static

    Sorry, I don't quite get what you are on to here...does the second code bit have anything to do with the first one here at all?

    This is what you have:

    Code:
    	public class Class1
    	{
    		public Class1(){}
    
    		public static void Main()
    		{
    			SetTestString("Hello");
    			WriteTestString();
    		}
    
    		private static void SetTestString(string Input)
    		{
    			//Something
    		}
    
    		private static void WriteTestString()
    		{
    			//Something
    		}
    	}
    They have to be static because you are calling them without making a Class1 object first. If you don't want them to be static, then you need to make an object of them to call them.


    Code:
    	public class Class1
    	{
    		public Class1(){}
    
    		public static void Main()
    		{
                            Class1 myClass = new Class1();
    			myClass.SetTestString("Hello");
    			myClass.WriteTestString();
    		}
    
    		private void SetTestString(string Input)
    		{
    			Class2.TestString = Input;
    		}
    
    		private void WriteTestString()
    		{
    			System.Console.WriteLine(Class2.TestString);
    		}
    	}

    Then this will work. If it had someting to do with your class two, then I am sorry but don't understand where you are going....

    I will make one more post after this one, and try to explain a bit furuther.

  5. #5
    Retired G&G Mod NoteMe's Avatar
    Join Date
    Oct 2002
    Location
    @ Opera Software
    Posts
    10,190

    Re: Non Static vs Static

    There is a few times that you want to make only have static functions in a class. A good example can be if you are making a math library or something like that. Then you don't want to make an object just to be able to sum up two numbers or something. So then all the functions in the class will be static. And to call them, you will have to use the class name.

    I.e: The functions looks like this (they are in the Math class):

    Code:
    public static int add(int a, int b){
        return a+b;
    }
    
    public static int mul(int a, int b){
        return a*b;
    }

    Then in your app, you can use them like this.

    Code:
    int finalAdd = Math.Add(3,4);
    int finalMul = Math.Mul(3,4);

    If you had NOT made the functions static. Then you would first have had to make an object out of it. So then your calling code have to look like this:

    Code:
    Math myMathObject = new Math();
    
    int finalAdd = myMathObject.Add(3,4);
    int finalMul = myMathObject.Mul(3,4);
    and that is something you usualy don't want if you are just adding a few numbers.


    *************************************

    To make it easier to deside when to use static look at this real life scenario. I am a game programmer, so here we go with a game programming scenario. Lets say I have an enemy class. In my game it is two really importen things I want to save. It is the enemies name, and it is how many enemies I have in total in the game. Each enemy has a uniqe name. Lets call them "Tor, Anders, and Hans". So that means that we have 3 enemies. Now should we make the name static or not. Hmm....if you guessed not static, then you are starting to understand. Because they have all different names, so the variable that holds the name needs to belong the object, and not the class, so every object have it's own instance of the name variable.

    But then we are over to the "count" variable. The variable that should hold the number of enemies. Should it be static or not. Well, one enemy doesn't know about all the other enemies. So it doesn't make sense to have it as a non static variable. If we make it static, then there will only be ONE variable called "count". And it can be updated every time we make a new enemy. It would be much harder to update a variable that holds the total number of enemies if we had to update the variable in all the objects in play. So by making it static (making it a "class" variable rather then object variable), we only need to update it at one place.


    Hope that helps a bit.
    - ØØ -

  6. #6

    Thread Starter
    Fanatic Member steve65's Avatar
    Join Date
    Jun 2000
    Posts
    610

    Re: Non Static vs Static

    Thank you for your time, I think I have a handle on it now. Is the scope of the static class only within the assembly that it is added in? In otherwords can another program using the same class, reference the properties that I am setting in my program? I would think the answer is no.

    Why does the calling method have to be static in order to call the static class' methods?
    Code:
    public static void TestMethod()
    {
    	MessageBox.Show(Convert.ToString(Class2.add(1,3)));
    	MessageBox.Show(Convert.ToString(Class2.mul(2,3)));
    }
    If I don't set TestMethod to static I then get the error:
    An object reference is required for the nonstatic field, method, or property 'WindowsApplication1.Class1.TestMethod()'
    This space for rent...

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