Article View: borland.public.csharpbuilder.language.csharp
Article #158Re: True Constants in C# ?
From: Marc Rohloff TeamB
Date: Wed, 30 Aug 2006 00:27
Date: Wed, 30 Aug 2006 00:27
36 lines
2278 bytes
2278 bytes
On Mon, 28 Aug 2006 22:47:18 -0400, Dr. Bob Miller wrote:
> In most object oriented languages, there are obvious ways of creating true
> constants that have a lifetime that is the lifetime of the whole
> application, live outside of any object, are visible by code in other files,
> and usable within multiple objects.
I hate to contradict what has already been suggested but you don't
want to use static or readonly, you want to use the 'const' keyword.
'const' has an advantage over static readonly fields as the values are
calculated at compile time. eg.
class MyClass
{
public int x;
public static readonly int c2 = 5;
}
public static void Main()
{
Console.WriteLine("c1 = {0}, c2 = {1}", MyClass.c1, MyClass.c2
Console.WriteLine("c1*4 = {0}, c2*4 = {1}", MyClass.c1*4, MyClass.c2*4
);
In the second WriteLine the compiler will pre calculate the value 20,
for c2 it will perform the calculation on each execution.
A couple of points 'const' fields are automatically static and
read-only.
'readonly' fields aren't always.
--
Marc Rohloff [TeamB]
marc rohloff -at- myrealbox -dot- com
Technical Details
Message-ID:
<1j04hi3wixlhw.dlg@dlg.marcrohloff.com>Path:
arc1-ca.pugleaf.net!g2news2.google.com!news1.google.com!news.maxwell.syr.edu!newsfeed00.sul.t-online.de!newsfeed01.sul.t-online.de!t-online.de!newsgroups.borland.com!not-for-mailReferences:
<44f3aab7$1@newsgroups.borland.com>Show Full Headers
Complete Article Headers
X-Google-Thread: 1efe35,1326b8d2515daa80 X-Google-Attributes: gid1efe35,public X-Google-Language: ENGLISH,ASCII-7-bit From: "Marc Rohloff [TeamB]" <"on request"> Subject: Re: True Constants in C# ? Newsgroups: borland.public.csharpbuilder.language.csharp User-Agent: 40tude_Dialog/2.0.15.1 MIME-Version: 1.0 Content-Type: text/plain; charset="us-ascii" Content-Transfer-Encoding: 7bit References: <44f3aab7$1@newsgroups.borland.com> Date: Tue, 29 Aug 2006 20:27:17 -0400 Message-ID: <1j04hi3wixlhw.dlg@dlg.marcrohloff.com> X-Face: "huzh55Xi]!ZNni78>a*5+).`SK?<^q2MlHk-C]Z2M9T@\J5ZCB$95Ey+s"XQuhGFA[eutZ :0^AV!Q;t>gE`1-=8d;HZ6~*o1dH<X9\b$!|(}+I'!Xq)@3Op}%0ArW&nf'Qh*EwR X-Antivirus: avast! (VPS 0635-1, 08/28/2006), Outbound message X-Antivirus-Status: Clean NNTP-Posting-Host: 65.31.1.121 X-Trace: newsgroups.borland.com 1156897633 65.31.1.121 (29 Aug 2006 17:27:13 -0700) Lines: 36 X-Authenticated-User: mrohloff Path: arc1-ca.pugleaf.net!g2news2.google.com!news1.google.com!news.maxwell.syr.edu!newsfeed00.sul.t-online.de!newsfeed01.sul.t-online.de!t-online.de!newsgroups.borland.com!not-for-mail