Creating a C# Assembly
It's pretty easy to create an assembly from scratch. In Microsoft Visual C# 2008 Express Edition, choose File > New Project, select Class Library as the project type, enter a name (if you want a non-default name), and click OK. The wizard will chug away and then create your brand-new class library. When it's done, the editor will open the C# file that represents the entry point for the assembly. For example, if I create a class library and accept the defaults, when the wizard finishes, the IDE should look something like Figure 1.
Figure 1 A class library, successfully created.
Notice the C# class (called Class1) in Figure 1. This class is part of the automatically generated namespace called ClassLibrary1.
You've got all of the infrastructure you need to start writing your assembly, so let's insert some code, as illustrated in Listing 1.
Listing 1The assembly code.
using System; using System.IO; using System.Management; using System.Collections.Generic; using System.Linq; using System.Text; namespace ClassLibrary1 { public class Class1 { public void dumpPlatformDetails() { String nl = Environment.NewLine; System.Console.WriteLine("HasShutdownStarted: " + Environment.HasShutdownStarted); System.Console.WriteLine("MachineName: " + Environment.MachineName); System.Console.WriteLine("OSVersion: " + Environment.OSVersion.ToString()); System.Console.WriteLine("TickCount: " + Environment.TickCount); System.Console.WriteLine("UserDomainName: " + Environment.UserDomainName); System.Console.WriteLine("UserInteractive: " + Environment.UserInteractive); System.Console.WriteLine("UserName: " + Environment.UserName); System.Console.WriteLine("OS Version: " + Environment.Version.ToString()); System.Console.WriteLine("WorkingSet: " + Environment.WorkingSet); String[] drives = Environment.GetLogicalDrives(); System.Console.WriteLine("Logical Drives: " + String.Join(", ", drives)); } } }
In Listing 1, I've added a few extra namespaces and a single method called dumpPlatformDetails(). What does this method do? As you might have gleaned from the code and the method name, it simply extracts and displays some interesting details about the execution platform.
Now let's see about calling the code in Listing 1. One thing about the model of using .NET assemblies is that it's an example of the separation of concerns. The assembly is, in effect, a kind of container for the shared code; to access that code, we need to create a client program.