Object creation of class having constant.

A

archana

Hi all,

I am having suppose say following class
class MyClass
{
public int x;
public int y;
public const int c1 = 5;
public const int c2 = c1 + 5;

public MyClass(int p1, int p2)
{
x = p1;
y = p2;
}
}

here 2 variables c1 and c2 are constant. So those can be access
without creating object of class 'myclass'. So when i create new object
of class 'myclass' will this new object allocate new memory for
constant c1 and c2. of constant are stored at a time of loading
application only?

please correct me if i am wrong.

thanks in advance.
 
M

Marc Gravell

One of the differences between a "const" and a "static readonly" is
that a "const" will get burnt into the *calling* code, so actually
MyClass.c1 will only be evaluated at *compile time* and will never
reference the class after build. And so it doesn't need to create any
instances. Or even load the assembly (if referenced). More detail
below - however, this is your 3rd (at least) post on this (or related)
subject(s) - why don't you just tell us what you are trying to do?

Using your code and
static void Main()
{
Console.WriteLine(MyClass.c1);
}
compiles to (IL):
..method private hidebysig static void Main() cil managed
{
.entrypoint
.maxstack 8
L_0000: nop
L_0001: ldc.i4.5
L_0002: call void [mscorlib]System.Console::WriteLine(int32)
L_0007: nop
L_0008: ret
}
or reversed back to C#:
private static void Main()
{
Console.WriteLine(5);
}

Marc
 
M

Marc Gravell

Additional to my last post, the consts themselves compile to (IL):
.field public static literal int32 c1 = int32(0x00000005)
.field public static literal int32 c2 = int32(0x0000000A)

I don't know enough about IL to say for sure, but this suggests that
(in addition to the compiler evaluation) they may get treated broadly
along the same rules as static; if this is correct, then static fields
are initialised when first touching the class, so it may consume a
tiny amount of memory when you create the first object, but not
afterwards... but given the volumes - do you have a specific scenario
in mind?

Marc
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top