i need to use static variable to get it's value in any class in my solution .
i created a class named Myclass
public class Myclass {
public static str myVar ;
}
an other class where i need to set a value to my variable
public class MyOtherClass {
Myclass myclass;
myclass.myVar = "valeur";
}
but i get errors .
Thank you for your help.
thank you for your help but my code in MyOtherClass have to be Inside a method
Next time, please tell us what errors you got.
The first bug it that your code in MyOtherClass isn't inside the method.
Then you're accessing the variable incorrectly. Static variables are associated with the class, not with an instance, therefore you need to use the type and not the instance. And you need to use :: to access static members. Therefore the assignment should look like this:
Myclass::myVar = "valeur";
But I wouldn't ever do it and it wouldn't pass my code review. Public variables are problematic and I strongly recommend that you never use them. Forget that this option exists; it's not wise. For example, what if you later realize that you want to run some extra logic when the value is changed? This can be easily done if you keep the variable non-public and allow its changes only through a (public) method.
And be very careful with static variables. Are you sure it's absolutely necessary in your scenario? And even if you absolutely need something static, shouldn't you create a singleton object wrapping all the related logic?
public class MyOtherClass
{ Myclass::myVar = "value"; }
Here's how you should use it: blogs.msdn.microsoft.com/.../x-in-ax7-static-members
Stay up to date on forum activity by subscribing. You can also customize your in-app and email Notification settings across all subscriptions.
André Arnaud de Cal... 291,188 Super User 2024 Season 2
Martin Dráb 230,030 Most Valuable Professional
nmaenpaa 101,156