460 likes | 474 Vues
This tutorial provides an introduction to object-oriented programming using C#. It covers the basics of C# language concepts and writing applications in C#. The tutorial also introduces the Visual Studio .NET development environment and explains how to write console applications, Windows applications, and libraries in C#.
E N D
Object Oriented Programming Introduction to C# Dr. Mike Spann m.spann@bham.ac.uk
Contents • Introducing C# • Writing applications in C# • Visual Studio .NET • Basic C# language concepts
Introducing C# • C# (‘C-sharp’) is a language that targets one and only one platform, namely .NET • That doesn’t mean it’s restricted to Windows • There are now .NET implementations on other operating systems including Linux • As long as we get to grips with object oriented programming, C# is a simple language to master
Introducing C# • C# derives it’s power from .NET and the framework class library • The most similar language to C# is Java • There are a number of striking similarities • BUT there is one fundamental difference • Java runs on a virtual machine and is interpreted • C# programs runs in native machine code • This is because of the power of .NET and leads to much more efficient programs
Writing applications in C# • An application in C# can be one of three types • Console application (.exe) • Windows application (.exe) • Library of Types (.dll) • The .dll is not executable • These 3 types exclude the more advanced web-based applications
Writing applications in C# • Before we look at the more detailed structure and syntax of C# programs, we will show a simple example of each type • In each case we will use the command line compiler (csc) to create the binary (assembly) • Later in this lecture we will look at using Visual Studio to create our applications
Writing applications in C# • Example 1 – A console application • This example inputs a number from the console and displays the square root back to the console • Uses a simple iterative algorithm rather than calling a Math library function
Writing applications in C# using System; class Square_Root { static void Main(string[] args) { double a,root; do { Console.Write("Enter a number: "); a=Convert.ToDouble(Console.ReadLine()); if (a<0) Console.WriteLine(“Enter a positive number!"); } while (a<0); root=a/2; double root_old; do { root_old=root; root=(root_old+a/root_old)/2; } while (Math.Abs(root_old-root)>1.0E-6); Console.WriteLine("The square root of " + a + " is " + root); } }
Writing applications in C# • We can see that everything in a C# application is in a class • In this case the class defines a program entry point Main • This makes the application binary an executable • Note the use of the System namespace • Classes referred to, such as Console and Math, are actually System.Consoleand System.Math
Writing applications in C# • Example 2 – A windows application • A simple GUI displaying a menu • This example displays a window with couple of menu buttons • Clicking on a menu button displays a pop-up dialog box • The code listing demonstrates the simplicity of GUI programming in C#
Writing applications in C# using System; using System.Drawing; using System.Windows.Forms; class App{ public static void Main(){ Application.Run(new MenuForm()); } } class MenuForm:Form{ public MenuForm(){ this.ContextMenu = new ContextMenu(SetupMenu()); this.Menu = new MainMenu(SetupMenu()); } MenuItem[] SetupMenu(){ MenuItem file = new MenuItem("&File"); file.MenuItems.Add("Exit", new EventHandler(OnExit)); MenuItem messages = new MenuItem("&Message Boxes"); EventHandler handler = new EventHandler(OnMessageBox); messages.MenuItems.Add("Message Box 1", handler); messages.MenuItems.Add("Message Box 2", handler); return new MenuItem[]{file, messages}; } void OnExit(Object sender, EventArgsargs){ this.Close(); } void OnMessageBox(Object sender, EventArgsargs){ MenuItem item = sender as MenuItem; MessageBox.Show(this, "You selected menu item - "+item.Text); } }
Writing applications in C# • This program is considerably more complex than the previous example • It uses the System.Drawing and System.Windows.Formsnamespaces • The (System.Windows.Forms).Form class is a standard outer graphics container for most windows/GUI applications • It also uses event handling to respond to user interaction (menu button clicks)
Writing applications in C# • Example 3 – A library • We can take some of the code from example 1 for computing the square root and make it a library • It will not have a Main method • We indicate that we are compiling to a .dll using the /Target:libraryoption
Writing applications in C# using System; public class Square_Root_Class { public static double calcRoot(double number) { double root; root=number/2; double root_old; do { root_old=root; root=(root_old+number/root_old)/2; } while (Math.Abs(root_old-root)>1.0E-6); return root; } }
Writing applications in C# • We can now write a simple program containing a Main method which uses this library class • The only thing we need to do is to reference the library .dllusing the /r switch when we compile the application
Writing applications in C# using System; class Square_Root { static void Main(string[] args) { double a,root; do { Console.Write("Enter a number: "); a=Convert.ToDouble(Console.ReadLine()); if (a<0) Console.WriteLine("Please enter a positive number!"); } while (a<0); root=Square_Root_Class.calcRoot(a); Console.WriteLine("The square root of " + a + " is " + root); } }
Visual Studio .NET • VS.NET is an Integrated Development Environment or IDE • It includes a source code editors (usually pretty fancy ones containing language help features) • Software project management tools • Online-help and • Debugging • GUI design tools • And lots more......
Visual Studio .NET • Creating a new project gives the user the option of the language and project type • Visual Basic, C++, C#, J# • Console, Windows, Class Library, Active Web Page or Web Service
Visual Studio .NET • We can group our projects under a common solution • Each application has just one solution but may comprise many projects • A single solution can comprise projects written in different languages • Each project contains a number of files including source files, executables and xml files containing information about the project and resources
Visual Studio .NET • We can add each of our previous 3 example applications (projects) to a single solution Learning C Sharp • Its a simple matter to flip between them and view the code from each project by selecting the appropriate tab • Each project must be built (compiled) before executing and any of the projects in a solution can be selected to be executed
Visual Studio .NET • It is a simple matter to reference a .dll from a project • We can check all the references that a project makes by expanding the References menu item in the solution explorer • Notice for the windows project, lots of FCL classes are referenced
Visual Studio .NET • An important feature of VS is its ability to enable visual programming • Essentially we can create fairly sophisticated GUI’s without writing a line of code • We simply add GUI components to an outer window (a Form) and set up the properties of the components to get the required look and feel • VS allows us to easily switch between code and design views • We will look more into visual programming in a future lecture
Basic C# language concepts C# has a rich C-based syntax much like C++ or Java The concepts of variables, program statements, control flow, operators, exceptions etc are the same in C# as in C++ and Java Like Java, everything in C# is inside a class{} We will only look at those C# language issues which differ from those we are already familiar with
Basic C# language concepts • Primitive types • These are types representing the basic types we are familiar with – integers, floats, characters etc • In C# they are part of the FCL so they are treated as Objects (unlike in Java!) but are used in the same way as normal primitive types • So, for example, we can apply the normal arithmetic operators to them
Basic C# language concepts • Reference Types and Value Types • When we declare a variable in a C# program it is either a reference or a value type • All non-primitive types are reference types • Essentially the variable name is a reference to the memory occupied by the variable • But primitive types can be either • Even though all primitive types are treated as objects (unlike in Java)!!
Basic C# language concepts Int32 x=10; String s=“Hello”; • For example String and Int32 are both primitive types • BUT • String is a reference type • Int32 is a value type • String variable s is a reference (memory address) of some memory which stores the string (which defaults to null) • Int32 variable x is the actual value of the integer (which defaults to zero)
Basic C# language concepts // A one dimensional array of 10 Bytes Byte[] bytes = new Byte[10]; // A two dimensional array of 4 Int32s Int32[,] ints = new Int32[5,5]; // A one dimensional array of references to Strings String[] strings = new String[10]; • Arrays • Array declaration and initialization is similar to other languages
Basic C# language concepts • The array itself is an object • The array is automatically derived from the Array class in the FCL • This enables a number of useful methods of the Array class to be used • Finding the length of an array • Finding the number of dimensions of an array • Arrays themselves are reference types although their elements can be value types, or reference types
Basic C# language concepts • Control flow statements in C# are the same as for C++ and Java • if {} else{} • for {} • do{} while() • etc • However, there is one additional new one in C#! • foreach
Basic C# language concepts foreach (type identifier inarrayName) • foreachsimplifies the code for iterating through an array • There is no loop counter • If the loop counter variable is required in the loop, then a for construct must be used • The type must match the type of elements in the array • The array cannot be updated inside the loop
Basic C# language concepts using System; public class ForEachTest { static void Main(string[] args) { int[] array ={ 0, 2, 4, 6, 8, 10, 12, 14}; int total = 0; foreach (int n in array) total += n; Console.WriteLine("Array total= " + total); } }
Basic C# language concepts Int32 x = 10;while(x--) DoSomething(); • Expressions and operators • C# is a strongly typed language • Variables are declared before use • Implicit type conversions that don’t lose precision will be carried out • Unlike C++ (but like Java) C# has a Boolean type • Thus the following code generates a compilation error
Basic C# language concepts C# has the standard set of operators we are familiar with Also it has operators such as is and typeof for testing variable type information C# provides operator overload functions (as does C++ but not Java) to enable standard operators to be applied to non-primitive types
Basic C# language concepts • Error handling • This is always done in C# using structured exception handling • Use of the try{} catch{} mechanism as in Java and C++ • Functions should not return error conditions but should throw exceptions • This is done universally by methods in FCL classes
Basic C# language concepts public static void ExceptionExample() { // try-catch try { Int32 index = 10; while(index-- != 0) Console.WriteLine(100/index); } catch(DivideByZeroException) { Console.WriteLine("A divide by zero exception!"); } Console.WriteLine("Exception caught; code keeps running"); // try-finally try { return; } finally { Console.WriteLine("Code in finally blocks always runs"); } }
Summary • We have looked at different types of simple C# applications • Console applications • Windows applications • Libraries (reusable types) • We have looked at the basics of using Visual Studio.NET • We have looked at some C# language issues from the point of view of differences from C++ and Java