- C# Class Library Projects Introduction
- C# Class Library Projects Part 2
In this post we provide the C# source code for a very simple example of a class library, as we continue from the previous post.
Here is where you can store all of your library routines. Our example only has three objects: a welcome string, a time two method, and a times three method. For a client application to use these they must be public. Also, static objects do not need to be instantiated by the calling application.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using static System.Console; namespace ClassLibrary { public class ExternalClass { public string strWelcomeMsg = "Welcome!"; public long TwoTimesInt(int intMyInteger) { return (2 * intMyInteger); } public static long ThreeTimesInt(int intMyInteger) { // static does not need to be instantiated. return (3 * intMyInteger); } } }
Here is what the Solution Explorer looks like. There is an internal class but there is no code in it.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using static System.Console; using ClassLibrary; // this is my class namespace ClientApp { class Program { static void Main(string[] args) { // This app makes use of my C# ClassLibrary // I needed to add a reference to my library // Optionally I can add a using statement as shown above. long longResult; longResult = ExternalClass.ThreeTimesInt(3); WriteLine(longResult); ClassLibrary.ExternalClass myObj = new ClassLibrary.ExternalClass(); longResult = myObj.TwoTimesInt(3); WriteLine(longResult); WriteLine(myObj.strWelcomeMsg); ReadKey(); } } }
Here is a view of the Solution Explorer for the client application.
Here is a view of the Object Browser for the client application.
Making use of external classes in external assemblies is necessary in C# programming and is something you do all the time when you use any of the classes in the .NET Framework.