-1

This is a somewhat more complicated question than it might appear.

Every Unity video and tutorial that discusses access modifiers that I can find tells me that "private is the default access modifier for member variables in C#", but according to the C# documentation the default access modifier should be internal.

So, the question is, what is the true story of what's going on here? If I don't put an access modifier on a variable in a unity script it does act private, but what is Unity doing to make this happen!? Somehow I cannot find an explanation online.

See also this unanswered question on Unity Answers.

syusim
  • 143
  • 6
  • The default access modifier depends on _what_ sort of thing you're talking about. Classes and members have different defaults. – gunr2171 Dec 12 '22 at 20:23
  • I am talking about member variables. I said this in the question. – syusim Dec 12 '22 at 20:23
  • "Class and struct members, including nested classes and structs, have private access by default" from your first link – gunr2171 Dec 12 '22 at 20:24
  • I don't think the rules are different than normal C#, so see [this question](https://stackoverflow.com/questions/2521459/what-are-the-default-access-modifiers-in-c) for a more complete answer. – Joe Sewell Dec 12 '22 at 20:31

1 Answers1

2

I think you are confused by the scope here: The default access modifier for members (fields and methods) is private, while the default access modifier for classes and interfaces is internal. That's because classes cannot be declared private (that would mean they're only visible within themselves, which doesn't make sense). An exception are inner classes (classes within classes), but for these, separate default rules apply.

It's good style to always explicitly declare the access modifier for all objects.

PMF
  • 14,535
  • 3
  • 23
  • 49
  • 1
    `classes cannot be declared private` isn't true. You can create a private class within another class that can only be used by the class it's declared in. –  Dec 12 '22 at 20:42
  • @rshepp Ok, it's more precisely "top level classes" that cannot be private. I think that's beyond the scope of this basic question, though. – PMF Dec 12 '22 at 21:22
  • "It's good style to always explicitly declare the access modifier for all objects." is subjective. I personally find this pointless and noisy. – Asik Dec 12 '22 at 21:33