Sealed class with constant.

A

archana

Hi all,

I have created one sealed class having one constant.

Can i access that constant of sealed class without creating object of
that class. If yes will internally new object gets created. Or will it
behave like static member which remains in memory throughotut
applications' lifetime.

Please correct me if i am wrong.

thanks in advance.
 
J

Jianwei Sun

archana said:
Hi all,

I have created one sealed class having one constant.

Can i access that constant of sealed class without creating object of
that class. If yes will internally new object gets created. Or will it
behave like static member which remains in memory throughotut
applications' lifetime.

Please correct me if i am wrong.

thanks in advance.
In C#, Constants are accessed as if they were static fields, although
they cannot use the static keyword. So I believe you should access that
constant of sealed class without creating object of that class.
 
J

Jon Skeet [C# MVP]

archana said:
I have created one sealed class having one constant.

Can i access that constant of sealed class without creating object of
that class.

Yes - constants are inherently static.
If yes will internally new object gets created. Or will it
behave like static member which remains in memory throughotut
applications' lifetime.

It effectively *is* a static member, so no objects will be created.
I seem to recall that there are some subtle differences between a
constant and a normal static member - but in particular the constant
value will be "baked into" any assembly referencing it, so changing the
constant's value in source code requires both the assembly containing
it *and any referencing assemblies* to be recompiled.

Jon
 
J

Jon Shemitz

archana said:
I have created one sealed class having one constant.

Can i access that constant of sealed class without creating object of
that class. If yes will internally new object gets created. Or will it
behave like static member which remains in memory throughotut
applications' lifetime.

If the constant is public, then you can use it from other classes.

Referring to a constant *looks like* referring to a static field, but
the compiled code is different. Referring to a static field reads the
current field value from memory; every reference compiles to object
code that contains a memory address. (If the field changes, the value
you read changes.) Referring to a constant inlines the constant value
in the object code; it's just like using a literal value in your code.

Iow, referring to a constant will not create an instance of the class
(whether sealed or not) and will not allocate storage in the same way
that referring to a static field will.
 

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