The extern keyword eliminates conflicts. Suppose we have 2 class libraries that contain a class
that has the same name.
For example, ClassLibrary1
and ClassLibrary2
both introduce the same class
. With extern, we can use both of those classes at once. This keyword has limited use in most environments.
Create 2 Class Library projects and have them specify the same name class
with no containing namespace. In Visual Studio change the Aliases fields to X and Y.
ClassLibrary1
and ClassLibrary2
DLL files.extern alias X; extern alias Y; using System; class Program { static void Main() { X.A._b = 1; Y.A._b = 2; Console.WriteLine(X.A._b); Console.WriteLine(Y.A._b); } }public class A { public static int _b; }public class A { public static int _b; }1 2
In simple programs, the extern alias syntax is rarely useful. However, if you are developing a huge framework, it would definitely be useful.
This alias directive provides a way for us to specify the location of a class
, not just its name. This means we can use a class
A from many files with no conflicts.