locked
not clear when to use 'friend' vs 'public' (access modifier for routines) RRS feed

  • Question

  • User-1422203677 posted

    I have a website with an asp.net class in the  App_Code folder.

    The class has some routines that have to be accessed by the rest of the project, so I made them PUBLIC.

    But my question is - does this mean that someone could somehow reference my class and call the routines in it from a different project?

    If so, I would want to prevent that.  However, using FRIEND instead of PUBLIC makes it impossible for even my project to access those routines.

    (all routines in this class are SHARED, as well)

    Thanks.

    Monday, January 9, 2017 4:48 PM

Answers

  • User-707554951 posted

    Hi cheahengteong,

    But my question is - does this mean that someone could somehow reference my class and call the routines in it from a different project?

    Yes, it is. If we used public key word on  class and routines. someone one could reference your class and routines form a different project after adding correct reference.

    For your problem. I suggest you could use internal key word on your routines or class.

    The type or member of modified by internal can be accessed by any code in the same assembly, but not from another assembly.

    Sample code for your reference:

    namespace WebApplication1.App_Code
    {
      public  class MyClass
        {
    //use internal key word on routines. internal string GetDateTime() { return DateTime.Now.ToString(); } } }

    If you try to access GetDateTime method, you will get error as below:(

    Error CS0122 'MyClass.GetDateTime()' is inaccessible due to its protection level.

    For the difference between access modifiers. Please check the following links:

    https://msdn.microsoft.com/en-us/library/7c5ka91b.aspx

    http://stackoverflow.com/questions/614818/what-is-the-difference-between-public-private-protected-and-nothing

    Best regards

    Cathy

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, January 10, 2017 8:45 AM