C# coding style question
-
For
static
members, do you preferpublic static Type Member;
or
static public Type Member;
where
public
can be any of the visibility keywords. I've found I use both :-O, and I'm trying to find out if there's a best practice out there that makes sense.Software Zen:
delete this;
I'm with Richard Deeming here, I use the first method myself. As Richard said, consistency is the key!
-
I agree with Richard Deeming's response focusing on "consistency." And, I emphatically agree with PIEBALDConsult's response, when he says/implies that one should always specify the scope with Public/Private, and that it would be a good thing for the .NET compiler to "enforce" this. I prefer to use: public/private static variabletype. It's interesting to me that if you write (C#, WinForms) inside the scope of a Form's class definition:
public static bool availableOutsideFormClassScope = true;
That ReSharper 8 will "suggest" that the use of 'public is redundant. But, if you write this:
static bool notAvailableOutsideFormClassScope = true;
, you have, in effect, declared this variable as private. I have never had occasion to use a Form scoped static variable, method, embedded class, etc; I only use static when I want something to be accessible outside a Form's class scope. But, perhaps if I were dealing with multiple instance of the same application, or multi-threading, there would be an "organic" need for this ? When I write applications where there are multiple independent Forms (in WinForms this can be done by modifying the Program.cs file so it calls an initializer method to "run" the application ... and that initializer creates and "shows" all Form instances ... rather than doing the usual: Application.Run(new SomeMainForm()); ... in that circumstance I usually use a ststic class defined as an an application top-level class (i.e., added via VS's Project/Add Class menu). I know there are people who feel an almost "religious zeal" about not using static anything/anywhere, perceiving the use of static whatever as a violation of the No-Globals-Strongly-Typed supreme being, and doomed to provoke the wrath of the Threading sub-deities :) I have yet to have a cause to feel such a conviction. Bill
Google CEO, Erich Schmidt: "I keep asking for a product called Serendipity. This product would have access to everything ever written or recorded, know everything the user ever worked on and saved to his or her personal hard drive, and know a whole lot about the user's tastes, friends and predilections." 2004, USA Today interview
BillWoodruff wrote:
I know there are people who feel an almost "religious zeal" about not using static anything/anywhere, perceiving the use of static whatever as a violation of the No-Globals-Strongly-Typed supreme being
I have a feeling you and I are of a vintage, Bill :). We are grizzled combat veterans of the FORTRAN wars. We remember when men were men, women created compilers[^], and you knew how to handle globals safely.
Software Zen:
delete this;
-
I prefer to put visibility first, and for what it's worth, I don't think I would make a static field public.
Espen Harlinn Principal Architect, Software - Goodtech Projects & Services AS Projects promoting programming in "natural language" are intrinsically doomed to fail. Edsger W.Dijkstra
Espen Harlinn wrote:
I don't think I would make a static field public
I normally don't, but for the purposes of the example...
Software Zen:
delete this;
-
Espen Harlinn wrote:
I don't think I would make a static field public
I normally don't, but for the purposes of the example...
Software Zen:
delete this;
:thumbsup: Fair enough ;) But then you never know who is following these discussions, and some will surely copy your code without a second thought ...
Espen Harlinn Principal Architect, Software - Goodtech Projects & Services AS Projects promoting programming in "natural language" are intrinsically doomed to fail. Edsger W.Dijkstra
-
I prefer the following.
static public...
private static...I do it that way to make the basic nature of the items more visible to all.
Hmm. Some of my usage variation seems like that, like my intent was to call attention to the fact something was
static
.Software Zen:
delete this;
-
I'm with Richard Deeming. Additionally, I always specify the access modifier, I never allow a default to apply -- I think the defaults should be removed from the language.
I always specify the access modifier as well. I've always distrusted my memory when it comes to default behaviors with subtle consequences. I explicitly parenthesize as well :-O.
Software Zen:
delete this;
-
:thumbsup: Fair enough ;) But then you never know who is following these discussions, and some will surely copy your code without a second thought ...
Espen Harlinn Principal Architect, Software - Goodtech Projects & Services AS Projects promoting programming in "natural language" are intrinsically doomed to fail. Edsger W.Dijkstra
If they're copying the millifragment I posted, they're in more trouble than they know.
Software Zen:
delete this;
-
If they're copying the millifragment I posted, they're in more trouble than they know.
Software Zen:
delete this;
Agree, but then, on the other hand, they probably wouldn't notice ...
Espen Harlinn Principal Architect, Software - Goodtech Projects & Services AS Projects promoting programming in "natural language" are intrinsically doomed to fail. Edsger W.Dijkstra
-
Hmm. Some of my usage variation seems like that, like my intent was to call attention to the fact something was
static
.Software Zen:
delete this;
Then you should have said so.
-
I agree with Richard Deeming's response focusing on "consistency." And, I emphatically agree with PIEBALDConsult's response, when he says/implies that one should always specify the scope with Public/Private, and that it would be a good thing for the .NET compiler to "enforce" this. I prefer to use: public/private static variabletype. It's interesting to me that if you write (C#, WinForms) inside the scope of a Form's class definition:
public static bool availableOutsideFormClassScope = true;
That ReSharper 8 will "suggest" that the use of 'public is redundant. But, if you write this:
static bool notAvailableOutsideFormClassScope = true;
, you have, in effect, declared this variable as private. I have never had occasion to use a Form scoped static variable, method, embedded class, etc; I only use static when I want something to be accessible outside a Form's class scope. But, perhaps if I were dealing with multiple instance of the same application, or multi-threading, there would be an "organic" need for this ? When I write applications where there are multiple independent Forms (in WinForms this can be done by modifying the Program.cs file so it calls an initializer method to "run" the application ... and that initializer creates and "shows" all Form instances ... rather than doing the usual: Application.Run(new SomeMainForm()); ... in that circumstance I usually use a ststic class defined as an an application top-level class (i.e., added via VS's Project/Add Class menu). I know there are people who feel an almost "religious zeal" about not using static anything/anywhere, perceiving the use of static whatever as a violation of the No-Globals-Strongly-Typed supreme being, and doomed to provoke the wrath of the Threading sub-deities :) I have yet to have a cause to feel such a conviction. Bill
Google CEO, Erich Schmidt: "I keep asking for a product called Serendipity. This product would have access to everything ever written or recorded, know everything the user ever worked on and saved to his or her personal hard drive, and know a whole lot about the user's tastes, friends and predilections." 2004, USA Today interview
Just to clarify:
static bool notAvailableOutsideFormClassScope = true;
is in fact NOT
private
. Neither is itpublic
. The default isinternal
(scope=assembly). As a default this makes the most sense in my opinion (regardless if having a default makes sense at all) I still specify the visibility for every class (and member). Just because I don't like relying on defaults ;) Edit: See Access Modifiers (C# Programming Guide) (MSDN)[^] First paragraph of the section "Class and Struct Accessibility" Edit2: Regarding Resharper (At least in Version 6.1) you let Resharper suggest explicit access modifiers: :) -> Resharper -> Options... -> Code Editing -> Formatting Style -> Other -> Modifiers -> "Use explicit private modifier" / "Use explicit internal modifier" -
I agree with Richard Deeming's response focusing on "consistency." And, I emphatically agree with PIEBALDConsult's response, when he says/implies that one should always specify the scope with Public/Private, and that it would be a good thing for the .NET compiler to "enforce" this. I prefer to use: public/private static variabletype. It's interesting to me that if you write (C#, WinForms) inside the scope of a Form's class definition:
public static bool availableOutsideFormClassScope = true;
That ReSharper 8 will "suggest" that the use of 'public is redundant. But, if you write this:
static bool notAvailableOutsideFormClassScope = true;
, you have, in effect, declared this variable as private. I have never had occasion to use a Form scoped static variable, method, embedded class, etc; I only use static when I want something to be accessible outside a Form's class scope. But, perhaps if I were dealing with multiple instance of the same application, or multi-threading, there would be an "organic" need for this ? When I write applications where there are multiple independent Forms (in WinForms this can be done by modifying the Program.cs file so it calls an initializer method to "run" the application ... and that initializer creates and "shows" all Form instances ... rather than doing the usual: Application.Run(new SomeMainForm()); ... in that circumstance I usually use a ststic class defined as an an application top-level class (i.e., added via VS's Project/Add Class menu). I know there are people who feel an almost "religious zeal" about not using static anything/anywhere, perceiving the use of static whatever as a violation of the No-Globals-Strongly-Typed supreme being, and doomed to provoke the wrath of the Threading sub-deities :) I have yet to have a cause to feel such a conviction. Bill
Google CEO, Erich Schmidt: "I keep asking for a product called Serendipity. This product would have access to everything ever written or recorded, know everything the user ever worked on and saved to his or her personal hard drive, and know a whole lot about the user's tastes, friends and predilections." 2004, USA Today interview
Well if all you're writing is front-end stuff, then you wouldn't have many public members anyway. I write mostly back-end library stuff so a great many of my members are public static methods, but not many fields. A few examples:
public static readonly System.Type BaseType = typeof(T) ;
public static readonly Rational MaxValue = new Rational ( decimal.MaxValue , 1M ) ;
public static event ErrorDelegate OnError ;
public static ValueOf<T> operator + ( ValueOf<T> Op1 , ValueOf<T> Op2 ) ...
public static System.Reflection.PropertyInfo CommandTextAttributeProperty { get ; private set ; }Consistency allowed me to
find
these easily. -
For
static
members, do you preferpublic static Type Member;
or
static public Type Member;
where
public
can be any of the visibility keywords. I've found I use both :-O, and I'm trying to find out if there's a best practice out there that makes sense.Software Zen:
delete this;
-
BillWoodruff wrote:
I know there are people who feel an almost "religious zeal" about not using static anything/anywhere, perceiving the use of static whatever as a violation of the No-Globals-Strongly-Typed supreme being
I have a feeling you and I are of a vintage, Bill :). We are grizzled combat veterans of the FORTRAN wars. We remember when men were men, women created compilers[^], and you knew how to handle globals safely.
Software Zen:
delete this;
Well, I'd be pleased as punch to be of the same vintage as you ... but, I suspect the year of my exfiltration from the womb, 1943, is some ways "off" from your ship-date. However, I only started messing with computers in 1982 (after my use-by date), and I turned to vinegar early. I do, though, use 'static anything only in circumstances where I feel there is an absolute need to do so, although I suspect I use them more frequently than the mythical "average" .NET programmer. bill
Google CEO, Erich Schmidt: "I keep asking for a product called Serendipity. This product would have access to everything ever written or recorded, know everything the user ever worked on and saved to his or her personal hard drive, and know a whole lot about the user's tastes, friends and predilections." 2004, USA Today interview
-
Just to clarify:
static bool notAvailableOutsideFormClassScope = true;
is in fact NOT
private
. Neither is itpublic
. The default isinternal
(scope=assembly). As a default this makes the most sense in my opinion (regardless if having a default makes sense at all) I still specify the visibility for every class (and member). Just because I don't like relying on defaults ;) Edit: See Access Modifiers (C# Programming Guide) (MSDN)[^] First paragraph of the section "Class and Struct Accessibility" Edit2: Regarding Resharper (At least in Version 6.1) you let Resharper suggest explicit access modifiers: :) -> Resharper -> Options... -> Code Editing -> Formatting Style -> Other -> Modifiers -> "Use explicit private modifier" / "Use explicit internal modifier":thumbsup:Hi Nicholas, that's a very interesting, and appreciated, response, thanks. I am definitely a devotee of the cult whose mantra is: "declared accessibility keeps you virgin." I studied the MSDN page you kindly sent me a link to: the word 'static does not appear in it; the distinction between 'private and 'internal mentioned there applies to classes, and structs: "Classes and structs that are declared directly within a namespace (in other words, that are not nested within other classes or structs) can be either public or internal. Internal is the default if no access modifier is specified." The example I showed uses variables. But, I did find that page worth studying, and bookmarking, for future reference ! Given these two declarations in a Form class' scope: static bool notAvailableOutsideFormClassScope1 = true; private static bool notAvailableOutsideFormClassScope2 = true; There is no difference in accessibility/behavior outside/inside the Form class' scope. I've actually gone to the trouble, just to make sure, of testing (code on request) if there's any difference in accessibility/behavior. In externally declared classes, one static, the other public, neither the static class, or the public class, can access those static bool, form class' scoped, variables. As you would expect, both the static class, and an instance of the public class created in the Form's scope, where those variables are declared, can use/access (set, get) those variables. So, I see no evidence for your assertion that a static variable declared without access-modifier is, by default, 'internal, and not 'private. ReSharper 8: Resharper/Options/Code Editing/C#/Formatting Style/Other/Modifiers dialog ... I note that I have both options, "Use explicit internal modifier," and "Use explicit private modifier:" enabled. The default behavior in ReSharper 8, with these options enabled, is to prepend the 'private access-modifier for a static variable, after you type it. bill
Google CEO, Erich Schmidt: "I keep asking for a product called Serendipity. This product would have access to everything ever written or recorded, know everything the user ever worked on and saved to his or her personal hard drive, and know a whole lot about the user's tastes, friends and predilections." 2004, USA Today interview
-
public static is more poetic. We've been using it for a decade now. Why change it? :-O
Starting to think people post kid pics in their profiles because that was the last time they were cute - Jeremy.
Vunic wrote:
public static is more poetic.
Just curious: is private static any less poetic ? bill
Google CEO, Erich Schmidt: "I keep asking for a product called Serendipity. This product would have access to everything ever written or recorded, know everything the user ever worked on and saved to his or her personal hard drive, and know a whole lot about the user's tastes, friends and predilections." 2004, USA Today interview
-
Vunic wrote:
public static is more poetic.
Just curious: is private static any less poetic ? bill
Google CEO, Erich Schmidt: "I keep asking for a product called Serendipity. This product would have access to everything ever written or recorded, know everything the user ever worked on and saved to his or her personal hard drive, and know a whole lot about the user's tastes, friends and predilections." 2004, USA Today interview
-
:thumbsup:Hi Nicholas, that's a very interesting, and appreciated, response, thanks. I am definitely a devotee of the cult whose mantra is: "declared accessibility keeps you virgin." I studied the MSDN page you kindly sent me a link to: the word 'static does not appear in it; the distinction between 'private and 'internal mentioned there applies to classes, and structs: "Classes and structs that are declared directly within a namespace (in other words, that are not nested within other classes or structs) can be either public or internal. Internal is the default if no access modifier is specified." The example I showed uses variables. But, I did find that page worth studying, and bookmarking, for future reference ! Given these two declarations in a Form class' scope: static bool notAvailableOutsideFormClassScope1 = true; private static bool notAvailableOutsideFormClassScope2 = true; There is no difference in accessibility/behavior outside/inside the Form class' scope. I've actually gone to the trouble, just to make sure, of testing (code on request) if there's any difference in accessibility/behavior. In externally declared classes, one static, the other public, neither the static class, or the public class, can access those static bool, form class' scoped, variables. As you would expect, both the static class, and an instance of the public class created in the Form's scope, where those variables are declared, can use/access (set, get) those variables. So, I see no evidence for your assertion that a static variable declared without access-modifier is, by default, 'internal, and not 'private. ReSharper 8: Resharper/Options/Code Editing/C#/Formatting Style/Other/Modifiers dialog ... I note that I have both options, "Use explicit internal modifier," and "Use explicit private modifier:" enabled. The default behavior in ReSharper 8, with these options enabled, is to prepend the 'private access-modifier for a static variable, after you type it. bill
Google CEO, Erich Schmidt: "I keep asking for a product called Serendipity. This product would have access to everything ever written or recorded, know everything the user ever worked on and saved to his or her personal hard drive, and know a whole lot about the user's tastes, friends and predilections." 2004, USA Today interview
Hm... Very interesting Bill :thumbsup: Had to test it myself too now :) It looks like the default access modifier is only
internal
for classes and structs, while it isprivate
for class members (Variables, Methods, etc.). So I was wrong in the first place :-O (considering the topic/examples were about variables). Looks like a lack of consistency to me. A reason more for me to dislike those defaults ;) I've never noticed that as I always write the access modifier to be clear of my intentions. As far as I can see, the default value should be sufficient in most cases to be able to use your class without any explicit modifiers.private
makes usually no sense for a class (as you won't be able to use it anywhere except the top level class "possessing this class) andinternal
allows enough for usage in you application. if you want to expose it more you can still change it to public. A default ofprivate
for class members also seems reasonable given that you usually want fields to private (and probably a bunch of class methods too).BillWoodruff wrote:
The default behavior in ReSharper 8, with these options enabled, is to prepend the 'private access-modifier for a static variable, after you type it.
You should also be able to change the order of the modifiers on the following line :)
-
Well, I'd be pleased as punch to be of the same vintage as you ... but, I suspect the year of my exfiltration from the womb, 1943, is some ways "off" from your ship-date. However, I only started messing with computers in 1982 (after my use-by date), and I turned to vinegar early. I do, though, use 'static anything only in circumstances where I feel there is an absolute need to do so, although I suspect I use them more frequently than the mythical "average" .NET programmer. bill
Google CEO, Erich Schmidt: "I keep asking for a product called Serendipity. This product would have access to everything ever written or recorded, know everything the user ever worked on and saved to his or her personal hard drive, and know a whole lot about the user's tastes, friends and predilections." 2004, USA Today interview
Hmm. Physically, I'm a mite younger than you, since I was born in 1961. Professionally, I'm older, as I've been working as a programmer since 1980, when I started part-time my sophomore year of college. Compared to our compatriots here at CP (nice little alliteration there), we're both Jurassic :-D :sigh:.
Software Zen:
delete this;
-
For
static
members, do you preferpublic static Type Member;
or
static public Type Member;
where
public
can be any of the visibility keywords. I've found I use both :-O, and I'm trying to find out if there's a best practice out there that makes sense.Software Zen:
delete this;
First one... always.
-
Hm... Very interesting Bill :thumbsup: Had to test it myself too now :) It looks like the default access modifier is only
internal
for classes and structs, while it isprivate
for class members (Variables, Methods, etc.). So I was wrong in the first place :-O (considering the topic/examples were about variables). Looks like a lack of consistency to me. A reason more for me to dislike those defaults ;) I've never noticed that as I always write the access modifier to be clear of my intentions. As far as I can see, the default value should be sufficient in most cases to be able to use your class without any explicit modifiers.private
makes usually no sense for a class (as you won't be able to use it anywhere except the top level class "possessing this class) andinternal
allows enough for usage in you application. if you want to expose it more you can still change it to public. A default ofprivate
for class members also seems reasonable given that you usually want fields to private (and probably a bunch of class methods too).BillWoodruff wrote:
The default behavior in ReSharper 8, with these options enabled, is to prepend the 'private access-modifier for a static variable, after you type it.
You should also be able to change the order of the modifiers on the following line :)
Hi Nicholas, I am curious now: in what circumstances have you ever used a static class, struct, or fields, or method, defined in the scope of a Form's class, and either made it private by declaring it private, or let it become private by default when you left off the access-modifier ? I have never found a reason to do that, myself, but I suspect there are reasons for doing it under some circumstances that I'm not aware of ... and, I'd like to be aware of what possible use a private static something-or-other could be ! fyi: I went into ReSharper 8, and changed the modifier list so 'internal was at the top of the list. Declaring a static boolean variable in a Form: ReSharper 8 prepended the 'private access-modifier as soon as I completed the declaration. It is good to learn new things, and it is good to have cause to question what one takes for granted, so I thank you for motivating me to revisit these aspects of .NET :) yours, Bill
Google CEO, Erich Schmidt: "I keep asking for a product called Serendipity. This product would have access to everything ever written or recorded, know everything the user ever worked on and saved to his or her personal hard drive, and know a whole lot about the user's tastes, friends and predilections." 2004, USA Today interview