2

This is a very mysterious behavior.

In my C# ASP.NET project (.asmx web service), constants are assigned in a file Constants.cs.

namespace MyProject
{
    public class MyConstants
    {
        public const string MyString = "Mars";
        public static readonly string[] MyArray = { "Pluto", "Eart", "Venus" };
    }
}

If MyString is called in main unit with

string StrPlanet = MyConstants.MyString;

all works.

If I call ANY element of MyArray and assign it with

string StrPlanet = MyConstants.MyArray[0];

I get this error:

System.IndexOutOfRangeException: Index was outside the bounds of the array.
at MyProject.Constants..cctor()

Where is mistake?

Thanks.

5
  • Please have a look at the answers to Declare a const array and see if any of them provide a good solution for you. Commented Mar 17, 2024 at 15:15
  • The above code seems to work fine. Are you sure you are not looping over the MyConstants.MyArray? Maybe your index is going out of bounds there. Commented Mar 17, 2024 at 15:52
  • Same code in other project works fine. It is very mystery for me. Commented Mar 17, 2024 at 15:55
  • "Same code in other project works fine." - So the code works for you? Commented Mar 17, 2024 at 21:39
  • 1
    @NicoBlu Where is MyProject.Constants..cctor() ? Commented Mar 18, 2024 at 5:53

1 Answer 1

-1

Try making the class static: public static class MyConstants

Also You could try to use List<string> instead.

Sign up to request clarification or add additional context in comments.

2 Comments

Same code works in other twin project... incredibile!
but I bet it not in a asmx class - which is static by default......

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.