Solved

How do you const-ify a string array literal in C# ?

Posted on 2010-09-16
6
676 Views
Last Modified: 2013-12-16
In C# I'd like to specify that an array with it's literal values cannot be modified in any way.  Is this possible in C#?

Using readonly keyword doesn't seem to be complete...  the seal keyword doesn't compile (only for classes)... and the const keyword doesn't compile because arrays are reference types.
public const string[] BANDS = new string[] {"Rush", "Banco De Gaia"};

Open in new window

0
Comment
Question by:ZuZuPetals
  • 3
  • 2
6 Comments
 
LVL 8

Expert Comment

by:Gururaj Badam
ID: 33693515
try this
public class Class

    {

        private IList Bands;



        public Class()

        {

            Bands = ArrayList.ReadOnly(new string[] { "Rush", "Banco De Gaia" });

        }

    }Tr

Open in new window

0
 
LVL 8

Accepted Solution

by:
Gururaj Badam earned 500 total points
ID: 33693541
Sorry forgot mention that string[] can be assigned to IList reference and hence the above code will not introduce any unwanted changes to your existing code.

IList Bands = new string[] { "Rush", "Banco De Gaia" };  // No compile error

And hence

IList Bands = ArrayList.ReadOnly(new string[] { "Rush", "Banco De Gaia" });  // Should work the same way as above
0
 
LVL 13

Expert Comment

by:Naman Goel
ID: 33693946
yes can use ArrayList.ReadOnly(IList) method as suggested by novice_novice

as it is internally creates ReadOnlyList

   public static IList ReadOnly(IList list)
{    
if (list == null)
 {
 throw new ArgumentNullException("list");
    }    
return new ReadOnlyList(list);
}


and better than that you can use ReadOnlyCollection<T> Class

ReadOnlyCollection<string> BANDS = new ReadOnlyCollection<string>( new string[] {"Rush", "Banco De Gaia"});



0
3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

 
LVL 2

Author Comment

by:ZuZuPetals
ID: 33694457
Golly.

I appreciate the solution but it's syntactic molasses.

I wish .Net inventors had just let us add the keyword const or perhaps a new keyword like fixed (to get around the underlying technical reasons--reference, etc.) to make the string values immutable.
0
 
LVL 13

Expert Comment

by:Naman Goel
ID: 33694592
Yes, even I will be happy to see this type of implementation but for now  

ReadOnlyCollection is the best way to achieve this.

http://msdn.microsoft.com/en-us/library/ms132474.aspx
0
 
LVL 8

Expert Comment

by:Gururaj Badam
ID: 33694639
C# does not support Constant Array (Contents are constants), You will have to live with it.

The choice whether List over Collection should fit your needs not fancy.
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In my previous article (http://www.experts-exchange.com/Programming/Languages/.NET/.NET_Framework_3.x/A_4362-Serialization-in-NET-1.html) we saw the basics of serialization and how types/objects can be serialized to Binary format. In this blog we wi…
This article describes relatively difficult and non-obvious issues that are likely to arise when creating COM class in Visual Studio and deploying it by professional MSI-authoring tools. It is assumed that the reader is already familiar with the cla…
A short film showing how OnPage and Connectwise integration works.
With Secure Portal Encryption, the recipient is sent a link to their email address directing them to the email laundry delivery page. From there, the recipient will be required to enter a user name and password to enter the page. Once the recipient …

932 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now