Jorge Córdoba
Jorge Córdoba

Reputation: 52123

Const vs protected static readonly

I've got a wrapper class which encapsulates a piece of information that needs to be transmitted as a byte array.

In that way, the class encapsulates the necessary header (with fields like DATA_LENGTH or MESSAGE_TYPE) into the corresponding byte positions. For that I want to define positions and length in constants, for example:

HEADER_DATA_LENGTH_IX = 0;
HEADER_DATA_LENGTH_LENGTH = 2;

which means DATA_LENGTH starts at 0 and takes two bytes.

but so far I'm struggling with making them constants or static readonly fields. Const cannot be protected, therefore I won't be able to derive a new class and change the constants if a use them, on the other way I might declare new constants in the derived class and the use them.

What will be your approach?

Upvotes: 2

Views: 5542

Answers (5)

Oz Radiano
Oz Radiano

Reputation: 789

If you want to change the value of these params in a derived class, you can make them readonly and change them in the constructor of the derived class

I wouldn't make them const anyhow, because they're not...

Upvotes: 5

Brann
Brann

Reputation: 32376

This exact question is answered by the official c# faq on msdn

Upvotes: 1

Robert C. Barth
Robert C. Barth

Reputation: 23315

Create an inner class with the constants. The deriving classes can then later override the inner class and change the constants as necessary.

e.g. base class:

public class Stuff
{
  public class HeaderInformation
  {
    public const int HEADER_DATA_LENGTH_IX = 0;
    public const int  HEADER_DATA_LENGTH_LENGTH = 2;
  }
}

Then the derived class can do this:

public class DerivedStuff : Stuff
{
  public new class HeaderInformation : Stuff.HeaderInformation
  {
    public new const int HEADER_DATA_LENGTH_IX = 10;
  }
}

This way, you have flexibility. In DerivedStuff, the HeaderInformation class has all of the constants in the base Stuff.HeaderInformation class, but can change any of them, or keep the ones it has.

Upvotes: 1

Jason
Jason

Reputation: 15931

The basic difference is when the variable is initialized. 'readonly' is set at initialization, or in the contructor, while 'const' is set at compile time.

I think the big decision is if you want to inherit the class and override the value. If you do, go readonly. Otherwise I don't think it really matters.

readonly C#ref: http://msdn.microsoft.com/en-us/library/acdd6hb7.aspx

const C# ref: http://msdn.microsoft.com/en-us/library/e6w8fe1b.aspx

Upvotes: 4

Gerrie Schenck
Gerrie Schenck

Reputation: 22368

I wouldn't make these constant because they simply aren't constants. When declaring something as const you should ask yourself: can this change? Your message lengths might change one day, so they are better to be made readonly.

Upvotes: 0

Related Questions