0
Question about static variables/ classes C#
So I've been working through the C# course and I've just finished the static section but Im a lil confused. Ive used Unity before learning C# so it was super trial and error. But I never needed the Main method, could anyone explain when / where I'd declare a variable or method static if I don't have a main method to call them in? I think I've misunderstood what static is meant for. I look forward to your replys.
4 Réponses
+ 1
No. The values are only shared per run of the program. If you want something to persist to another run you have to save stuff to the file system and load it during the next run.
That example is something I copied to check it's output. In this example, ageSum is the sum of all dogs ever created while the program is running. If you get rid of one of the dogs ageSum will still be 5. I think the best way for you to understand it would be to play with the values for a bit to see what happens when you start creating and deleting dogs.
+ 1
static variables are shared between all instances of a class
Below is an example I had laying around.
You can access static variables without needing to be in a static function like main, just remember that they are not attached to an object.
https://code.sololearn.com/cXU99ERo52b2/?ref=app
0
I think I understand. In your example you made ageSum static so that no matter how many dogs there are their age will add to the total.
Am I right in saying if the program were ran twice the total age would be 10? (2+3+2+3) because ageSum remains static?
0
Ok I will try that. Thankyou for the help