C# Methods

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • arggg
    New Member
    • Mar 2008
    • 91

    C# Methods

    What exactly is the point of
    private
    public
    protected?

    If you are making the code why not just make it all accesible since you do not need to hide information from yourself?

    Is this mainly for if you create a library that other people using that library cannot obtain information outside of the class you created?

    I'm learning C# so would like to know the correct times that these will need to be used.
  • Plater
    Recognized Expert Expert
    • Apr 2007
    • 7872

    #2
    It all depends. It's considered "good practice" to use them correctly.
    It can also be used to "save you from yourself".

    For instance I have a class with the following:
    Code:
    private string _motd="";
    public string MOTD
    {
       get
       {
          //...
       }
       set
       {
          //...
       }
    }
    And in the getter/setter I control writing the value to disk and reading it from disk (if it's dirty).

    So it would be good of me to hide(private) the _motd variable because I don't want it used.


    Another plus is that if you have a lot of "helper" functions and whatnot for a class, if you mark them private, then when you are using an instance of the class, the intelisense won't go crazy showing you all of your private functions.
    (Well I guess depending on how you do it it will show them anyway, only with a little "lock" on them to denote that they're private)

    Comment

    • r035198x
      MVP
      • Sep 2006
      • 13225

      #3
      Originally posted by arggg
      What exactly is the point of
      private
      public
      protected?

      If you are making the code why not just make it all accesible since you do not need to hide information from yourself?

      Is this mainly for if you create a library that other people using that library cannot obtain information outside of the class you created?

      I'm learning C# so would like to know the correct times that these will need to be used.
      On the other hand, one could ask why you would make a method public if it is only called from within the class that it is defined in.

      Comment

      • arggg
        New Member
        • Mar 2008
        • 91

        #4
        Originally posted by r035198x
        On the other hand, one could ask why you would make a method public if it is only called from within the class that it is defined in.
        Does making a method public use more memory?

        Comment

        Working...