Information Technology Reference
In-Depth Information
Inheritance Between Assemblies
So far, I have been declaring derived classes in the same assembly where the base class is
declared. But C# also allows you to derive a class from a base class defined in a different assem-
bly. To do this, the following must be true:
The base class must be declared
public
, so that it can be accessed from outside its assembly.
You must include a reference in your Visual Studio project, to the assembly containing
the base class.
To make it easier to refer to the classes and types in the other assembly, without using their
fully qualified names, place a
using
directive at the top of the source file, with the namespace
containing the classes or types you want to access.
■
Note
Adding a reference to the other assembly and adding a
using
directive are two separate things.
Adding the reference to the other assembly tells the compiler where the required types are defined. Adding
the
using
directive allows you to reference other classes without having to use their fully qualified names.
Chapter 10 covers this in detail.
For example, the following two code segments, from different assemblies, show how easy
it is to inherit a class from another assembly. The first code listing creates an assembly that
contains the declaration of a class called
MyBaseClass
, which has the following characteristics:
It is declared in a source file called
BaseClass.cs
, and inside a namespace declared as
BaseClassNS
.
t is declared
public
, so that it can be accessed from other assemblies.
It contains a single member, a method called
PrintMe
, that just writes out a simple mes-
sage identifying the class.
// Source file name BaseClass.cs
using System;
Namespace containing declaration of base class
↓
namespace BaseClassNS
{
Declare the class public, so it can be seen outside the assembly.
↓
public class MyBaseClass {
public void PrintMe() {
Console.WriteLine("I am MyBaseClass");
}
}
}