Public variables are bad practice - I have always been told to stay clear of them. Why? Because they accept invalid values. Make those variables 'protected' or 'private', they told me. And then access them via get()/set() methods. Well, that was many years ago.
Turns out there’s also a good security reason why .Net developers should avoid public variables.
It's called Code Access Security (CAS). .Net relies on the CAS framework to enforce security across assemblies. When an inter-assembly call is made, .Net initiates a stack walk to check the permissions of the caller, and the callers above it in the call chain. This stack walk is fundamental to enforcing security in .Net. It ensures assemblies with less permissions cannot call privileged methods. [We discussed CAS and stack walks last month].
Notice the stack walk? Ay, there’s the rub. The stack walk is triggered only for function calls and not for public variables. Thus a public variable is not protected by CAS. So that’s one reason secure software should not use public variables. What about the get()/set() strategy? They work well with CAS - the stack walk checks if their caller has adequate permissions.
If you have reasons why public variables should be used, I'd love to hear that.