Monday, December 22, 2008

C# Tutorial For Beginners - Third tutorial

Third tutorial

Now you become to be pretty confident, I guess, so we could start using multiple file, and even a dll ? go into an other directory (or stay in this one, I won't mind) and create 2 file:hello.cs using System;

public class Hello
{
public static void Main()
{
HelloUtil.Echo h = new HelloUtil.Echo("Hello my 1st C# object !");
h.Tell();
}
}
echo.cs using System;

namespace HelloUtil
{
public class Echo
{
string myString;

public Echo(string aString)
{
myString = aString;
}

public void Tell()
{
Console.WriteLine(myString);
}
}
}
Note in hello.cs I have used the syntax "HelloUtil.Echo" it's because Echo is in the namespace HelloUtil, you could have typed (at he start of the file) using HelloUtil and avoid HelloUtil., that's the way namespace work.
Now you could compile both in one .exe with > csc /nologo /out:hello.exe *.csBut it's not my intention, no.Well.(Have you tried?)Let's go building a DLL: > csc /nologo /t:library /out:echo.dll echo.csthat's it (dir will confirm).Now we could use it ... > csc /out:hello.exe /r:echo.dll hello.cs if you typed "hello" it will worked as usual..., but if you delete "echo.dll" the program will now crash: it use the DLL. You could also change Echo.cs, rebuild the DLL and see... that's the advantage of DLL!
You could also put your DLL in the global assembly cache (GAC), and any program would be able to access it, even if the DLL is not in its directory! to put it in the GAC, I sugest you read MS doc but here are the unexplained step:
create your assembly key, create it once and use it for every version. you create it with: sn -k myKeyName.snkthe .snk file should be in your compilation directory (the one where your run csc)
create a strong asssembly title by adding in any .cs source file the following directive at top level: using System.Reflection;
using System.Runtime.CompilerServices;
[assembly: AssemblyTitle("My Lib Title")]
[assembly: AssemblyVersion("1.2.3.4")]
[assembly: AssemblyKeyFile("myKeyName.snk")]

now add it to the GAC: > gacutil.exe /if myLib.dll
By the way, did I tell you ? when I referenced the hello.dll while compiling, remember? csc /out:hello.exe /r:echo.dll hello.cs, it could have been any assembly, even a .exe !!!

No comments: