Declare a Const Array in C#



In C#, use readonly to declare a const array.

public static readonly string[] a = { "Car", "Motorbike", "Cab" };

In readonly, you can set the value at runtime as well unlike const.

Another alternative of achieving what we saw above −

public ReadOnlyCollection<string> a { get { return new List<string> { "Car", "Motorbike", "Cab" }.AsReadOnly();}}

.NET framework 4.5 brings an improvement to what we saw −

public ReadOnlyCollection<string> a { get; } = new ReadOnlyCollection<string>(
new string[] { "Car", "Motorbike", "Cab" }
);
Updated on: 2020-06-22T09:57:59+05:30

11K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements