0
using System;

namespace Protected_Specifier
{
  class access
   {
 // String Variable declared as protected
 protected string name;
 protected internal string FirstName;
 public void print()
  {
    Console.WriteLine("\nMy name is " + name);
  }
  public void print1()
  {
    Console.WriteLine("\nMy Firstname is " + FirstName);
  }
   }

 class Program : access // Inherit access class
   {
 static void Main(string[] args)
  {
    //Program p=new Program();
    access a=new access();
    Console.Write("Enter your name:\t");
    a.name = Console.ReadLine(); //error
    a.FirstName = Console.ReadLine();//no error
    a.print();
    a.print1();
    Console.ReadLine();
  }
   }
 }

I have one doubt regarding to inheritance. In this if we use instance of base class it is not working for protected and it is working for protected Internal. Please tell me the reason.....

Kireet
  • 33
  • 8
  • 1
    Can you provide an example of code that doesn't work, but should? It sounds like you are saying you can't access the protected variable from a member method, which should not be the case. – IllusiveBrian Jul 18 '14 at 06:05
  • I think OP is trying to access the `name` variable from `access` class from the Program class.very good question aprt from that compiletime error. – Sudhakar Tillapudi Jul 18 '14 at 06:09
  • @SudhakarTillapudi That's my thought too, but the only thing I can think of that might be the issue is that he is trying to access the (non-static) member variable from a static method in `access`. – IllusiveBrian Jul 18 '14 at 06:10
  • 1
    this helps : http://stackoverflow.com/questions/13683324/cannot-access-protected-member-in-base-class – Sudhakar Tillapudi Jul 18 '14 at 06:11
  • Please for future question specify your expectations clearly. I.e. current `// No Error!!` on the line that causes compile time error is not exactly most obvious way to explain what you mean. – Alexei Levenkov Jul 18 '14 at 06:18

1 Answers1

2

If your question is you can't access name field in base class through base class instance, yes that is how protected modifier works.

It needs an instance of derived type in order to access protected members.

Example taken from msdn

A protected member of a base class is accessible in a derived class only if the access occurs through the derived class type. For example, consider the following code segment:

class A
{
    protected int x = 123;
}

class B : A
{
    static void Main()
    {
        A a = new A();
        B b = new B();

        // Error CS1540, because x can only be accessed by 
        // classes derived from A. 
        // a.x = 10;  

        // OK, because this class derives from A.
        b.x = 10;
    }
}

The statement a.x = 10 generates an error because it is made within the static method Main, and not an instance of class B.

Sriram Sakthivel
  • 72,067
  • 7
  • 111
  • 189