3

I have a class with many fields and about half of them are public. Right now it looks like this:

public int someint1, someint2, someint3;
public string str1, str2;
public bool[] boolArray;
public List<string> listOfStrings;

…and so on. And after that there are some private fields.

Is it possible to write public just once for all those public fields?

user1306322
  • 8,561
  • 18
  • 61
  • 122
  • No, you can't do that. You could, however, define a custom object that has the desired fields on it with standard getters/setters, and then you could reduce the section to something like `public CustomObj state;` – aroth Sep 15 '12 at 13:42
  • Fields should never be public though (except possibly readonly fields). It’s a simple rule, don’t deviate from it unless there’s a good reason. – Konrad Rudolph Sep 15 '12 at 13:45
  • @KonradRudolph why, what's bad in using public fields? – user1306322 Sep 15 '12 at 13:45
  • @user1306322 - The answer to that is here: http://stackoverflow.com/questions/480627/why-wont-anyone-accept-public-fields-in-c – aroth Sep 15 '12 at 13:46
  • @user1306322 Check out [this question](http://programmers.stackexchange.com/questions/161303/is-it-bad-practice-to-use-public-fields) and its duplicate for the gory details. – Adam Lear Sep 15 '12 at 13:47

3 Answers3

3

No, there is no way to do that in C#, you have to declare for every field its access way. In general C# tends limit access by-default, so even if do not write anything, the members will end up like private ones.

Tigran
  • 61,654
  • 8
  • 86
  • 123
0

No there isn't, and you should think about using properties rather than public fields - Why won't anyone accept public fields in C#?

Community
  • 1
  • 1
devdigital
  • 34,151
  • 9
  • 98
  • 120
  • And then, as a next step, get rid of the properties, too. They also expose the state publicly. [Tell, don’t ask](http://c2.com/cgi/wiki?TellDontAsk) – Konrad Rudolph Sep 15 '12 at 13:46
0

if you dont declare an access modifier (private, protected, internal, public), the code will take is a private (so most protected one). Else, you have to delclare it by your self, so type the one you need!

Mitja Bonca
  • 4,268
  • 5
  • 24
  • 30