Start networking and exchanging professional insights

Register now or log in to join your professional community.

Follow

Who I can declare a protected variable in c#. And can I change it to private or public ? If yes then tell me who?

user-image
Question added by fahad shahzad
Date Posted: 2013/11/15
Daanish Rumani
by Daanish Rumani , Product Manager , Publicis Sapient

Note that only members (varaibles, properties, and methods) of a class can be assigned access specfiers (like public, private, protected). You cannot set access modifiers on local variables.

 

Syntax to delare a member variable:

public class Rectangle

{

    private double length;

    private double breadth;

    protected bool isDrawn;

 

    public Rectangle(double length, double breadth)

    {

        this.length = length;

        this.breadth = breadth;

    }

 

    public double Length

    {

        get { return length; }

    }

 

    public double Breadth

    {

        get { return breadth; }

    }

 

    public virtual void Draw()

    {

        // draw logic goes here

        isDrawn = true;

    }

}

 

In the above example isDrawn is a protected variable. This means that another class working on an object of Rectangle cannot access it. It can only access its public members as shown below:

Rectangle rect = new Rectangle(30.4,12.25);

Console.WriteLine("Length: " + rect.Length); // prints this -> Length:30.4

Console.WriteLine("Breadth: " + rect.Breadth); // prints this -> Breadth:12.25

rect.Draw();

 

Using the following would result in compile time errors:

rect.length; // member length is private

rect.breadth; // member breadth is private

rect.isDrawn; // member isDrawn is protected

 

Protected members of a base class can be accessed by methods in derived classes. Example:

public class DottedLineRectangle : Rectange

{

    public DottedLineRectangle(double length, double breadth)

        : base(length, breadth)

    {

    }

 

    public override void Draw()

    {

        // dotted line rectangle specific drawing logic

        isDrawn = true; // Can access this as it is protected in Rectangle

    }

}

 

As seen above a method (Draw) of the derived class (DottedLineRectangle) can access isDrawn as it is protected in the base class (Rectangle). However private members i.e. length and breadth as they are private.

 

Like for Reactangle, another class working on an object of DottedLineRectangle cannot access the private and protected members of Rectangle (i.e. length, breadth, and isDrawn) but can access the public members of Rectangle as shown below:

DottedLineRectangle dottedLineRect = new DottedLineRectangle(40.0,15.0);

Console.WriteLine("Length: " + dottedLineRect.Length); // prints this -> Length:40.0

Console.WriteLine("Breadth: " + dottedLineRect.Breadth); // prints this -> Breadth:15.0

dottedLineRect.Draw();

 

Now you can change isDrawn and make it public but that would leak it to the outside world as any other class working on an object of Rectangle can modify it. This can cause some of the code in a method of Rectangle to produce undesirable results because it was unexpectedly modified by an outside class.

 

If you make it private then derived class such as DottedLineRectangle would not be able to access it. As a result it would be difficult for DottedLineRectangle to indicate when it was drawn and again cause unexpected behavior because it was not modified/updated when it was expected of DottedLineRectangle to modify/update isDrawn.

 

The bottomline is you follow this rule:

Make all members private first and then change them to be protected or public as required for your logic to work. Ensure that you do not leak members to other classes unless when it is expected.

 

Mahmoud Manaa
by Mahmoud Manaa , Network Engineer , Zain - Kuwait

Firstly thank you for inviting me to Answer , i think Daanish Rumani's Answer is technically Very Good , in the Application side i think that Ahmad Anbari's answer is Nice one

they make me have nothing to say ,Really

Ahmad Anbari
by Ahmad Anbari , Software System Engineer , Continental Jet Services FZCO

Let me first assume your question is: How can I declare a protected variable in C#?

Let me first explain what an access modifier is (private, protected, and public). Let’s say you’re teaching your kids about privacy by saying: the bedroom where I and your mom sleep is accessible privately by me and your mom. The living room, kitchen, and other rooms are accessible by our family members; it is protected from outside intruders. The garden outside is open to public, our family members, neighbors and whoever would like to share. In a similar way we can explain the access modifiers.

Class members, including variables and methods, are declared as private, protected, internal, and public.

Private means the method or the variable is accessible from members in the same class.

Protected means the method or the variable is accessible from members in the same class in addition to those members in the inherited class. Let’s say class A inherit from class B, then all protected members in class B are accessible from class A.

Public, as the name says, is accessible from members and outside methods.

Answer #1: you can declare a protected variable as follow:

class Employee

{

    protected string rank;

}

Answer #2: yes you can as follow:

class Employee

{

    Private string rank;

}

Of course you can’t change an access modifier of a class written by someone else.

 

If someone wrote a class and inside this class he declared a method as protected and you would like to use it, the only way is to inherit from that class.

Zubair Ali
by Zubair Ali , Software Developer III , S&P Global

Go Simple:

  • Make those members of class as protected to which you want to access in child classes in such a way that you would access or modify them remaining inside the child class rather to create a public method in base (this) class and to play with members via that public method. 
  • You can for sure make them private but if you have used them at any of the level in inherited classed then you will encouter a compilation error. :)

Abdul Aziz Ghulam Muhammad
by Abdul Aziz Ghulam Muhammad , Software System Engineer , QSE

 

public class example01 

{

protected  int protected_variable;

private  int private_variable01;

}

 

You cannot change it , if it's written by someone else. But obviously , if you want to change it to public or private yourself and you wrote the class yourself then you can change it. Protected variables can be used in inhertience also for example 

 

public class example02 : example01 

{

private  int private_variable02;

public  int public_variable;

 

public void method01example()

{

this. protected_variable =3600;

// but you cannot access the private variable, that is private_variable01;

// so if you want to change the protected variable to public or private just change the access //modifier where you declared it//See the above two explanations. 

}

}

 

 IF YOU WANT A MORE CLEAR EXAMPLE. JUST COPY PASTE THE CODE BELOW IN A CONSOLE APPLICATION USING C# AND PLAY WITH THE CODE. 

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

namespace Examples

{

    class Program02:Program //inheritence 

    {

  

        public void method02()

        {

            this.abc =100;

            Console.WriteLine(this.abc);

            Console.ReadLine();

        }

    }

    class Program // class Program 

    {

        protected int abc; // You can change it to public or private or what ever you want. 

        static void Main(string[] args)

        {

            Program02 obj2 = new Program02();

            obj2.method02();

       }

 

    }

}

 

 

 

More Questions Like This

Do you need help in adding the right keywords to your CV? Let our CV writing experts help you.