Sei sulla pagina 1di 16

Functions

A function allows you to encapsulate a piece of code and call it from other parts of your code. You may very soon run into a situation where you need to repeat a piece of code, from multiple places, and this is where functions come in. In C#, they are basically declared like this:
<visibility> <return type> <name>(<parameters>) { <function code> }

To call a function, you simply write its name, an open parenthesis, then parameters, if any, and then a closing parenthesis, like this:
DoStuff();

Here is an example of our DoStuff() function:


public void DoStuff() { Console.WriteLine("I'm doing something..."); }

The first part, public, is the visibility, and is optional. If you don't define any, then the function will be private. More about that later on. Next is the type to return. It could be any valid type in C#, or as we have done it here, void. A void means that this function returns absolutely nothing. Also, this function takes no parameters, as you can see from the empty set of parentheses, so it's actually just a tad bit boring. Let's change that:
public int AddNumbers(int number1, int number2) { int result = number1 + number2; return result; }

We've changed almost everything. The function now returns an integer, it takes two parameters (both integers), and instead of outputting something, it makes a calculation and then returns the result. This means that we can add two numbers from various places in our code, simply by calling this function, instead of having to write the calculation code each time. While we don't save that much time and effort in this small example, you better believe that you will learn to love functions, the more you use C#. This function is called like this:
int result = AddNumbers(10, 5); Console.WriteLine(result);

As mentioned, this function actually returns something, and it has to, because we told C# that it's supposed to do so. When declaring anything else than void as a return type, we are forcing our self to return something. You can try removing the return line from the example above, and see the compiler complain: 'AddNumbers(int, int)': not all code paths return a value The compiler is reminding us that we have a function which doesn't return something, although we promised. And the compiler is pretty clever! Instead of removing the line, try something like this:
public int AddNumbers(int number1, int number2)

{ int result = number1 + number2; if(result > 10) { return result; } }

You will see the exact same error - but why? Because there is no guarantee that our if statement will evaluate to true and the return line being executed. You can solve this by having a second, default like return statement in the end:
public int AddNumbers(int number1, int number2) { int result = number1 + number2; if(result > 10) { return result; } return 0; }

This will fix the problem we created for our self, and it will also show you that we can have more than one return statement in our function. As soon as a return statement is reached, the function is left and no more code in it is executed. In this case, it means that as long as the result is higher than 10, the "return 0" is never reached. Having problems with this chapter? Ask in our forums!

C# Tutorial For Beginners


07. Dec, 2006 by admin 6 Comments

So you just install .NET framework and want to start using C# but you don't know where to start ? well First you could download this complete tutorial here. There is a directory for each tutorial with a build.bat to build the tutorial and a run.bat to run the program. And every example is already compiled, just in case
First tutorial

You should first open a DOS command shell. (If you don't know what it is, clic on the Start menu then run (at the bottom) and type, in the text field: "cmd".

exercise: there is an easiest way to do that, try to find it.) You should begin to work in an empty directory for this. let call it "C:\learncs". Type in the shell: > md C:\learncs > cd C:\learncs > C: Now you should create your first C# program, type "notepad hello.cs" and type (in the notepad) using System; public class Hello { public static void Main() { Console.WriteLine("Hello C# World } } ");

the using keyword just let you write Console at line 7, instead of System.Console. It's very usefull shortcut when you use a lot of "class" define in System. Save the file. Now you could compile. Type in the DOS Shell again and type:
csc /nologo /out:hello.exe hello.cs

You probaly have some errors, correct them, compile again, and now you have a working hello.exe program type hello, see
Second tutorial

Congratulation you've done the most difficult, let increase the difficulty. and create an object instance. in the DOS shell create a new directory: > md ..\learncs2 > cd ..\learncs2 > notepad hello.cs and then type, in the notepad using System; public class Echo { string myString;

public Echo(string aString) { myString = aString; } public void Tell() { Console.WriteLine(myString); } } public class Hello { public static void Main() { Echo h = new Echo("Hello my 1st C# object !"); h.Tell(); } } Wouah, 25 lines! That's a program! Save it, compile it, run it What happened? csc look for a Main() function in your program, it should find one (and only one) and it will be the entry point of your program. In this tutorial we create 2 classes: Echo & Hello. In the Main() method you create an Echo object (an instance of the Echo class) with the keyword new Then we called the instance method "Tell()". the upper case letter on class or Method is just a MS convention, do as it pleased you. public is a visibility access, method wich are not public could not be seen from outside, there is also other visibility keywords, to learn more, clic on Start menu-> Programs -> Microsoft .NET Framework SDK -> Documentation there is a search window, an index window, etc try to learn more about public private protected.
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 *.cs

But it's not my intention, no. Well. (Have you tried?) Let's go building a DLL:
> csc /nologo /t:library /out:echo.dll echo.cs that'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:
1. create your assembly key, create it once and use it for every version. you create it with:
sn -k myKeyName.snk

the .snk file should be in your compilation directory (the one where your run csc) 2. 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")] 3. 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 !!!
Fourth tutorial

Congratulation you would soon be able to hack CsGL but there is one last step you should understand : interop (with C code). You will need a C compiler, I advise gcc for windows called MinGW, it's free, it's good, it's GCC! We will create 3 file: echo.c #include <stdio.h> #define DLLOBJECT __declspec(dllexport) DLLOBJECT void writeln(char* s) { printf("%s\ n", s); } echo.cs using System; using System.Runtime.InteropServices; namespace HelloUtil { public class Echo

{ [DllImport("echo.native.dll", CallingConvention=CallingConvention.Cdecl)] static extern void writeln(string s); string myString; public Echo(string aString) { myString = aString; } public void Tell() { writeln(myString); } } } hello.cs using System; using HelloUtil; public class Hello { public static void Main() { Echo h = new Echo("Hello my 1st interop code !"); h.Tell(); } } Hehe, here you discover a completly new thing, Attribute. "[DllImport(.." is an attribute. You could tag any method/field/class with any number of attribute. They generate extra information that could be used by anyone who could understand them. This DllImport attribute is understand by the compiler and told him that the function below is in fact in a DLL whose name is "echo.native.dll". I add a calling convention parameter as the default .NET calling convention is __stdcall whereas, in C, it's __cdecl. By the way, if you look for DllImport in the documentation, look for DllImportAttribute, because you remove "Attribute" to attribute classname when using them, it's like this. And now let's compile this! > csc /nologo /t:library /out:echo.dll echo.cs > csc /nologo /out:hello.exe /r:echo.dll hello.cs

> > rem "if the following line don't work, read bellow.." > gcc -shared -o echo.native.dll echo.c > strip echo.native.dll the 2 last line (the gcc & strip command) are for building the "C-DLL". If they don't work maybe gcc is not in a directory listed in your path environment variable ? check with:
%lt; echo %PATH%

Well it's probably not,anyway, so type, assumin mingc is in C:\MinGW:


set PATH=C:\MinGW;%PATH%

And try again you sure it's not a syntax error ? If it compile test it now: hello Great isn't it ? Now I should admit I didn't tell you all the truth. echo.dll and echo.native.dll are not the same kind of DLL. It's not just the language (C / C#) the C one is a plain executable full of, probably, x86 instruction, whereas the C# one is what MS call a portable executable.. anyway they are different. If you install echo.dll in the GAC it wont work because it won't find echo.native.dll except if you put in into the PATH (like C:\Windows\System32). In the same manner when you add the reference in VS.NET echo.native.dll is overlooked and your program won't work. So either put the native one in your path or copy it in the debug/release directory of VS.NET. Or do everything by hand (makefile? build.bat?) and put all your dll in you build directory, and everything work fine..
And now..

Well, first forget about notepad. It's good to learn, but so painfull to use regularly.., try to find real developer friendly small text editor (like JFE) or a complete IDE like SharpDevelop. Now you are ready to understand, I could tell you all the truth: csgl.dll is a C# assembly and csgl.native.dll is just a dll compiled by GCC, upon which csgl.dll depends Chapter 1: About Microsoft. NET

All About Microsoft. NET Microsoft. NET is one of the latest and new technologies introduced by Microsoft Corporation. Nowadays we use to connect to the internet using a computer and a remote computer responses via a web page and a collection of web pages are called as Web Sites. The Concept in .NET is that these websites can integrate with other sites and services using Standard Protocols like HTTP. Microsoft .NET Platform comprises of four core components such as:

y y y

NET Building Block Services such as file storage, calendar called Passport. NET NET Device Software which will run on latest Internet Devices like Mobile Phones. NET user experience such as integrating this technology to user created documents (integrates with XML). For example if you code XML via a .NET Language like C#, it will automatically create XML document. NET infrastructure which includes NET Framework (Common Language Runtime & .NET Framework Class Libraries) Microsoft Visual Studio.NET such as Visual Basic.NET ,Visual C++.NET etc NET Enterprise Servers and Microsoft Windows. NET.

We can build robust, scalable, distributed applications with the help of .NET and the part that helps us to develop these applications is called the .NET Framework. The .NET Framework contains Common Language Runtime (CLR) and the .NET Framework class libraries also called as Base Class Libraries. All the .NET languages (like C-sharp, VisualBasic.NET, Visual C++. NET etc) have the .NET Framework class libraries built into them. The .NET class Libraries also supports File I/O, database operations, XML (Extensible Markup Language) and SOAP (Simple Object Access Protocol). For example you can develop XML Pages by using C-sharp language. When someone talks about .NET development, then you should understand that they are talking about .NET Framework. It includes a Runtime environment and a set of Class Libraries which is being used by a new language called C-sharp abbreviated as C# (more or less similar to C/C++/Java family of languages) and all other .NET Languages. Simply speaking C-sharp is a new language for developing custom solutions for Microsoft's .NET Platform. The runtime which we discussed just now is also used by VisualStudio.NET. Visual Studio.NET Provides us with a visual environment to design and develop .NET Applications. Every language in VisualStudio.NET uses this runtime to execute its applications. Moreover these languages compiles its source code into an intermediate language upon compilation. Hence you can very well use a module written using C-sharp in a Visual Basic Application. For example you can design a user interface with Visual Basic.NET and write a DLL function using C-sharp. .NET Framework Process

Terms Associated with Microsoft .NET Common Language Runtime Common Language Runtime also called CLR Provides a universal execution engine for developers code. It generates SOAP when it makes remote procedure calls. CLR is independent and is provided as part of the .NET Framework. The main features of CLR are as follows: 1. 2. 3. Managed Code Automatic application installation Memory Management

4. 5.

Automatic Garbage Collection Very high level of Security while executing

.NET Framework Class Libraries These class libraries works with any language under the common language runtime environment. It includes Visual Studio.NET, C-Sharp. Therefore if you are familiar with one .NET language then you can easily migrate to other .NET Languages. The figure given below shows the .NET Framework hierarchy

Note: 1. All namespaces should have to be called in your Program by applying the keyword using. For example if your programs needs to call System namespace, then it should be applied in the program as using System. 2. Classes cannot be called along with the using directive. 3. The using directive applies only to namespaces, just like importing packages in Java. Hence the following code will result in compilation error, using System.Console. However you can create an alias like the following using mysys = System.Console. Then you have to apply the alias in your program as follows mysys.writeLine("Hello C#"); Common Language Specification (CLS) It is a set of rules that a language compiler must adhere to in order to create .NET Applications that run in the CLR. If you are going to create a compiler for .NET, you have to adhere to the rules enumerated in the common language specification and this enables us to create a club of CLS compliant languages. Each such compiler will have the following features: y y Complete access to .NET Framework hierarchy High level of interoperability with other compliant languages like Visual Basic. NET etc.

For example a Visual Basic class can inherit from a C# Class. You should note that the syntaxes and other programming structures differ from each of these languages. The only difference is that a developer well versed with a language such as C-sharp can easily program in Visual Basic.NET or Visual C++.NET without investing a lot or spending too long to learn a new language.

Chapter 2: Begin C-Sharp Programming


Getting Started with C-sharp First of all let me welcome you to the world of this new programming language. I hope you will have a basic idea about Object Oriented Programming languages because many

languages like Java, C++ have come by the past 5 years. However there will be no difficulty in learning this language if you are a fresher, because this tutorial and the coming ones will explain all the concepts and features right from the beginning. Wherever required I explained the features involved in C-sharp by comparing them with Java. This will ensure smooth progress for experienced Programmers. I recommend you to install the appropriate software's outlined in the next section before learning this new language. Basic Requirements needed to begin C-sharp Programming 1. 2. .NET Framework Software Development Kit and An Editor (like Notepad or DOS Editor) to write source codes.

Optional Requirements: 1. Visual C#. NET or 2. Visual C++ 6.0 included with VisualStudio 6.0 Installing .NET Framework SDK As a first step you should install .NET SDK on your computer to begin C-sharp Programming. It can be downloaded from the Microsoft's Website. It is also available with almost all the popular computing magazine CD'S. It also comes with the complete documentation in the form of HTML Help. At the time of this writing only beta version of the kit is available. This kit enables you to compile & execute the source code in C#, Visual Basic by using its built-in Command line Compiler (csc and vbc) and runtime Just In Time (JIT) Compiler. This is similar to Java Compiler (javac) and Java Interpreter (java) included with Java Development Kit. You can also develop applications with C-sharp and Visual Basic by using Visual Studio.NET languages like Visual C#.NET and Visual Basic.NET. This will help you to develop windows based applications easily and with limited effort because you don't have to devote too much time in designing the user interface (Usage of WinForms). The only work left for you to do is to write the codings appropriately as per the .NET Standards. About the Editors Notepad is the best choice among developers using .NET SDK to develop C# applications. However it is not the most suitable editor since it does not support syntax coloring, code numberings etc. Developers can use Visual C++ 6.0 included with Visual Studio 6.0. However they should make some tweaking in the registry before using the same. It supports syntax colorings and other features such as finding line numbers (Ctrl+G). However it is dangerous for a new user to make changes in registry. Hence only advanced and experienced users can be able to use Visual Studio 6.0 for developing C#. It is not possible to compile and execute the applications from the Visual C++ 6.0 Environment. Hence there is not much use except some of the features listed above.

VisualStudio.NET provides all the integrated tools and wizards for creating C# and Visual Basic applications. It also supports features such as intellisense, Dynamic help. Moreover you can compile and execute your applications from the IDE itself. Hence in order to experience the power of developing the .NET applications, you should try VisualStudio.NET. Many Third Party editors are now available either from magazine's CD'S or can be downloaded from the internet. However it is up to you to decide upon which editor to use. I recommend you to try one common editor and learn the language in full.

Chapter 3: Your First Hello C# Program


Getting Started with Hello C-Sharp After understanding the fundamentals of .NET and its Structure, let us now move on to look at a classic Hello C# Program. As I mentioned in the previous tutorial, you can use any text editor as per your Convenience. Listing 3.1 gives the coding for this simple Hello C# Program. using System ; Class Hello { Public static void Main () { Console.writeLine ("Hello C#"); } } //end of the main What to do next: Save the following file as Hello.cs. cs is an extension to indicate C-sharp like .java for a Java Source File. You have to supply this extension while saving your file, otherwise the code will not compile correctly. The saved file will be of .cs.txt extension. Compile the above Code by giving the following Command at the Command Prompt csc Hello.cs If there are compile errors then you will be prompted accordingly, otherwise you will be getting a command prompt with the copyright information. Keep in mind that the compiler generates MSIL. Your next job is to execute the program to view the final Output. For that purpose you have to simply give Hello at the command Prompt. If everything goes on well, a message Hello C# will be printed on the Screen. You can view the MSIL Code generated by any .NET Language with the help of an Utility called Intermediate Language Disassembler or shortly ILDASM. This utility will display the application's information in a tree like fashion. Since the contents of this file is read only, a Programmer or anybody accessing these files cannot make any modifications to the output generated by the Source Code.

To view the MSIL Code for the above Hello C# Program, open Hello.exe file from the ILDASM tool. In Windows 98, ME & NT this tool can be accessed via start - programs Microsoft .NET Framework SDK - Tools - IL Disassembler Detailed Review of the above Program: I am giving below the process occurring to the source code, during the compilation and execution stages once again for your reference. Compilation Stage: C# Compiler produces MSIL as output after compilation. It is itself a complete language and it is more or less similar to Assembly language. MSIL stands for Microsoft Intermediate Language. The same thing happens to any application written in any CLR Compliant Language like Visual Basic.NET, Visual C++.NET etc. Execution Stage: The MSIL is then compiled into native CPU instructions by using JIT (Just in Time) compiler at the time of the program execution. The Source Code is recompiled and executed only after making any changes to it . Now let us analyze the Hello C# Program as a whole. I am giving below the code once again for your reference. Please note that the line numbers are given for clarification and explanation and is not a part of the Source Code. using System ; class Hello { public static void Main () { Console.writeLine ("Hello C#"); } } //end of the main

Line Number wise Analysis


Line - 1: - It is called as the namespace. Simply speaking, a namespace is a collection of .NET Classes similar to packages in Java. Line - 2: - It is the class declaration similar to Java & C++ Line - 3: - This is the main method which is required in all C# applications. Line - 4: - This code will print Hello C# onto the Console. Here Console is the class belonging to System namespace and writeLine is the static method belonging to Console Class. Line - 5:- The Opening and Closing curly races are similar to that of C++/Java.

Debugging Techniques in C#
by Mike Borromeo, 12/5/01
Download Source Code

Debugging GUI applications for me mostly consists of printing out debug statements in the form of a dialog box with some text. While this technique was helpful for small to medium size apps I find writing large apps with a dialog box popping up after every other statement is counterproductive. With this in mind, I set out to find a better method for displaying debug statements during runtime. Enter C#. C# solves three problems I faced when designing the useful and scalable debugging system. These problems exist either in Java, C/C++, or both (my main programming languages). 1. Not having very much meta-information (e.g. line number, method name, etc.) 2. Having to add and remove debug statements whenever the debug focus shifts 3. Having the debug statements compiled into the program affecting performance Ok, discussing the solution for these problems in order well start with number one. Basically a few classes from the System.Reflection and System.Diagnostics namespaces solve this problem. Using the System.Diagnostics.StackFrame class the call stack can be explored and stack details such as what is on the stack level above the current one, what line is a function being called from, etc. And with the System.Reflection classes the names of functions, namespaces, variable types, etc., can be ascertained. Applying all this to the problem at hand heres some code that retrieves the file name, line number, and method name of the function that called it.
// create the stack frame for the function that called this function StackFrame sf = new StackFrame( 1, true ); // save the method name string methodName = sf.GetMethod().ToString(); // save the file name string fileName = sf.GetFileName(); // save the line number int lineNumber = sf.GetFileLineNumber();

Moving right along to problem number two lets discuss how to selectively debug different sections of a program during runtime. Number two ties in with number one in that information from number one will help us filter debug statements from being displayed. For this example well filter by namespace. So say that you have fifteen namespaces in your program and right now you only want to display debug statements from one all you would have to do is tell the debug class only allow that one namespace to display debug statements. Simple enough. Heres some code.

// create the namespaces hashtable namespaces = new Hashtable(); // get the assembly of this class Assembly a = Assembly.GetAssembly( new Debug().GetType() ); // now cycle through each type and gather up all the namespaces foreach( Type type in a.GetTypes() ) { // check if the namespace is already in our table if( ! namespaces.Contains( type.Namespace ) ) namespaces.Add( type.Namespace, true ); }

The above code will create a Hashtable object containing all the namespaces in the same assembly as the Debug class of which this code is a part. Of course, this is only half of the solution so here is the actual filtering code.
// only proceed if the namespace in question is being debugged if( (bool) namespaces[ method.DeclaringType.Namespace ] ) // this is where the debug statement display code would be

Ok, so far so good. With the problems number one and two knocked out that leaves us with the obstacle of removing those darn debug statements when the final release is to be made without actually having to manually comment out or delete each one. This is where those handy little things called attributes come in to play. Assuming you have knowledge of how attributes work in C# Ill cut to the chase and introduce the ConditionalAttribute which is part of the aforementioned System.Diagnostics namespace. So heres some showing how to use the ConditionalAttribute class.
[Conditional("DEBUG")] public void Debug( string msg ) { // this is where the debug statement display code would be }

What this will do is when this program is compiled it will check if DEBUG was #defined and if it was then the call to this function will be remain, however if DEBUG is not #defined all calls to this function not will be compiled leaving us with no performance hit. Now, some of you are probably saying that you could solve some of the problems above in C/C++ and Java. I will note that neither language solves all of them. For example in C/C++ you can #define and #ifdef much like you can use ConditionalAttribute class and C# defines. But getting useful meta-information in C/C++ is limited. And in Java getting meta-information is possible but as far as I know all the code is always compiled (i.e. theres no Conditional type functionality). Thankfully there is C# which does solve (gracefully I might add) all the problems I mentioned above and quite a few more.

To demonstrate these techniques I wrote a small windows application along with this article. The Debug class can be plugged into your own projects. So enjoy and happy coding.

Potrebbero piacerti anche