Saturday, February 21, 2015

C# : Access Modifiers

C# has five different access modifiers (arranged from least to most restrictive):
  • public
  • protected internal
  • internal
  • protected
  • private

Given an access modifier, whether or not you can access it depends on two things:
  • Is it being accessed within the same assembly?
  • Is it being accessed within a derived type?
Try-It-Yourself
Here's a couple of simple examples you can use to become more familiar with C#'s access modifiers.
Just change the access modifier of the BaseKlass' str field to the one you want to try out.
Same Assembly
using System;

public class BaseKlass {
  public string str = "Hello World";

  public BaseKlass() {
    Console.WriteLine("(base) str = " + str);
  }
}

public class DerivedKlass : BaseKlass {

  public DerivedKlass() { 
    Console.WriteLine("(derived) str = " + str);
  }
}

public class Other {
  public static void Main() {
    BaseKlass baseKlass = new BaseKlass();
    Console.WriteLine("baseKlass.str = " + baseKlass.str);

    Console.WriteLine();

    DerivedKlass derivedKlass = new DerivedKlass();
    Console.WriteLine("derivedKlass.str = " + derivedKlass.str);
  }
}
Different Assembly
// file: BaseKlass.cs
using System;

public class BaseKlass {
  public string str = "Hello World";

  public BaseKlass() {
    Console.WriteLine("(base) str = " + str);
  }
}
Compile the above with the target switch.
csc /target:library BaseKlass.cs
This will produce a BaseKlass.dll
// file: DerivedKlass.cs
using System;

public class DerivedKlass : BaseKlass {

  public DerivedKlass() { 
    Console.WriteLine("(derived) str = " + str);
  }
}

public class Other {
  public static void Main() {
    BaseKlass baseKlass = new BaseKlass();
    Console.WriteLine("baseKlass.str = " + baseKlass.str);

    Console.WriteLine();

    DerivedKlass derivedKlass = new DerivedKlass();
    Console.WriteLine("derivedKlass.str = " + derivedKlass.str);
  }
}
Compile the above with reference switch.
csc /reference:BaseKlass.dll DerivedKlass.cs
Result
The cells marked within X indicate the class member is accessible.


Same Assembly
Different Assembly

Derived Type
Not-Derived
Derived Type
Not-Derived
public
X
X
X
X
protected internal
X
X
X

internal
X
X


protected
X

X

private




No comments:

Post a Comment