Solved

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

Posted on 2010-09-16
6
685 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
Forrester Webinar: xMatters Delivers 261% ROI

Guest speaker Dean Davison, Forrester Principal Consultant, explains how a Fortune 500 communication company using xMatters found these results: Achieved a 261% ROI, Experienced $753,280 in net present value benefits over 3 years and Reduced MTTR by 91% for tier 1 incidents.

 
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

Instantly Create Instructional Tutorials

Contextual Guidance at the moment of need helps your employees adopt to new software or processes instantly. Boost knowledge retention and employee engagement step-by-step with one easy solution.

Question has a verified solution.

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

The object model of .Net can be overwhelming at times – so overwhelming that quite trivial tasks often take hours of research. In this case, the task at hand was to populate the datagrid from SQL Server database in Visual Studio 2008 Windows applica…
Many of us here at EE write code. Many of us write exceptional code; just as many of us write exception-prone code. As we all should know, exceptions are a mechanism for handling errors which are typically out of our control. From database errors, t…

726 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