11 Replies - 1869 Views - Last Post: 28 March 2016 - 02:27 PM

Poll: Naming convention for constants in C# (10 member(s) have cast votes)

What naming convention do you currently use for your constants in C#?

  1. C/C++: ACCELERATION_DUE_TO_GRAVITY (5 votes [33.33%] - View)

    Percentage of vote: 33.33%

  2. .NET Naming: AccelerationDueToGravity (5 votes [33.33%] - View)

    Percentage of vote: 33.33%

  3. Isolated class C/C++: Constants.ACCELERATION_DUE_TO_GRAVITY (2 votes [13.33%] - View)

    Percentage of vote: 13.33%

  4. Isolated class .NET: Constants.AccelerationDueToGravity (2 votes [13.33%] - View)

    Percentage of vote: 13.33%

  5. Settings class property: Settings.AccelerationDueToGravity (1 votes [6.67%] - View)

    Percentage of vote: 6.67%

Do you use one convention for P/Invoke and another for managed code?

  1. Yes: P/Invoke should look like the original API documentation (7 votes [70.00%] - View)

    Percentage of vote: 70.00%

  2. No: All code should like managed code. (1 votes [10.00%] - View)

    Percentage of vote: 10.00%

  3. Yes: I'm lazy and I'll just copy and paste from PInvoke.org (2 votes [20.00%] - View)

    Percentage of vote: 20.00%

If you didn't have to work on a team, which convention would you use?

  1. C/C++: ACCELERATION_DUE_TO_GRAVITY (4 votes [36.36%] - View)

    Percentage of vote: 36.36%

  2. .NET Naming: AccelerationDueToGravity (5 votes [45.45%] - View)

    Percentage of vote: 45.45%

  3. Isolated class C/C++: Constants.ACCELERATION_DUE_TO_GRAVITY (1 votes [9.09%] - View)

    Percentage of vote: 9.09%

  4. Isolated class .NET: Constants.AccelerationDueToGravity (1 votes [9.09%] - View)

    Percentage of vote: 9.09%

  5. Settings class property: Settings.AccelerationDueToGravity (0 votes [0.00%])

    Percentage of vote: 0.00%

Should enums be named like constants?

  1. Yes (5 votes [50.00%] - View)

    Percentage of vote: 50.00%

  2. No (5 votes [50.00%] - View)

    Percentage of vote: 50.00%

Should read only properties be named like constants?

  1. Yes (4 votes [40.00%] - View)

    Percentage of vote: 40.00%

  2. No (6 votes [60.00%] - View)

    Percentage of vote: 60.00%

Do you keep your constant values in a settings or configuration file?

  1. Yes: Constants can be changed without recompiling (1 votes [10.00%] - View)

    Percentage of vote: 10.00%

  2. No: Constants are constant. Rebuild and re-run unit tests if they change. (9 votes [90.00%] - View)

    Percentage of vote: 90.00%

Vote Guests cannot vote

#1 Skydiver  Icon User is online

  • Code herder
  • member icon

Reputation: 5895
  • View blog
  • Posts: 20,128
  • Joined: 05-May 12

Naming convention for constants in C#

Posted 06 February 2016 - 06:19 PM

What naming convention do you use for your constants when you are writing C# code? Are you consistent with it? Does your concept of constants extend out to enums, as well as read only properties?
Is This A Good Question/Topic? 0
  • +

Replies To: Naming convention for constants in C#

#2 modi123_1  Icon User is online

  • Suitor #2
  • member icon



Reputation: 13491
  • View blog
  • Posts: 53,888
  • Joined: 12-June 08

Re: Naming convention for constants in C#

Posted 06 February 2016 - 07:25 PM

I don't find myself using too many constants outside of what you defined in enums and read only properties. Looking back - when I do I may throw in 'CONST' in the name.
Was This Post Helpful? 0
  • +
  • -

#3 Skydiver  Icon User is online

  • Code herder
  • member icon

Reputation: 5895
  • View blog
  • Posts: 20,128
  • Joined: 05-May 12

Re: Naming convention for constants in C#

Posted 08 February 2016 - 06:53 AM

Sort of the flip side of this poll is this question that I wanted to ask: If you use the C/C++ naming convention for constants, what other .NET Naming Conventions do you not follow?

For example, I know that a lot of people tend to do the VB-style Hungarian their control names even though the .NET Naming Conventions say that Hungarian should be eschewed. ex. btnNukeIt instead of NukeItButton

Lately, I've been seeing more people ignoring the Pascal case for long acronyms. ex. JSONParser instead of JsonParser.

Lately, I've been seeing more people ignore the meaningful parameter names, specially when using lambdas. ex. (g, k) => { g[k] = 12; } vs. (group, key) => { group[key] = 12; }
Was This Post Helpful? 0
  • +
  • -

#4 ybadragon  Icon User is offline

  • Home Owner
  • member icon

Reputation: 571
  • View blog
  • Posts: 2,647
  • Joined: 11-May 12

Re: Naming convention for constants in C#

Posted 08 February 2016 - 08:02 AM

I name my controls btnNukeIt

I have also been using the Pascal case for acronyms. As well with lambda, the only time I'm giving names to the parameters is if I'm generating anonymous types like with my service generator

		var services = ds.Tables[0].Rows.Cast<DataRow>().Where(row=> (string)row.ItemArray[8] != "ProjectName").Select(row=> new {ID = (long)row.ItemArray[0], ServiceType = (string)row.ItemArray[2], ServiceCall = (string)row.ItemArray[3], EntityType = (string)row.ItemArray[7], ProjectName = (string)row.ItemArray[8], EntityNamespace = (string)row.ItemArray[9], NodeRoute = (string)row.ItemArray[6]});



Was This Post Helpful? 0
  • +
  • -

#5 Curtis Rutland  Icon User is offline

  • (╯□)╯︵ (~ .o.)~
  • member icon


Reputation: 5101
  • View blog
  • Posts: 9,283
  • Joined: 08-June 10

Re: Naming convention for constants in C#

Posted 08 February 2016 - 10:39 AM

I've decided that, to make my life easier (and because it's reasonably sane) that I will take Resharper's naming suggestions by default. If I work on a team that has some particular style, I change them, but R# basically uses Microsoft's guidelines, which I'm happy with.

I tend to use a fair amount of constants, mainly because R# identifies values that do not change in code and suggests to make them constant. I also work with Dynamics CRM a lot, which involves using "property bag" objects, with a lot of var val = entity["fieldName"]; type of code, so I have lots of "Field Name" constants.

How do you guys organize your constants in C#? In cases like I just described, I like to make a static class (typically inside the class that's doing the work) called Fields, sometimes actually Constants. How about you guys?

Quote

Lately, I've been seeing more people ignore the meaningful parameter names, specially when using lambdas. ex. (g, k) => { g[k] = 12; } vs. (group, key) => { group[key] = 12; }


I'm guilty of this sometimes, but it's probably two reasons:

1. When I was learning, almost every example of a lambda used x => ...
2. It's shortcut syntax, so it's not that big a logical leap to use shortcut variable names.

I do try to use letters or short names that make semantic sense. If I have a collection called rows, then my iterator variable will be r. Sometimes I'll write the code with one-letter variable names, then refactor when I'm done to be more descriptive.
Was This Post Helpful? 0
  • +
  • -

#6 rgfirefly24  Icon User is offline

  • D.I.C Lover
  • member icon


Reputation: 446
  • View blog
  • Posts: 2,177
  • Joined: 07-April 08

Re: Naming convention for constants in C#

Posted 08 February 2016 - 11:56 AM

I am with Curtis on the R# thing. It has made my development a lot easier to just go with that. As for how I organize my constants, they are always at the top of the file/class/etc where they are used, and I put a region around them.

ex:
public class Config
{

    #region Config Constants
    private const int DefaultCofigId = 1234;
    #endregion
}



As for Lambda's I am also guilty of using short cuts here, but typically try and make them logical.

configItems.Where(ci => ci.App.Equals("MyApplication"));
Was This Post Helpful? 0
  • +
  • -

#7 ybadragon  Icon User is offline

  • Home Owner
  • member icon

Reputation: 571
  • View blog
  • Posts: 2,647
  • Joined: 11-May 12

Re: Naming convention for constants in C#

Posted 08 February 2016 - 12:12 PM

with constants I normally just put them at the top of the file
Was This Post Helpful? 0
  • +
  • -

#8 JacobH  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 26
  • View blog
  • Posts: 176
  • Joined: 07-September 15

Re: Naming convention for constants in C#

Posted 22 February 2016 - 01:08 PM

Almost always just standard resharper settings, but code not native to your application to me is a very special case. Having wrote a lot of "lower-level" C# code in my limited time programming, I have kind of a lot of comments on this very topic, take them for what you will but I have been very happy with the way I've done things in my last project in regards to most of these questions. Sorry for the length.

Quote

What naming convention do you currently use for your constants in C#?


If the related code is not native to my application, I choose to follow the naming of the original code and disable any related style-cop esk settings for the project for that field or class.
public const int WM_USER = 0x0400; // I like this.
public const int WmUser = 0x0400; // I hate this.



If the property is a const and native to my applications code, I prefer to separate them into a separate file "Constants.cs" in the relevant folder as partial class, like so:

    public partial class Engine
    {
        // Core stuff.      
    }
    // EngineConstants .cs
    public partial class Engine
    {
        public static class Constants
        {
            public const int AccelerationDueToGravity = 0;
            public const float OtherConstant = 5f;
        }
    }


This lets me separate the constants clearly and still call things like:
DoWork(Engine.Constants.AccelerationDueToGravity);


Quote

Do you use one convention for P/Invoke and another for managed code?


Yes and yes. If you ask me, it is more confusing to even .NET developers who have only been hardcore managed code users and follow the Microsoft C# naming conventions religiously to use anything but the closest representation of the native API being used. This allows easy reviewing of MSDN pages and the tons of resources on how to use the native code.

I tend to place pinvokes in a class matching the module name they reside in, and copy and paste the MSDN documentation and link as xml comments in the pinvoke, and tend to only add them on a as-needed basis as to not have bloat. Here is an example:

Note: Normally placed in something like src\Native\Pinvokes\User32.cs etc
    public class User32
    {
        /// <summary>
        ///     Loads the specified module into the address space of the calling process. The specified module may cause other
        ///     modules to be loaded.
        /// </summary>
        /// <param name="lpFileName">
        ///     The name of the module. This can be either a library module (a .dll file) or an executable module (an .exe file).
        ///     The name specified is the file name of the module and is not related to the name stored in the library module
        ///     itself,
        ///     as specified by the LIBRARY keyword in the module-definition (.def) file.
        ///     If the string specifies a full path, the function searches only that path for the module.
        ///     If the string specifies a relative path or a module name without a path, the function uses a standard search
        ///     strategy to find the module; for more information, see the Remarks.
        ///     If the function cannot find the module, the function fails. When specifying a path, be sure to use backslashes (\),
        ///     not forward slashes (/).
        ///     For more information about paths, see Naming a File or Directory.
        ///     If the string specifies a module name without a path and the file name extension is omitted, the function appends
        ///     the default library extension .dll to the module name.
        ///     To prevent the function from appending .dll to the module name, include a trailing point character (.) in the
        ///     module name string.
        /// </param>
        /// <returns>
        ///     If the function succeeds, the return value is a handle to the module.
        ///     If the function fails, the return value is NULL. To get extended error information, call
        ///     <see cref="Marshal.GetLastWin32Error" />.
        /// </returns>
        [DllImport("kernel32", SetLastError = true, CharSet = CharSet.Unicode)]
        public static extern IntPtr LoadLibrary(string lpFileName);
    } 



Quote

If you didn't have to work on a team, which convention would you use?


I don't work on a team, but I am fairly positive if when I reach the level of being able to work on a team and not just for fun at home, I would make my argument for the above in as humble of fashion as possible and accept the teams choice one way or another happily, but slightly more happily if they would accept my argument :)/>/>/>/>/>.

Quote

Should enums be named like constants?


Once again I think it just depends on what your enum represents. If it's an enum of possible window message events, then no I think you should name them exactly as the actual native code does. Snippet from my WindowsMessage enum:


  
    /// <summary>
    ///     Enum of Window messages that can be intercepted inside the native windows WindowProc call back.
    /// </summary>
    /// <remarks>
    ///     See https://msdn.microsoft.com/en-us/library/windows/desktop/ms633573(v=vs.85).aspx for more details on the
    ///     WindowProc call back.
    /// </remarks>
    public enum WindowMessages
    {
        /// <summary>
        ///     Sent as a signal that a window or an application should terminate.
        ///     A window receives this message through its WindowProc function.
        /// </summary>
        /// <remarks>Review https://msdn.microsoft.com/en-us/library/windows/desktop/ms632617(v=vs.85).aspx for details.</remarks>
        WM_CLOSE = 0x0010
    }



Should read only properties be named like constants?-
No. They are not the same.

Do you keep your constant values in a settings or configuration file?-
Of course not. Settings and configurations are just that. Constants are not.

Quote

Lately, I've been seeing more people ignore the meaningful parameter names, specially when using lambdas.


I find this perfectly acceptable in the right setting. Take this example, it to me is very clear what m is and I imagine it should be for anyone else looking at it.. there is no need to write out monster.
var monsters = Game.EntityList.OfType<Monster>();
var monstersToMakeFlee = monsters.Where(m => m.CurrentHealth.AsPercentage <= 50);
foreach(var m in monstersToMakeFlee)
{
    m.MakeFlee();
}

This post has been edited by JacobH: 22 February 2016 - 01:10 PM

Was This Post Helpful? 1
  • +
  • -

#9 maceysoftware  Icon User is online

  • D.I.C Lover
  • member icon

Reputation: 348
  • View blog
  • Posts: 1,494
  • Joined: 07-September 13

Re: Naming convention for constants in C#

Posted 22 February 2016 - 01:47 PM

Originally we were told to name our controls like FooButton in VB.Net however we have since been told to change it to ButtonFoo. just so you can start typing button to bring up all the buttons...
Was This Post Helpful? 0
  • +
  • -

#10 lordofduct  Icon User is offline

  • I'm a cheeseburger
  • member icon


Reputation: 2667
  • View blog
  • Posts: 4,786
  • Joined: 24-September 10

Re: Naming convention for constants in C#

Posted 25 March 2016 - 07:25 AM

There's a lot of .Net standard naming conventions I ignore.

But usually I do so only in a private scope, and stick to more standard public naming conventions.

For instance I use the underscore '_' prefix for private fields, I find it faster and easier to distinguish when reading code in my methods.

1)lowercase leading is a local variable in the method irrelevent of the object
2)uppercase leading is a property of the object and represents information about the object
3)underscore leading is a field of the object and represents the state of the object

I guess one could use lowercase for private fields, and use 'this.' to distinguish fields from local variables. But my brain just happens to interpret 'this' as meaning 'accessing the interface of self'... and I don't think of fields as being on the interface of this. Just the way I read it... (and it's 4 extra characters)

The most glaring public facing naming standard I use that is not .Net is the FULL_CAPS_CONST naming convention from C/C++. It screams out "I'm a constant!" to me. The .Net standard makes it look like any other property... I don't intrinsicly know if it's const or not with out inspecting it more closely.
Was This Post Helpful? 0
  • +
  • -

#11 JacobH  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 26
  • View blog
  • Posts: 176
  • Joined: 07-September 15

Re: Naming convention for constants in C#

Posted 28 March 2016 - 12:34 PM

The most glaring public facing naming standard I use that is not .Net is the FULL_CAPS_CONST naming convention from C/C++. It screams out "I'm a constant!" to me. The .Net standard makes it look like any other property... I don't intrinsicly know if it's const or not with out inspecting it more closely. 


This is why I prefer to abuse partial classes to avoid confusion while still allowing me to follow standard naming conventions for C# stuff.

public partial class Engine
{
    // Core stuff.      
}
// EngineConstants .cs
public partial class Engine
{
    public static class Constants
    {
        public const int AccelerationDueToGravity = 0;
        public const float OtherConstant = 5f;
    }
}


I find this:
WorkWithValue(Engine.Constants.AccelerationDueToGravity);


To be much more clear and self-explanatory than:

WorkWithValue(Engine.ACCELERATION_DUE_TO_GRAVITY);



You also get the added bonus of it also being super clear of what is going on for people who may have never even used C++ / C++ standard naming conventions in the past.
Was This Post Helpful? 0
  • +
  • -

#12 lordofduct  Icon User is offline

  • I'm a cheeseburger
  • member icon


Reputation: 2667
  • View blog
  • Posts: 4,786
  • Joined: 24-September 10

Re: Naming convention for constants in C#

Posted 28 March 2016 - 02:27 PM

The resulting name is pretty nice.

But it's a lot of extra code which would cause me to struggle changing. Combined with the commonality of the C++ naming system being so widely understood. I tripped over it within my first few weeks of programming, and that was in Actionscript years back!
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1