47
Object Oriented Programming Introduction to C# Introduction to C# Dr. Mike Spann Dr. Mike Spann [email protected] [email protected]

Object Oriented Programming Introduction to C# Dr. Mike Spann [email protected]

Embed Size (px)

Citation preview

Page 1: Object Oriented Programming Introduction to C# Dr. Mike Spann m.spann@bham.ac.uk

Object Oriented Programming

Introduction to C#Introduction to C#

Dr. Mike SpannDr. Mike Spann

[email protected]@bham.ac.uk

Page 2: Object Oriented Programming Introduction to C# Dr. Mike Spann m.spann@bham.ac.uk

Contents

Introducing C#Introducing C# Writing applications in C#Writing applications in C# Visual Studio .NETVisual Studio .NET Basic C# language conceptsBasic C# language concepts

Page 3: Object Oriented Programming Introduction to C# Dr. Mike Spann m.spann@bham.ac.uk

Introducing C#

C# (‘C-sharp’) is a language that targets one C# (‘C-sharp’) is a language that targets one and only one platform, namely .NETand only one platform, namely .NET

That doesn’t mean it’s restricted to WindowsThat doesn’t mean it’s restricted to Windows There are now .NET implementations on There are now .NET implementations on

other operating systems including Linuxother operating systems including Linux As long as we get to grips with object oriented As long as we get to grips with object oriented

programming, C# is a simple language to programming, C# is a simple language to mastermaster

Page 4: Object Oriented Programming Introduction to C# Dr. Mike Spann m.spann@bham.ac.uk

Introducing C#

C# derives it’s power from .NET and the framework C# derives it’s power from .NET and the framework class libraryclass library

The most similar language to C# is JavaThe most similar language to C# is Java There are a number of striking similaritiesThere are a number of striking similarities BUT there is one fundamental differenceBUT there is one fundamental difference

Java runs on a virtual machine and is interpretedJava runs on a virtual machine and is interpretedC# programs runs in native machine codeC# programs runs in native machine codeThis is because of the power of .NET and leads to This is because of the power of .NET and leads to

much more efficient programsmuch more efficient programs

Page 5: Object Oriented Programming Introduction to C# Dr. Mike Spann m.spann@bham.ac.uk

Writing applications in C#

An application in C# can be one of three typesAn application in C# can be one of three types Console application (.exe)Console application (.exe) Windows application (.exe)Windows application (.exe) Library of Types (.dll)Library of Types (.dll)

The .dll is not executableThe .dll is not executable These 3 types exclude the more advanced These 3 types exclude the more advanced

web-based applicationsweb-based applications

Page 6: Object Oriented Programming Introduction to C# Dr. Mike Spann m.spann@bham.ac.uk

Writing applications in C#

Before we look at the more detailed Before we look at the more detailed structure and syntax of C# programs, we structure and syntax of C# programs, we will show a simple example of each typewill show a simple example of each type

In each case we will use the command line In each case we will use the command line compiler (csc) to create the binary compiler (csc) to create the binary (assembly)(assembly) Later in this lecture we will look at using Later in this lecture we will look at using

Visual Studio to create our applicationsVisual Studio to create our applications

Page 7: Object Oriented Programming Introduction to C# Dr. Mike Spann m.spann@bham.ac.uk

Writing applications in C#

Example 1 – A console applicationExample 1 – A console application This example inputs a number from the This example inputs a number from the

console and displays the square root back console and displays the square root back to the consoleto the console

Uses a simple iterative algorithm rather Uses a simple iterative algorithm rather than calling a Math library functionthan calling a Math library function

Page 8: Object Oriented Programming Introduction to C# Dr. Mike Spann m.spann@bham.ac.uk

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);

}}

Page 9: Object Oriented Programming Introduction to C# Dr. Mike Spann m.spann@bham.ac.uk

Writing applications in C#

Page 10: Object Oriented Programming Introduction to C# Dr. Mike Spann m.spann@bham.ac.uk

Writing applications in C#

We can see that everything in a C# application is We can see that everything in a C# application is in a classin a class

In this case the class defines a program entry point In this case the class defines a program entry point MainMain This makes the application binary an This makes the application binary an

executableexecutable Note the use of the Note the use of the SystemSystem namespace namespace

Classes referred to such as Classes referred to such as ConsoleConsole and and Math Math actually actually System.Console System.Console and and System.MathSystem.Math

Page 11: Object Oriented Programming Introduction to C# Dr. Mike Spann m.spann@bham.ac.uk

Writing applications in C#

Example 2 – A windows applicationExample 2 – A windows application A simple GUI displaying a menuA simple GUI displaying a menu

This example displays a window with This example displays a window with couple of menu buttonscouple of menu buttons

• Clicking on a menu button displays a Clicking on a menu button displays a pop-up dialog boxpop-up dialog box

The code listing demonstrates the The code listing demonstrates the simplicity of GUI programming in C#simplicity of GUI programming in C#

Page 12: Object Oriented Programming Introduction to C# Dr. Mike Spann m.spann@bham.ac.uk

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, EventArgs args){ this.Close(); } void OnMessageBox(Object sender, EventArgs args){ MenuItem item = sender as MenuItem; MessageBox.Show(this, "You selected menu item - "+item.Text); }}

Page 13: Object Oriented Programming Introduction to C# Dr. Mike Spann m.spann@bham.ac.uk

Writing applications in C#

Page 14: Object Oriented Programming Introduction to C# Dr. Mike Spann m.spann@bham.ac.uk

Writing applications in C#

Page 15: Object Oriented Programming Introduction to C# Dr. Mike Spann m.spann@bham.ac.uk

Writing applications in C#

This program is considerably more complex than This program is considerably more complex than the previous examplethe previous example

It uses the It uses the System.DrawingSystem.Drawing and and SSystem.Windows.Forms ystem.Windows.Forms namespacesnamespaces The (SThe (System.Windows.Formsystem.Windows.Forms).).FormForm class is a class is a

standard outer graphics container for most standard outer graphics container for most windows/GUI applicationswindows/GUI applications

It also uses event handling to respond to user It also uses event handling to respond to user interaction (menu button clicks)interaction (menu button clicks)

Page 16: Object Oriented Programming Introduction to C# Dr. Mike Spann m.spann@bham.ac.uk

Writing applications in C#

Example 3 – A libraryExample 3 – A library We can take some of the code from We can take some of the code from

example 1 for computing the square root example 1 for computing the square root and make it a library and make it a library

It will not have a It will not have a MainMain method method We indicate that we are compiling to We indicate that we are compiling to

a .dll using the a .dll using the /Target:library /Target:library option option

Page 17: Object Oriented Programming Introduction to C# Dr. Mike Spann m.spann@bham.ac.uk

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;}

}

Page 18: Object Oriented Programming Introduction to C# Dr. Mike Spann m.spann@bham.ac.uk

Writing applications in C#

Page 19: Object Oriented Programming Introduction to C# Dr. Mike Spann m.spann@bham.ac.uk

Writing applications in C#

We can now write a simple program We can now write a simple program containing a containing a Main Main method which uses this method which uses this library classlibrary class The only thing we need to do is to The only thing we need to do is to

reference the library reference the library .dll .dll using the /r using the /r switch when we compile the applicationswitch when we compile the application

Page 20: Object Oriented Programming Introduction to C# Dr. Mike Spann m.spann@bham.ac.uk

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); }}

Page 21: Object Oriented Programming Introduction to C# Dr. Mike Spann m.spann@bham.ac.uk

Writing applications in C#

Page 22: Object Oriented Programming Introduction to C# Dr. Mike Spann m.spann@bham.ac.uk

Visual Studio .NET

VS.NET is an Integrated Development Environment VS.NET is an Integrated Development Environment or IDE or IDE It includes a source code editors (usually pretty It includes a source code editors (usually pretty

fancy ones containing language help features)fancy ones containing language help features) Software project management toolsSoftware project management tools Online-help and Online-help and DebuggingDebugging GUI design toolsGUI design tools And lots more......And lots more......

Page 23: Object Oriented Programming Introduction to C# Dr. Mike Spann m.spann@bham.ac.uk

Visual Studio .NET

Creating a new project gives the user the option of Creating a new project gives the user the option of the language and project typethe language and project type Visual Basic, C++, C#, J#Visual Basic, C++, C#, J# Console, Windows, Class Library, Active Web Console, Windows, Class Library, Active Web

Page or Web ServicePage or Web Service

Page 24: Object Oriented Programming Introduction to C# Dr. Mike Spann m.spann@bham.ac.uk

Visual Studio .NET

Page 25: Object Oriented Programming Introduction to C# Dr. Mike Spann m.spann@bham.ac.uk

Visual Studio .NET We can group our projects under a common We can group our projects under a common

solutionsolution Each application has just one solution but may Each application has just one solution but may

comprise many projectscomprise many projects A single solution can comprise projects written A single solution can comprise projects written

in different languagesin different languages Each project contains a number of files including Each project contains a number of files including

source files, executables and source files, executables and xmlxml files containing files containing information about the project and resourcesinformation about the project and resources

Page 26: Object Oriented Programming Introduction to C# Dr. Mike Spann m.spann@bham.ac.uk

Visual Studio .NET

We can add each of our previous 3 example We can add each of our previous 3 example applications (projects) to a single solution applications (projects) to a single solution Learning C SharpLearning C Sharp Its a simple matter to flip between them and Its a simple matter to flip between them and

view the code from each project by selecting view the code from each project by selecting the appropriate tabthe appropriate tab

Each project must be built (compiled) before Each project must be built (compiled) before executing and any of the projects in a solution executing and any of the projects in a solution can be selected to be executedcan be selected to be executed

Page 27: Object Oriented Programming Introduction to C# Dr. Mike Spann m.spann@bham.ac.uk

Visual Studio .NET

Page 28: Object Oriented Programming Introduction to C# Dr. Mike Spann m.spann@bham.ac.uk

Visual Studio .NET

It is a simple matter to reference a It is a simple matter to reference a .dll.dll from from a projecta project

We can check all the references that a We can check all the references that a project makes by expanding the project makes by expanding the ReferencesReferences menu item in the solution explorermenu item in the solution explorer Notice for the windows project, lots of Notice for the windows project, lots of

FCL classes are referencedFCL classes are referenced

Page 29: Object Oriented Programming Introduction to C# Dr. Mike Spann m.spann@bham.ac.uk

Visual Studio .NET

Page 30: Object Oriented Programming Introduction to C# Dr. Mike Spann m.spann@bham.ac.uk

Visual Studio .NET An important feature of VS is its ability to enable An important feature of VS is its ability to enable

visual programmingvisual programming Essentially we can create fairly sophisticated GUI’s Essentially we can create fairly sophisticated GUI’s

without writing a line of codewithout writing a line of code We simply add GUI components to an outer window We simply add GUI components to an outer window

(a (a Form)Form) and set up the properties of the and set up the properties of the components to get the required look and feel components to get the required look and feel

VS allows us to easily switch between code and VS allows us to easily switch between code and design viewsdesign views

We will look more into visual programming in our We will look more into visual programming in our lab sessionslab sessions

Page 31: Object Oriented Programming Introduction to C# Dr. Mike Spann m.spann@bham.ac.uk

Visual Studio .NET

Page 32: Object Oriented Programming Introduction to C# Dr. Mike Spann m.spann@bham.ac.uk

Basic C# language concepts

C# has a rich C-based syntax much like C++ or C# has a rich C-based syntax much like C++ or JavaJava

The concepts of variables, program statements, The concepts of variables, program statements, control flow, operators, exceptions etc are the same control flow, operators, exceptions etc are the same in C# as in C++ and Javain C# as in C++ and Java

Like Java, everything in C# is inside a Like Java, everything in C# is inside a class{}class{} We will only look at those C# language issues We will only look at those C# language issues

which differ from those we are already familiar which differ from those we are already familiar with with

Page 33: Object Oriented Programming Introduction to C# Dr. Mike Spann m.spann@bham.ac.uk

Basic C# language concepts

Primitive typesPrimitive types These are types representing the basic types we These are types representing the basic types we

are familiar with – integers, floats, characters are familiar with – integers, floats, characters etcetc

In C# they are part of the FCL so they are In C# they are part of the FCL so they are treated as treated as ObjectsObjects (unlike in Java!) but are used (unlike in Java!) but are used in the same way as normal primitive typesin the same way as normal primitive types

So, for example, we can apply the normal So, for example, we can apply the normal arithmetic operators to themarithmetic operators to them

Page 34: Object Oriented Programming Introduction to C# Dr. Mike Spann m.spann@bham.ac.uk

Basic C# language concepts

C# Primitive C# Alias Description

Boolean bool Indicates a true or false value. The if, while, and do-while constructs require expressions of type Boolean.

Byte byte Numeric type indicating an unsigned 8-bit value.

Char char Character type that holds a 16-bit Unicode character.

Decimal decimal High-precession numerical type for financial or scientific applications.

Double double Double precision floating point numerical value.

Single float Single precision floating point numerical value.

Int32 int Numerical type indicating a 32-bit signed value.

Int64 long Numerical type indicating a 64-bit signed value.

SByte sbyte Numerical type indicating an 8-bit signed value.

Int16 short Numerical type indicating a 16-bit signed value.

UInt32 uint Numerical type indicating a 32-bit unsigned value.

UInt64 ulong Numerical type indicating a 64-bit unsigned value.

UInt16 ushort Numerical type indicating a 16-bit unsigned value.

String string Immutable string of character values

Object object The base type of all type in any managed code.

Page 35: Object Oriented Programming Introduction to C# Dr. Mike Spann m.spann@bham.ac.uk

Basic C# language concepts Reference Types and Value TypesReference Types and Value Types

When we declare a variable in a C# program it is When we declare a variable in a C# program it is either a either a referencereference or a or a valuevalue type type

All non-primitive types are reference typesAll non-primitive types are reference typesEssentially the variable name is a reference to Essentially the variable name is a reference to

the memory occupied by the variablethe memory occupied by the variable But primitive types can be eitherBut primitive types can be either

Even though all primitive types are treated as Even though all primitive types are treated as objects (unlike in Java)!!objects (unlike in Java)!!

Page 36: Object Oriented Programming Introduction to C# Dr. Mike Spann m.spann@bham.ac.uk

Basic C# language concepts For example For example StringString and and Int32Int32 are both primitive types are both primitive types

BUTBUTStringString is a reference type is a reference typeInt32Int32 is a value type is a value type

StringString variable variable s s is a reference (memory address) of some is a reference (memory address) of some memory which stores the string (which defaults to null)memory which stores the string (which defaults to null)

Int32Int32 variable variable x x is the actual value of the integer (which is the actual value of the integer (which defaults to zero)defaults to zero)

Int32 x=10;String s=“Hello”;

Page 37: Object Oriented Programming Introduction to C# Dr. Mike Spann m.spann@bham.ac.uk

Basic C# language concepts

ArraysArrays Array declaration and initialization is Array declaration and initialization is

similar to other languagessimilar to other languages

// A one dimensional array of 10 BytesByte[] bytes = new Byte[10]; // A two dimensional array of 4 Int32s Int32[,] ints = new Int32[5,5]; // A one dimensional array of references to StringsString[] strings = new String[10];

Page 38: Object Oriented Programming Introduction to C# Dr. Mike Spann m.spann@bham.ac.uk

Basic C# language concepts

The array itself is an object The array itself is an object The array in is automatically derived from the The array in is automatically derived from the

ArrayArray class in the FCL class in the FCL This enables a number of useful methods of the This enables a number of useful methods of the

Array class to be used Array class to be used Finding the length of an arrayFinding the length of an arrayFinding the number of dimensions of an arrayFinding the number of dimensions of an array

Arrays themselves are reference types although their Arrays themselves are reference types although their elements can be value types, or reference typeselements can be value types, or reference types

Page 39: Object Oriented Programming Introduction to C# Dr. Mike Spann m.spann@bham.ac.uk

Basic C# language concepts

Control flow statements in C# are the same Control flow statements in C# are the same as for C++ and Javaas for C++ and Java if {} else{}if {} else{} for {}for {} do{} while()do{} while() etcetc

However, there is one additional new one in However, there is one additional new one in C#!C#! foreachforeach

Page 40: Object Oriented Programming Introduction to C# Dr. Mike Spann m.spann@bham.ac.uk

Basic C# language concepts

foreach foreach simplifies the code for iterating through an arraysimplifies the code for iterating through an array

There is no loop counterThere is no loop counterIf the loop counter variable is required in the loop, If the loop counter variable is required in the loop,

then a then a forfor construct must be used construct must be used The type must match the type of elements in the arrayThe type must match the type of elements in the array The array cannot be updated inside the loopThe array cannot be updated inside the loop

foreach (type identifier in arrayName)

Page 41: Object Oriented Programming Introduction to C# Dr. Mike Spann m.spann@bham.ac.uk

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); }}

Page 42: Object Oriented Programming Introduction to C# Dr. Mike Spann m.spann@bham.ac.uk

Basic C# language concepts

Expressions and operatorsExpressions and operators C# is a strongly typed languageC# is a strongly typed language Variables are declared before useVariables are declared before use Implicit type conversions that don’t lose precision Implicit type conversions that don’t lose precision

will be carried outwill be carried out Unlike C++ (but like Java) C# has a boolean typeUnlike C++ (but like Java) C# has a boolean type Thus the following code generates a compilation Thus the following code generates a compilation

errorerror

Int32 x = 10;while(x--) DoSomething();

Page 43: Object Oriented Programming Introduction to C# Dr. Mike Spann m.spann@bham.ac.uk

Basic C# language concepts

C# has the standard set of operators we are C# has the standard set of operators we are familiar withfamiliar with

Also it has operators such as Also it has operators such as isis and and typeoftypeof for for testing variable type informationtesting variable type information

C# provides operator overload functions (as C# provides operator overload functions (as does C++ but not Java) to enable standard does C++ but not Java) to enable standard operators to be applied to non-primitive typesoperators to be applied to non-primitive types This is something we shall look at in a This is something we shall look at in a

future lecturefuture lecture

Page 44: Object Oriented Programming Introduction to C# Dr. Mike Spann m.spann@bham.ac.uk

Basic C# language conceptsOperator category Operators

Arithmetic + - * / %

Logical (boolean and bitwise) & | ^ ! ~ && || true false

String concatenation +

Increment, decrement ++  --

Shift << >>

Relational == != < > <= >=

Assignment = += -= *= /= %=

&= |= ^= <<= >>=

Member access .

Indexing []

Cast ()

Conditional (Ternary) ?:

Delegate concatenation and removal + -

Object creation New

Type information is sizeof typeof   

Overflow exception control checked unchecked

Indirection and Address * -> [] &

Page 45: Object Oriented Programming Introduction to C# Dr. Mike Spann m.spann@bham.ac.uk

Basic C# language concepts Error handlingError handling

This is always done in C# using structured This is always done in C# using structured exception handlingexception handlingUse of the Use of the try{} catch{}try{} catch{} mechanism as in Java mechanism as in Java

and C++and C++Functions should Functions should notnot return error conditions return error conditions

but should throw exceptionsbut should throw exceptionsThis is done universally by methods in FCL This is done universally by methods in FCL

classesclasses

Page 46: Object Oriented Programming Introduction to C# Dr. Mike Spann m.spann@bham.ac.uk

Basic C# language conceptspublic 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"); }}

Page 47: Object Oriented Programming Introduction to C# Dr. Mike Spann m.spann@bham.ac.uk

Summary

We have looked at different types of simple C# We have looked at different types of simple C# applicationsapplications Console applicationsConsole applications Windows applicationsWindows applications Libraries (reusable types)Libraries (reusable types)

We have looked at the basics of using Visual We have looked at the basics of using Visual Studio.NETStudio.NET

We have looked at some C# language issues from We have looked at some C# language issues from the point of view of differences from C++ and Javathe point of view of differences from C++ and Java