Friday, July 19, 2013

Access modifiers in C#

Dot.Net Tutorials

aAccess modifiers
  • ·          Public                          Access not limited
  • ·         Private:                        Access limited to the containing of the class or a type
  • ·         Internal:                       Access limited to the containing of the program only
  • ·         Protected:                    Access limited to the containing class or types derived from the  
  •                                                                                                                    contained class
  • ·         Protected Internal:         Access limited to the program or types derived from the class


----------------------------------------------------------------------------------------------------
Example for public

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace demo_18
{
   public  class test
    {
        public int x;
        public int y;
    }
    class Program
    {
        static void Main(string[] args)
        {
            int result;
            test test1 = new test();
            test1.x = 5;
            test1.y = 10;
            result = test1.x + test1.y;
            Console.WriteLine(result);

        }
    }
}

-- In the above program, class 'test' is initialized with public access modifier, hence that class is accessed by another class i.e., program

So we would get the output as

Output:

15
... press any key to continue



 Private :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace demo_18
{
   private  class test
    {
        public int x;
        public int y;
    }
    class Program
    {
        static void Main(string[] args)
        {
            int result;
            test test1 = new test();
            test1.x = 5;
            test1.y = 10;
            result = test1.x + test1.y;
            Console.WriteLine(result);

        }
    }
}

In  above namespace, demo_18 class test is intizlised with private access modifier, where the accessibility of the test class is limited to the class test only... So above program with produce error..

" Error 1 Elements defined in a namespace cannot be explicitly declared as private, protected, or protected internal D:\Suresh Babu\demo_18\demo_18\Program.cs 8 24 demo_18"


No comments:

Post a Comment