.Net application development specialists
asp.net, c#, vb.net, html, javascript, jquery, html, xhtml, css, oop, design patterns, sql server, mvc and much more
contact: admin@paxium.co.uk

Paxium is the company owned by myself, Dave Amour and used for providing IT contract development services including


  • Application development - Desktop, Web, Services - with Classic ASP, Asp.net WebForms, Asp.net MVC, Asp.net Core
  • Html, Css, JavaScript, jQuery, React, C#, SQL Server, Ado.net, Entity Framework, NHibernate, TDD, WebApi, GIT, IIS
  • Database schema design, implementation & ETL activities
  • Website design and hosting including email hosting
  • Training - typically one to one sessions
  • Reverse Engineering and documentation of undocumented systems
  • Code Reviews
  • Performance Tuning
  • Located in Cannock, Staffordshire
Rugeley Chess Club Buying Butler Cuckooland Katmaid Pet Sitting Services Roland Garros 60 60 Golf cement Technical Conformity Goofy MaggieBears Vacc Track Find Your Smart Phone eBate Taylors Poultry Services Lafarge Rebates System Codemasters Grid Game eBate DOFF

Access Modifiers

C# Modifiers

C# modifiers are used to control access and functionality to things like classes, variables, properties etc.

Examples of modifiers include:

  • public
  • private
  • protected
  • internal
  • abstract
  • const
  • extern
  • new
  • override
  • readonly
  • sealed
  • static
  • virtual
  • volatile
  • void

A sub category of these modifiers are called access modifiers and strictly speaking access modifers only include those keywords which control access such as public, private etc. Keywords like static I don't think are actually termed access modifiers. To my mind though they come under the same category so I tend to lump them together when thinking about them. I think things like static and abstract are actually called just modifiers rather than access modifers but I'm not really sure - if anyone wan't to enlighten me feel free to get in touch - dave@audacs.co.uk

For example in the following class we can see two access modifiers in use. These are private and public and using these changes the scope or access or rules by which things can be accessed or used. 

    class MyClass
    {
        private int height;
 
        public int Height
        {
            get
            {
                return height;
            }
 
            set
            {
                height = value;
            }
        }
    }


In this example, private means that the variable height is only accessible to code within the class. The use of the public modifier makes the variable Height accessible to any code which instantiates an instance of this class eg:  

    class Program
    {
        [STAThread]
        static void Main(string[] args)
        {
            MyClass m = new MyClass();
 
            m.Height = 55;
 
            Console.WriteLine("The value of m.Height is {0}", m.Height);
 
            Console.Read();
        }
    }


When working with access modifers we need to consider that when one is omitted, then a default is used.

To illustrate this, take a look at the following code:

    class MyClass
    {
        int intValue;
 
        public int IntValue
        {
            get
            {
                return intValue;
            }
 
            set
            {
                intValue = value;
            }
        }
 
        public int DoubleIntValue()
        {
            return Double();
        }
    }


Note that the DoubleIntValue is public. If we omitted the public modifier then this would default to private and would therefore no longer be publically accessible.

Other modifers don't control access as in public or private but they define rules for use. For example the abstract modifier when used with a class means that you cannot create an instance of this class - you can only create instances of classes which inherit from this. In other words you would use the abstract modifier when you had a class which was only inteneded to be used as a base class.

Ok so hopefully you get the general idea of how these modifers work. There are quite a few of them and they can be applied to different things - classes, properties, members etc so what we really need is a table listing them all and how they work with different types of things:

Before we look at this table, there is an important and subtle issue we need to be aware of as follows:

If we have a private or protected class member (variable or method) then when we create an instance of this class then of course these will not be available to the instance. However if you create an instance of a class from within the same class then these private and protected members DO become accessible as follows:

using System; 

namespace Mods
{
    class Animal
    {
        private int legs = 4;
 
        public void MyMethod()
        {
            Animal dog = new Animal();
 
            Console.WriteLine(dog.legs);
 
            Console.Read();
 
        }
    }
 
    class Program
    {
        [STAThread]
        static void Main(string[] args)
        {
            Animal a = new Animal();
            a.MyMethod();
        }
    }
}


The reason for this is that when we say that private restricts access to the class - we mean the type not the instance - this is the way OOP is defined.

To quote AlexFM who helped me with this on Experts Exchange:

To understand this better think about compile time and run time concept. Access modifiers are defined for compiler and handled at compile time. Private member is member accessable only from the code of this class - this restriction is tested by compiler when it converts source code to executable file. They are designed to hide internal class implementation from the programmer who uses a class. Access modifiers don't exist at run time. 

Modifier Useage
 
public

Class

No restrictions. Classes marked public are visible to any method of any class. It is a common misconception that this is the default when no access modifier is supplied for a class definition. This is untrue and in fact the default is internal. Unless you are working with multiple projects/assemblies then this will behave just like public so maybe this is where the confusion arises?

Members variables

If a member variable is declared as public it is accessible from code within the class as well as any code instantiating an instance of the class.

Members methods

If a method is declared public it is accessible from any code creating instances of that class or using its static methods, if that method is also declared static. Of course it is also available from code within the class itself.

Enum

private

Class

A nested class that can only be accessed inside the class in which it is defined. This is the only way private can be used with a class definition.

Members variables

The variables are only accessible from code within the class itself.

Members methods

Methods are only accessible in the class in which they are defined

Enum

protected

Class

I believe the only time you can user protected with a Class is with a nested class. A nested class would be used when we have a class which is only really used by another class. Lets say we have a Person class and within there we have a Credit Card class. Not a great example I know but I can't think of anything else! Well if we make the Credit Card class protected then any classes which inherit from Person will also inherit this nested class.

Members variables

This means the variable is accessible in the type in which it is defined, and in derived types of that type.

Members methods

This means the method is accessible in the type in which it is defined, and in derived types of that type.

Enum

internal

Class

When classes are declared as internal, which is also the default when nothing is specified, then classes are visible only to any other code within the same assembly. Any other code which references this assembly will not be able to see the class.

Members variables

If you use internal on a member variable - one that you would normally have as public, private, protecetd etc - then this behaves like a public variable but only visible to other code within the same assembly. If other code references this assembly then the variable will not be visible.

Members methods

If you use internal on a member method - one that you would normally have as public, private, protecetd etc - then this behaves like a public variable but only visible to other code within the same assembly. If other code references this assembly then the variable will not be visible.

Enum

abstract

Class

When a class is modified with the abstract keyword then this means that an instance of this class cannot be created. Only classes which inherit this can be instantiated. Because of this, it is not possible to use the sealed modifier with the abstract modifier. Abstract classes have simillarities with interfaces - a big difference though is that abstract classes can contain actual code where interfaces cannot.

Members variables

The abstract modifer cannot be used on fields but can be used on properties. When it is used on a property then the containing class must itself be abstract. So when we have a class which inherits an abstract class which has an abstract property then the abstract property must be overridden. See the example below where the property is only defined as having a get and not a set and so this and only this is what must be overridden.

Members methods

When a method is marked as abstract then the method must belong to a class which is marked as abstract. Of course that class can have other methods which are not abstract. Abstract methods contain no code and must be overriden in inheriting classses. When overridden then of course the override keyword is used. 
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace Audacs.ConsoleApp
{
    public abstract class Animal
    {
        public abstract int Legs
        {
            get;
        }
    }
 
    public class Bird : Animal
    {
        private const int legs = 2;
 
        public override int Legs
        {
            get
            {
                return legs;
            }
        }
    }
 
    class Program
    {
        public static void Main()
        {
            Bird sparrow = new Bird();
 
            Console.Write("The sparrow has {0} legs", sparrow.Legs);
 
            Console.Read();
        }
    }
}

Note also that the get contains no body.

Enum

const

Class

Not applicable

Members variables

const actually only applies to fields and not properties. The fields can be either private or public eg:
 
public class Bird
{
    private const int legs = 2;
 
    public const int Wings = 2;
}

Note that when const is used then the field must be initialised when it is declared.

Members methods

Not applicable

Enum

Not applicable