Friday, January 11, 2019

Access Modifier In C#


Access Modifier
·         Public - Access in assembly as well as in reference. Default public access modifier enum, Interface
·         Private - Access within the scope of curly braces
·         Protected - Access in base and derived class
·         Internal - Access within the assembly and within the program that contains its declaration.
·         Protected Internal - Can access anywhere in the same assembly  and inherited class in another assembly.

    public class Class1
    {
        //Public - Accessable in this class, drived class, and refrence class
        public string pubString = "Public String";
        //Internal - Accessable within the assembly
        internal string intString = "Internal String";
        //Protected Internal - Accessable in Assembly and derived class
        protected internal string proIntString = "Internal String";
        //Protected - Accessable only in this class and derived class
        protected string proString = "Protected String";
        //Private - Accessable only on this class
        private string pvtString = "Private String";
        public string Method1()
        {
            //Private - Accessable within the Method1
            string pvtPhone = "Private String";
            return pvtPhone;
        }
        //Private Variable will not be accessible outside of Method1() 
    }

public class Class : Class1
    {
        public void Method1(int num1)
        {
            //Public Variable //Accessable in derived class
            Console.Write(pubString);
            //Internal Variable //Accessable in derived class
            Console.Write(intString);
            //Protected Internal Variable  //Accessable in derived class
            Console.Write(proIntString);
            //Protected variable  //Accessable in derived class
            Console.Write(proString);
            //private Variable  //Not Accessable in derived class
            Console.Write(pvtString);

            //Private Variable will not be accessible here
        }
    }

    public class Class2
    {
        //Public Variable //Accessable in derived class
        //Internal Variable //Accessable in derived class
        //Protected Internal Variable  //Accessable in derived class
        Class1 cls = new Class1() { intString = "", proIntString = "", pubString = "" };

        //Private Variable will not be accessible here
    }


No comments: