Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory allocation for const in C#

Tags:

c#

How is memory allocated when I use:

public class MyClass
{       
    public const string myEVENT = "Event";
    //Other code
}
like image 697
softwarematter Avatar asked Apr 13 '10 09:04

softwarematter


People also ask

Are constants allocated memory?

Constants have no storage location at runtime. All access to constant identifiers results in the literal value of that constant replacing the identifier when the code is compiled. No, const string literals will have object reference to an interned String object.

Where is const stored in memory?

As per the memory layout of C program ,constant variables are stored in the Initialized data segment of the RAM. But as per some of the Microcontroller memory layout ,const variables are stored in FLASH Memory.

How are constants stored in C?

'const' variable is stored on stack. 'const' is a compiler directive in "C".

Does const use less memory?

They keyword const still consumes RAM. The word "const" only tells the complier that the code can't change the value. So if you try to assign a const a value, the complier will throw an error.


1 Answers

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.

like image 56
Jon Skeet Avatar answered Sep 23 '22 01:09

Jon Skeet