150 likes | 297 Vues
This guide explains how to create a new class in C# that aggregates functions from another class, enabling better organization and code reuse. You'll learn how to create and compile a Dynamic Linked Library (DLL) to encapsulate your functions. The instructions cover adding a class to your project, defining functions (including static ones), and building the DLL. It also details how to reference the DLL in your projects and write outputs to a file using the StreamWriter class. This approach enhances modularity and allows for efficient function management in C# applications.
E N D
In a C# program, we can collect all functions in another class and write the new class in a separate file. Then we can create the object of this class and call the functions. If the function is defined as static, then we can directly call this function from class name. However, any function to be called must be public . Add function to a class
Step1. Go to Project Add Class 2 1 Step2. Fill class name which is the same as file name 3
Now we got the empty class as following usingSystem; namespace ConsoleApplication1 { publicclass util { public util() { } } }
Then we Copy functions into class block usingSystem; namespace ConsoleApplication1 { publicclass util { public util() { } public static int[] GetIntegers(){ . . . . . } public static int GetInteger() { . . . . . .} public static string Reverse(string str) { . . . . . . } } } Now it is ready for use
Use Dynamic Linked Library Dynamic linked library is a component that wraps class. Any Dynamic linked library file has extension *.dll. To make dll Step1: Go to File -> New -> Project… 1
3 2 4 Choose C# Choose Class Library Fill DLL name Click OK
Now we got the empty class Library as following usingSystem; namespaceDLLProject { publicclassClass1 { publicClass1() { } } }
Then we Copy Util class (over write Class1) usingSystem; namespaceDLLProject { publicclass util { publicutil() { } public static int[] GetIntegers(){ . . . . . } public static int GetInteger() { . . . . . .} public static string Reverse(string str) { . . . . . . } } } Now we click build to build dll
After build solution, We can see DLLProject.dll in debug folder
Use DLL for program 1 Click Add Reference… 2 Click Browse…
3 Click DLLProject.dll and Click Open
4 Then click OK
We can see DLLProject in reference 5 6 Add using DLLProject at the beginning
Write output to File Setup code FileStream fs = newFileStream("out.txt", FileMode.Create, FileAccess.Write); StreamWriter writer = newStreamWriter(fs); Then we can call Writer.Write(. . .); Writer.WriteLine(. . .); In the end, we must call Writer.Close(); Fs.Close();