A Question of Style

  • Thread starter Thread starter C# Learner
  • Start date Start date
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?
 
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.
 
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.
 
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
 
Back
Top