55

I have this code;

using System;

namespace Rapido
{
    class Constants
    {
        public static const string FrameworkName = "Rapido Framework";
    }  
}

Visual Studio tells me: The constant 'Rapido.Constants.FrameworkName' cannot be marked static

How can I make this constant available from other classes without having to create a new instance of it? (ie. directly accessing it via Rapido.Constants.FrameworkName)

  • 1
    Related post - [Why can't I have “public static const string S = ”stuff"; in my Class?](https://stackoverflow.com/q/408192/465053) – RBT Jun 29 '21 at 03:14

3 Answers3

130
public static class Constants
{
    public const string FrameworkName = "Rapido Framework";
}
Mitch Wheat
  • 295,962
  • 43
  • 465
  • 541
  • 1
    The poster asked for a way of not instantiating a class, and have it contain constants. – Mitch Wheat May 09 '09 at 03:38
  • 13
    You wouldn't have to create an instance to get to the constant value. Constants work just like statics. Other than they are copied at compile time instead of referenced. – Matthew Whited May 09 '09 at 03:42
  • 3
    would the downvoter (19/05/2011) plase leave a comment. Thanks. – Mitch Wheat May 20 '11 at 01:18
  • 1
    Not the downvoter, but I assume it's because the solution does not explain itself. – Eric Fossum Apr 18 '22 at 18:48
  • If that doesn't explain the question "How can I make this constant available from other classes without having to create a new instance of it?" - then I humbly suggest one shouldn't be programming in c# – Mitch Wheat Apr 18 '22 at 23:40
37

A const is already static as it cannot change between instances.

ggf31416
  • 3,582
  • 1
  • 25
  • 26
  • Right... so I don't understand why the compiler balks when you explicitly denote it as such... – Cuga May 09 '09 at 03:53
  • I understand that's the way it's implemented. I'm asking why it's done that way. – Cuga May 09 '09 at 04:08
  • 12
    Take care not to confuse const and static, they mean different things. const refers to an item's value whereas static refers to how an items storage is allocated. See http://stackoverflow.com/questions/842609/why-does-c-not-allow-const-and-static-on-the-same-line/842649#842649 – Tim Long May 09 '09 at 05:08
13

You don't need to declare it as static - public const string is enough.

Andrew Kennan
  • 13,947
  • 3
  • 24
  • 33
  • 4
    In fact it is an error to declare it static because that would imply that memory allocation and runtime initialisation needs to take place, neither of which is needed for a constant. – Tim Long May 09 '09 at 05:23