Home > Tutorial for Beginners > Constant arrays | Create constant arrays in C#

Constant arrays | Create constant arrays in C#

Fun behind the constants array, is you can’t create it, because you can apply constant only a local values.  However there is certain work around. Instead of constant array you can declare read only array, but all depends upon the requirement that you have.

In my case I wanted to declare a static array those values should not be reassigned, I can achieve this with the help of static read only array
private static readonly string[]constArray ={  "val1", "val2", "val3"};

Here my array will be initialized first before use.  But it is not advisable.

using System;

namespace myReadOnlyArray
  public class clsReadOnly
     public readonly int[] mygrades = {90, 90, 90};
     private readonly int[] privateGrades = {90, 90, 90};
     private readonly int[] securePrivateGrades = {90, 90, 90};

     // Making the array private does not protect it because it is passed to others.
     public int[] GetPrivateGrades()
        return privateGrades;
     //This method secures the array by cloning it.
     public int[] GetSecurePrivateGrades()
           return (int[])securePrivateGrades.Clone();

     public override string ToString()
        return String.Format("My Grades: {0}, {1}, {2} Private Grades: {3}, {4}, {5}  Secure Grades, {6}, {7}, {8}",
           mygrades[0], mygrades[1], mygrades[2], privateGrades[0], privateGrades[1], privateGrades[2],
           securePrivateGrades[0], securePrivateGrades[1], securePrivateGrades[2]);

Post Comments Below

  1. No comments yet.
  1. No trackbacks yet.