A Question of Style

C

C# Learner

Should constant class member variables be held like this:

public class Foo
{
public const int ConstVar = 100;
}

Or like this:

public class Foo
{
public int ConstVar
{
get { return 100; }
}
}

Or even:

public class Foo
{
private const int constVar = 100;

public int ConstVar
{
get { return constVar; }
}
}

Since I've been using C# and .NET (about two weeks), I've been using
the first way, i.e. public member variables.

Which is the "correct" way to do this, according to common style?
 
P

Peter Rilling

Either the first or the third would be the accepted definitions of
constants. Your choice of these are really whether your constant is used
only by the class or by the world.

Properties are used, primarily, to access an object's state. Constants are
not state, they are just values.
 
C

C# Learner

Peter Rilling said:
Either the first or the third would be the accepted definitions of
constants. Your choice of these are really whether your constant is used
only by the class or by the world.

In this scenario, the constants are to be used by the world.
Properties are used, primarily, to access an object's state. Constants are
not state, they are just values.

Thanks.
 
L

L#

Should constant class member variables be held like this:

public class Foo
{
public const int ConstVar = 100;
}

Or like this:

public class Foo
{
public int ConstVar
{
get { return 100; }
}
}

Or even:

public class Foo
{
private const int constVar = 100;

public int ConstVar
{
get { return constVar; }
}
}

Since I've been using C# and .NET (about two weeks), I've been using
the first way, i.e. public member variables.

Which is the "correct" way to do this, according to common style?

I would say that the first one is the correct and most performant one.

In the second example you expose the constant as a property, which is
overhead. A property should be used when some extra code is to be
executed before returning the value. In the case of a constant I don't
see the need for this.

In the third example you put the constant private, to hide it. I don't
think there's need to do this, for the samen reason as above. The
constant cannot be changed anymore, private or public.

My 2 cents,

Ludwig
 

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