c# - How to use properties to expose a private array as read-only? -


what following code do?

class myclass {     private int[] myprivates;     public int[] getmyprivates     {       { return myprivates; }     }      protected int[] setmyprivates     {       set { myprivates = value; }     } } 

is there better way of protecting array myprivates? possible make reat-only?

you replace getters , setters property way:

class myclass {     public int[] myvalues { get; protected set; }      public myclass() {         myvalues = new [] {1, 2, 3, 4, 5};     }      public void foo {         foreach (int in myvalues) {             trace.writeline(i.tostring());         }     } }  myotherclass {     myclass myclass;      // ...     void bar {         // can access myclass values in read outside of myclass,          // because of public property, not in write because          // of protected setter.         foreach (int in myclass.myvalues) {             trace.writeline(i.tostring());         }     } } 

you can add pretty protection level less 1 of property getters , setters.


Comments

Popular posts from this blog

c# - how to write client side events functions for the combobox items -

exception - Python, pyPdf OCR error: pyPdf.utils.PdfReadError: EOF marker not found -