smatter
smatter

Reputation: 29208

Memory allocation for const in C#

How is memory allocated when I use:

public class MyClass
{       
    public const string myEVENT = "Event";
    //Other code
}

Upvotes: 17

Views: 3548

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1502006

Well, it's a compile-time constant - so if you use it from other assemblies, "Event" will be copied into the IL for those other assemblies. Whether that gets interned cross-assembly or not depends on a CLR setting IIRC.

However, if you're worried about whether you'll get a new string or a new string variable for each instance of MyClass, you don't need to worry - const implies static.

In short, unless you've got huge, huge wads of constants (or enormous string constants) it's not going to cause you an issue.

Upvotes: 17

Related Questions