Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Public const string?

Tags:

Is it ok to use a class like this (design / guideline specific)? I'm using MVVM Pattern.

public static class Pages {     public const string Home = "Home.xaml";     public const string View2 = "View2.xaml";     /* a few more... */ } 
like image 405
SBoss Avatar asked Oct 13 '11 08:10

SBoss


People also ask

What is const string in C#?

You use the const keyword to declare a constant field or a constant local. Constant fields and locals aren't variables and may not be modified. Constants can be numbers, Boolean values, strings, or a null reference. Don't create a constant to represent information that you expect to change at any time.

What is const string?

String constants, also known as string literals, are a special type of constants which store fixed sequences of characters. A string literal is a sequence of any number of characters surrounded by double quotes: "This is a string."

How do you assign a value to a const string?

Const values cannot have a value assigned in runtime. If you need to be able to assign value in runtime, pass the value to a constructor call and make the member readonly .

Is string const in C++?

To define a string constant in C++, you have to include the string header library, then create the string constant using this class and the const keyword.


2 Answers

There are significant differences between const and public static readonly, and you should consider which to use with care:

(By "client" here, I mean "code in a different assembly referring to the member.)

  • If you change the value but don't recompile clients, they will still use the original value if you use const. With public static readonly, they will see the updated value. If you recompile all clients anyway, this isn't a problem.
  • Only the const form is a compile time constant, which means it can be used in:
    • Attribute arguments
    • Switch statements
    • Optional parameter declarations

If you're happy to recompile all your clients if you ever change the value, the benefits of the second bullet point point towards using const.

Of course, I wonder whether Pages really needs to be public anyway... it sounds like something which could be internal, with internal members - at which point the downsides of const go away entirely.

like image 77
Jon Skeet Avatar answered Sep 23 '22 02:09

Jon Skeet


A general guideline when using const for defining constant values. Whether these constants are to be accessed outside assembly? If not then declare it as

internal static class Pages {     public const string Home = "Home.xaml";     public const string View2 = "View2.xaml";     /* a few more... */ } 
like image 26
AksharRoop Avatar answered Sep 21 '22 02:09

AksharRoop