“Read only” Property Accessor in C#

前端 未结 8 1598
遇见更好的自我
遇见更好的自我 2021-02-12 14:08

I have the following class:

class SampleClass
{
   private ArrayList mMyList;

   SampleClass()
   {
       // Initialize mMyList
   }

   public ArrayList MyLis         


        
8条回答
  •  [愿得一人]
    2021-02-12 15:02

    Just make the property as Sealed (or NotInheritable in VB.NET) and readonly, like this:

       public sealed readonly ArrayList MyList
       {
           get { return mMyList;}
       }
    

    Also don't forget to make the backing field as readonly:

       private readonly ArrayList mMyList;
    

    But in order to initialize the value of mMyList, you must initialize it ONLY in the constructor, as in this example:

    public SampleClass()
    {
       // Initialize mMyList
       mMyList = new ArrayList();
    }
    

提交回复
热议问题