Follow Slashdot stories on Twitter

 



Forgot your password?
typodupeerror
×
Programming IT Technology

Coding Standards for C#? 82

infinite9 asks: "I've been given the task of writing the coding standards for my corporation. I've been in IT for 12 years, so many things are obvious. Recently though, my employer has standardized on C# and .NET, and since I'm new to the technology (isn't everyone?) I'm not sure what to include. I've included a paragraph about signing assemblies with a standard key pair as well as a few other odds and ends. Apart from the obvious statements that apply to any language like good comments, good variable names, and maintainable code, can anyone suggest other C#/.NET related things that I should include?"
This discussion has been archived. No new comments can be posted.

Coding Standards for C#?

Comments Filter:
  • Just one rule about coding in c#:

    Don't.

  • Google sez... (Score:3, Informative)

    by Hard_Code ( 49548 ) on Friday April 04, 2003 @09:21AM (#5660124)
    Following the Microsoft recommendations in the Framework SDK might be a

    good idea - they seem pretty well thought out, and the code is going to
    look and feel familiar to other .NET programmers.

    > -----Original Message-----
    > Sent: Monday, July 09, 2001 7:01 PM
    > Subject: [Mono-list] C# coding standards for Mono
    >
    > Hey kids,
    >
    > Has anybody taken a stab at a C# coding standard for Mono classes?
    I'm
    > thinking something along the lines of Sun's Java Coding Conventions
    > (http://java.sun.com/docs/codeconv/html/CodeConvTO C.doc.html)
    >
    • This is pretty sensible advice. Most C# shops I've worked in stick to the standard MS coding conventions.

      I would also stress: use the inline documentation stuff a log (/// comments). Use NDOC to generate documents from the XML output. Make use of the using() {} statement to encourage early resource disposal.

    • MS design guidelines (Score:4, Informative)

      by Jussi K. Kojootti ( 646145 ) on Friday April 04, 2003 @10:00AM (#5660325)
      Yep, They're not bad: Design Guidelines [microsoft.com] for Class Library Developers.

      Maybe you'll find this useful: White paper [gotdotnet.com] on resource management in components written for the Common Language Runtime (CLR).

      -jk

      • In looking at MS's design guidelines, I'm struck by how big the learning curve appears to be.

        One of the main ideas behind guidelines is supposed to be that consistency will result in more programmer productivity because the programmer will recognize new aspects more quickly.

        The question is: Does the time it takes to learn the guidelines so they are second nature exceed the time saved by avoiding a lookup of a function or having to come up with your own name?

        Guidelines are an engineering product just as m
      • Aren't these guidelines oriented to building libraries, more than code style?
    • There are a set of notes towards a set of C# conventions at http://www.xoc.net/standards [xoc.net]. RVBA has long been the most widely used set of conventions for Visual Basic. The new conventions take into account the features of C# and .NET.
  • by buro9 ( 633210 ) <david&buro9,com> on Friday April 04, 2003 @09:32AM (#5660177) Homepage
    Don't attempt to come up with any of your own formatting rules (as much as it's tempting to make your code look like the rest of your code)... having a standard formatting implemented by the IDE results in much cleaner formatting and will ensure that the people you hire will understand the code that much sooner.
    • having a standard formatting implemented by the IDE

      this might be the least worst thing to do, but VS has terrible default formatting. I forget the name of the style, but this is what you get by default:

      namespace Foo
      {
      public class Bar
      {
      void Bar()
      {
      if (foo)
      {
      bar(0);
      }
      else
      {
      bar(1);
      }
      }
      }
      }

      combine this with the all the toolbars and help viewers that are on by default, and you can effectively read about 4 lines of code at once.

      • Bullshit! That is nothing like how VS formats code. I just copied and pasted and this is how it formatted:

        namespace Foo
        {
        public class Bar
        {
        void Bar()
        {
        if (foo)
        {
        bar(0);
        }
        else
        {
        bar(1);
        }
        }
        }
        }
        • er, the indentation got lost in my post, but that wasn't the point. the point was that using sun's style this code is 10 lines while VS formats it to be 17 lines, presenting you with much less code per screen.
        • Ha! That's just a trick to inflate your stats as far as how much line of code per day you can write.

          Kinda like comments, but worse.

          Real men write:

          namespace Foo {
          public class Bar {
          void Bar() {
          if (foo) {
          bar(0);
          } else {
          bar(1);
          } } } }

          If you need more white space between your lines, adjust your font settings, but don't take it out on the brackets.
  • C# Coding Standards (Score:4, Informative)

    by cymantic ( 600615 ) on Friday April 04, 2003 @09:33AM (#5660189) Homepage
    To work out some standards use what you know from Java, Python or any other language with a C based syntax.

    The guys at ICSharpCode (http://www.icsharpcode.net/TechNotes/) have some nice documents on coding styles/standards for coding for #Develop (you don't have to follow them when coding using #Develop)

    Also have a look at something like FX Cop from MS (http://www.gotdotnet.com/team/libraries) to help enforce coding standards.

    t
  • by wonkamaster ( 599507 ) on Friday April 04, 2003 @09:52AM (#5660279)
    It doesn't really matter what coding standards you implement, as long as something consistent is used. And that doesn't really matter much either.

    Microsoft will probably innovate a new language syntax soon, my guess would be C##. It will undoubtedly be more scalable, secure, robust and less prone to errors. And it'll automatically be included in the latest version of Windows, but not be compatible with previous versions due to architecture limitations.

    Personally, I'm holding out for that version. I'm going to push my company to standardize on that version. Because it just makes good business sense.

    We need a moderation for Sarcastic!
    • We need a moderation for Sarcastic!

      I've thought about this as well. The problem is would it +1 Sarcastic or -1 Sarcastic? I think it should be something along the lines of +1 Sarcastic(Funny) and -1 Sarcastic(Asshole). Or how about a 0 Sarcastic that just adds "Sarcastic(" and ")" to the original modifier name?

      Just a thought.
      • I've thought about this as well. The problem is would it +1 Sarcastic or -1 Sarcastic? I think it should be something along the lines of +1 Sarcastic(Funny) and -1 Sarcastic(Asshole). Or how about a 0 Sarcastic that just adds "Sarcastic(" and ")" to the original modifier name?

        In my book Sarcastic would always be a +1. I would, however, like a "-1 poster is an idiot" while we're at it. Oh I suppose that's the Friend vs. Foe system.
  • Learn to use Visual Studio.NET. It will do everything you want it to. Don't worry about tabstops, etc. because it does stuff like that for you. Some helpful shortcuts:

    CTRL+[SPACE] = Type ahead
    /// = When used a line above functions, events, etc. it will autogenerate the XML based comments

    I used to program C# with UltraEdit before my company could afford VS.NET. VS.NET paid for itself the first day that I used it because it saved me so much time.

    If you have the time, I'd highly recommend reading the C [microsoft.com]
    • Re:VS.NET (Score:3, Interesting)

      by Schnapple ( 262314 )
      Two things I would suggest in regards to the reliance upon VS.net:
      1. VS.net obviously gives you the "VB" approach to design and coding, so you have things like Intellisense pop down your available functions and methods, and instead of worrying with coding your GUI design you design it in design mode.

        Of course the problems with this approach is that it's way too easy to use the IDE as a crutch - especially Intellisense. One day you'll be in a situation (like a technical quiz for an interview) where you won'

      • Well... VS.Net, for all that I love about it, sucks at managing large projects. I would STRONGLY recomend making sure you know how to build EVERY project, from the command line, without using the IDE (yes, you can invoke the IDE as a build tool from the command line.) To that end, I'd suggest using NAnt, Ant, or the not free but very fine FinalBuilder.

        As far as wizard generated code goes, the (extraordinarily expensive and worth it) Compuware DevPartner Studio often flags wizard code as non-compliant with
        • Well... VS.Net, for all that I love about it,

          I'm curious. Why *do* people like VS.Net, as opposed to say, emacs?
          • well, Mister CRLF, it is well suited to developing applications on the Windows platform. It provides such boons to us evil stormtroopers like:

            context sensitive help with examples coded in multiple languages.

            Intellisense that integrates user code documentation.

            Template creation to limit junior programmer usage of pretty/useless widgets

            Good macro support

            Integrated web load testing tools

            Integrated Active Directory support

            Integrated database support

            Integrated debugger

            Forms designer for the gui guys (I

            • It just seems that most of these have parallels.

              context sensitive help with examples coded in multiple languages.

              But so does man, which comes with cygwin.

              Intellisense that integrates user code documentation.

              Doxygen.

              Template creation to limit junior programmer usage of pretty/useless widgets

              Dunno exactly what this is.

              Good macro support

              Hehe. Yup, I think emacs could manage this.

              Integrated web load testing tools

              Why would you bundle web load testing tools into an IDE, and what's the benefit
              • Re:VS.NET (Score:3, Informative)

                I was in your shoes when I was using UltraEdit and the free .NET SDK for development. I had all kinds of macros set up to autogenerate a separate xml file where my comments would be extracted from the code and placed into, while placing the rest of the 40 or so cs files into a dll and running it, etc. I thought that the color coding was help enough with programming. I'd just assumed that VS.Net was just bloat-ware like every other MS dev. env. that I've used in the past.

                However, unless you have the enti
      • Of course the problems with this approach is that it's way too easy to use the IDE as a crutch - especially Intellisense. One day you'll be in a situation (like a technical quiz for an interview) where you won't have these tools available, so unless you're paying attention you won't know what to do.

        If I were on an interview and they were asking me such an API-specific question that Intellisense would have helped me answer it, I wouldn't work at that company anyway.

        • Your correct you wouldn't because they would not hire you.

          If a programmer does not know the language well enough to write out a class/method, etc. on a whiteboard without reference then who is really doing the programming?

          Part of being a progammer is understanding the language so well that you can see what the language is doing "under the covers". If the IDE does all of that for you, then I guess the company should hire monkeys because the IDE is doing all of the work.

      • "One day you'll be in a situation (like a technical quiz for an interview) where you won't have these tools available, so unless you're paying attention you won't know what to do. "

        Interesting our lead developer who does our interviews generally asks a question like this, and one of the acceptable answers is "I don't know, but that's easy to find in MSDN."

        We're much more pragmatic here in the heartland.

      • Be advised (warned ?) that the code written by the webforms designer is very, very buggy.

        If you want to wire in custom events for custom controls, or you just like to code your ascx controls in the source view (not the gui designer) then be prepared to have VS.Net intermittently decide to wipe out your event wirings.

        Also be prepared to have VS.Net hijack your xml (the aspx or ascx page) formating any time you switch from source editor to gui editor.
  • use an abstraction layer and your code will be portable (maybe) to gtk#
  • by n1k0 ( 553546 ) on Friday April 04, 2003 @11:24AM (#5660925)
    > and since I'm new to the technology (isn't everyone?)

    Used Java? ;-)
  • by Anonymous Coward
    Having an IT guy come up with coding standards is like asking the janitor to design an operating system.

    (The fact that he's consulting with Slashdot regarding aspects of his job is kind of a hint.)
    • Well, that is a pretty good point. The person creating the standards should be a Configuration Manager/CM Level III type; or a similar position, whose job no longer includes coding - a strong technical writing background is likely a job requirement here. I once worked for a very senior programmer and my duties consisted only of testing software; putting together installers and distribution media; and documentation - which included coding practices for the junior developers. Nice thing was the senior deve
  • You might want to look at what Microsoft has published about standards first, use that as a foundation

    http://msdn.microsoft.com/library/default.asp?url= /library/en-us/cpgenref/html/cpconnetframeworkdesi gnguidelines.asp [microsoft.com]
  • It's easy to abbreviate code with lots of Using statements. However, this obfuscates code, since there are several thousand classes scattered across numerous namespaces. Plus there's no different in byte code between explicit naming and abbreviated naming combined with Using statements. In our group, even the folks originally opposed to all that extra typing have now adopted this style, just for readability. One more thing: After using doxygen for the past year, I view Microsoft's xml tags a distant secon
    • that's not what using does. in C# 'using' is used to explicitly call an object's Dispose() method.
      • There are two forms of using.
        • The using Directive is a namespace alias (of which I was referring to)
        • The using Statement defines a scope at the end of which an object will be disposed (of which you were referring to)

        The point I'm making is to stay away from aliases as much as possible (just check out the header to almost all C# code. You'll see using System; at the front of nearly every file. That's just an alias that does not affect bytecode, but makes the code less clear. Regards...

        • I know this is slightly OT but...does anyone else find this "keyword overloading" (IIRR Don Box's essential .NET was where I saw this nice euphemism, or perhaps it was "namespace overloading") annoying? C# is C and C++ derived...why not use Imports (which has not been used for anyting in C#)?
    • It's easy to abbreviate code with lots of Using statements. However, this obfuscates code, since there are several thousand classes scattered across numerous namespaces.

      Actually, VS.NET comes to the rescue here, as well. If you do a Mouse Hover over the object in question, it will give you full namespace information. If you aren't certain of the class hierarchy, simply mouse over the object and VS.NET tells you what you need to know. More questions? Put the cursor over the object, press F1, and you g
  • by Sevn ( 12012 ) on Friday April 04, 2003 @12:21PM (#5661428) Homepage Journal
    Make sure you recommend CVS, or some other type
    of versioning system to save hell down the road.

    Enforce under penalty of death or termination of
    employment that DOCUMENTATION IS PART OF DEVELOPMENT.
    I've had many a contract where I've basically just
    had to say "screw it" and redo a rats nest of
    undocumentated code because of zero documentation.
    • CVS? They're a Microsoft shop.
      Nothing but M$ products for them.
      VSS I suppose. Make sure you do those backups.

      In addition to the standards document, you should make
      sure that you'll have the appropriate budget for buying
      new dev tools and training every year. I'd also beef up
      your end-user support budget, you'll probably need it.
      Also make sure that your current products will be well
      supported and viable for the next year or so because
      you'll be late on delivery of your C# and .net based rollout.
      • CVS? They're a Microsoft shop.
        Nothing but M$ products for them.

        That looks like a nice, standard mis-informed Slashdot post to me.

        For Windows, there is CVS NT [cvsnt.org] which works great. Then you can use Igloo [jalindi.com] for IDE integration. Or the even cooler Tortoise CVS [tortoisecvs.org] for explorer integration (an easier to use source control tool I have yet to find).

        OR, there is always Subversion [tigris.org] if you don't want CVS. Subversion also has a Tortoise port.

        Or, back in the closed source world, Perforce [perforce.com] and I'm sure a handful of others.

        • I think you're the one with the mis-informed Slashdot post. I'm not sure you've ever worked in a M$ shop, but in my experience very few of these will accept CVS, or any other open-source software solution for that matter. Sure, CVS and Subversion work, but VSS will be the solution most M$ shops use.

          Perforce, Subversion, and CVS are all decent solutions, and all tend to have better reliability than VSS. But I've found that most M$ shops stick with M$ solutions for most tasks. If you're stuck with VSS, f
          • Sure you might have some resistance to anything that isn't VSS, I was just pointing out some alternatives. I was replying to a misinformed post that said VSS was the only option.

            Also, there is Vault [sourcegear.com] which looks very promising. It uses SQL Server as it's repository, and SOAP as the transport and is written in .NET.

  • by Utopia ( 149375 ) on Friday April 04, 2003 @01:18PM (#5661895)

    ....several other readers. Take a look at FxCop [gotdotnet.com].
    It will help you check your code for conformance to design guidelines and point out possible usage errors, localization issues, security problems, and possible performance improvements.



  • Wiki Wiki Wiki (Score:2, Insightful)

    A complete coding standard is difficult to come up with in one shot. Also, developers generally have their "de-facto" standards that they like to follow, so getting buy-in can be difficult. Perhaps it's easier to just allow the coding standard to evolve as needed by using a collaboration facility to come up with it.

    Take a look at Twiki [twiki.org].
  • Poor guy. (Score:4, Insightful)

    by pmz ( 462998 ) on Friday April 04, 2003 @03:56PM (#5663311) Homepage
    Recently though, my employer has standardized on C# and .NET, and since I'm new to the technology (isn't everyone?)

    I'm suprised your company would take such a high-risk action. "Standardizing" on something so new and untested is, IMO, irresponsible.

    Adopting .NET now is like adopting J2EE when it was at version 1.0 or 1.1. The details of the APIs aren't hammered out, yet, so a lot of code your company creates will be "legacy" very quickly--probably within one year. If you don't believe me, ask anyone who jumped onto the JSP and Java Servlet bandwagon when they first came out (before tag libraries, etc.).
    • They're not the only ones. You see, .NET is a religion, just like Java was ten years ago. My company is the seventh largest in the world, but someone got religion, and now C# and .NET are all the rage, to the point that they're specing them for embedded devices. Yet just last year we were forbidden to use Java for anything. The training coordinator asked me if I knew of any experienced C# instructors. I've seen hiring reqs that specify five years experience in .NET.

      It doesn't really matter how new or untes
      • I've seen hiring reqs that specify five years experience in .NET.

        And surprisingly they find them. I wish I knew how to BS so well. I am tired of seeing BS experts get the jobs over me. I don't like dishonesty, but in this dog-eat-dog economy it is a necessity, and I find that I am not good at it due to lack of practice.
  • http://www.gotdotnet.com/team/libraries/

    This very useful program is a code analysis tool that checks your .NET assemblies for conformance to the .NET Framework Design Guidelines . It uses reflection, MSIL parsing, and callgraph analysis to inspect your assemblies for more than 200 defects in the following areas: naming conventions, library design, localization, security, and performance (see rule descriptions). The package includes both GUI and command line versions of the tool, as well as the SDK to creat
  • by Anonymous Coward
    I think it's pretty funny, yet deadly serious... They go through each feature of C# and end up concluding that you should avoid them all.
    C# Best Practice: Do not use boxing and unboxing [geocities.com]

    check it out here:
    csharp faq [geocities.com]

    • A site that purports to be a language FAQ and yet goes thru the features one at a time eliminating those that can be misused would rule out all good languages -- all useful tools in fact.

      There is some value in a list of wise warnings, but that's not how this site presents itself, so I'm forced to conclude that it's just another anti-MS propaganda piece.

      Since the REAL story about MS is pretty nasty, yet the technology of C# and .Net is very nice, I don't have much respect for nonsense like this.
  • by The Mayor ( 6048 ) on Saturday April 05, 2003 @01:15AM (#5667131)
    When developing your coding standards, categorize the "rules" into three categories: recommended, guidelines, and rules.

    Recommendations are really just suggestions. For instance, the last coding standards I helped to author we recommended that open brackets (the '{' character) be placed at the end of the expression rather than on a separate line. This recommendation was not followed by some, but it really isn't that critical towards code readability. For the record, I actually like putting open brackets on new lines, so that the open & close brackets line up. I did change my practices, but I occasionally forgot, and didn't get yelled at since it was merely a "recommendation".

    Guidelines are "rules" to be followed at all times unless there is a really good reason not to. For instance, we had a guideline that instructions should not be divided between lines, and that only one instruction should appear per line. Well, if you have a really long piece of logic, splitting the instruction across two lines makes sense. Conditional expressions (i.e. something of the form of "(ab)? a : b") counted as a single instruction.

    Rules must be followed at all times. For instance, one rule we used was no "goto" statements. Pretty simple and obvious.

    We found that by having the rules in this form, people that would categorically reject some of the guidelines under different circumstances were more receptive towards the guidelines when presented in this manner. So long as they weren't forced to adopt these "rules" they somehow seemed less ominous. YMMV.
    • I'll add one to this and see which category the folks here think it belongs in.

      Functions/methods should be separated into "functions", which return a value without modifying external values, and "procedures", which do exactly the opposite.
  • It is VERY nice to see people being helpful; and not just making cracks because C# is a Microsoft product.
  • I wasn't going to comment on this thread, not being particularly informed on C# itself, but two things have struck me that might be worth mentioning.

    1. Coding standards shouldn't be about your style and layout. It's helpful to be consistent in which way you write your {} and how you capitalise your function names, but this is hardly the serious stuff of professional programmers. Coding standards should be a guide to, for example, which common idioms in the language are adopted and which are not (preferably
  • SFAIK you can assign meta-data to all functions etc.. in C#.

    Defing some basic meta-data that should be present.

    Say Author, Data, Changes / BUGS , Links to design and test documentation etc...

    It should be easy to link any good configuration management software into the meta-data.

I've noticed several design suggestions in your code.

Working...