Problem with assigning the result of [string].IndexOf into a const int?

D

Duncan Smith

Having a cpp background I'm curious why I can't do the following:

const int openElementPosition = strXmlLine.IndexOf("<RacingNumber");

without getting the following error:

Error 1 The expression being assigned to 'closeElementPosition' must
be constant

If I drop the const then everything is fine, but I don't ever want to
change the value of openElementPosition so it would be better/safer as
a const. Assuming IndexOf returns a scalar integer value, why
shouldn't I be free to store it in a const variable?

Confused,

Duncan.
 
L

Lebesgue

try to specify the field as readonly instead of const - these can be set
once with a non-constant value
 
D

Duncan Smith

try to specify the field as readonly instead of const - these can be set
once with a non-constant value

Apparently this only works on member variables and not variables local
to the method. For if I try:

readonly int openElementPosition =
strXmlLine.IndexOf("<RacingNumber");

I get the error:

Error 2 The modifier 'readonly' is not valid for this item
 
L

Lebesgue

You can not give any specifiers to local variables (in-method) in C#. It's
up to you to know what you are doing in your method.
 
D

Duncan Smith

You can not give any specifiers to local variables (in-method) in C#. It's
up to you to know what you are doing in your method.

Groan! Remind me to check in again on C# in another three years...

Thanks anyway.

Duncan.
 

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