✅ Variables from different classes not adding up
Hello my name is Peter and i would like to ask for your help. In my code, i am unable to add variable from one class to variable from another class. I'll show you what i mean:
So if i try to print the value of , it should return 2, since it's 1+1. But unfortunately it returns only 1, as it seems to completely ignore the variable from the other class added to it.
5 Replies
$static
In C#, static allows you to have members (classes, methods, etc) that are not tied to any particular instance and are therefore always, globally, accessible. When applying
static
members, take the following considerations:
• If there are to be multiple instances of a class, do not use static
• If you need to track state, do not use static
• If you are going to have multi threaded workflows, do not use static unless you're aware of the caveats
static
is best used for stateless methods, extension methods/classes and in areas where you understand the pros/cons. Read more here: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/staticYou should understand the difference between objects and classes, and how static plays in to this
If you want Skret to initialise based upon the values of a Latkova object, then you first need to create said object and pass it into the Skret constructor
I think i understand a little bit. Since hodnotaBrneni is part of Latkova, and is a static variable, i thought that i dont need to create an instance of Latkova object, since the variable belongs to the class itself, if you know what i mean. Is there any solution? Thanks for hearing me out.
Understood, basically it means that static variable cannot be used in this manner and it needs to be non - static and belong to a created object, right? ill try that, thank you very much!
Okay, it would be like a bad habit to do it through static variables. Ill change it to non-static and try it again
Was this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.
Closed!