Object Oriented Programming

Slides:



Advertisements
Similar presentations
AP Computer Science Anthony Keen. Computer 101 What happens when you turn a computer on? –BIOS tries to start a system loader –A system loader tries to.
Advertisements

L2:CSC © Dr. Basheer M. Nasef Lecture #2 By Dr. Basheer M. Nasef.
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
Differences between Java and C CS-2303, C-Term Differences between Java and C CS-2303, System Programming Concepts (Slides include materials from.
Learning C#. What is C# A new object oriented language  Syntax based on C Similar to C++ and Java  Used to write.NET software Software that targets.
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
C#.NET C# language. C# A modern, general-purpose object-oriented language Part of the.NET family of languages ECMA standard Based on C and C++
8 November Forms and JavaScript. Types of Inputs Radio Buttons (select one of a list) Checkbox (select as many as wanted) Text inputs (user types text)
Fundamental Programming Structures in Java: Comments, Data Types, Variables, Assignments, Operators.
About the Presentations The presentations cover the objectives found in the opening of each chapter. All chapter objectives are listed in the beginning.
Chapter 2 - Java Programming Fundamentals1 Chapter 2 Java Programming Fundamentals.
Copyright © 2012 Pearson Education, Inc. Chapter 2 Introduction to Visual C#
CMSC 341 Introduction to Java Based on tutorial by Rebecca Hasti at
Java versus C# An introduction to C# and Visual Studio.
Differences between C# and C++ Dr. Catherine Stringfellow Dr. Stewart Carpenter.
Week 4-5 Java Programming. Loops What is a loop? Loop is code that repeats itself a certain number of times There are two types of loops: For loop Used.
Introduction to Java Appendix A. Appendix A: Introduction to Java2 Chapter Objectives To understand the essentials of object-oriented programming in Java.
11 Getting Started with C# Chapter Objectives You will be able to: 1. Say in general terms how C# differs from C. 2. Create, compile, and run a.
DAT602 Database Application Development Lecture 5 JAVA Review.
Microsoft Visual Basic 2008 CHAPTER NINE Using Arrays and File Handling.
EE4E. C++ Programming Lecture 1 From C to C++. Contents Introduction Introduction Variables Variables Pointers and references Pointers and references.
Tutorial C#. PLAN I. Introduction II. Example of C# program :Hello World III. How to use C# language GUI elements Primitives Types Expressions and operators.
PROGRAMMING IN VISUAL BASIC.NET VISUAL BASIC BUILDING BLOCKS Bilal Munir Mughal 1 Chapter-5.
Chapter 1: A First Program Using C#. Programming Computer program – A set of instructions that tells a computer what to do – Also called software Software.
Lecture 1 Programming in C# Introducing C# Writing a C# Program.
Lecture Set 1 Part C: Understanding Visual Studio and.NET – Applications, Solutions, Projects (no longer used – embedded in Lecture Set 2A)
Introduction to Programming David Goldschmidt, Ph.D. Computer Science The College of Saint Rose Java Fundamentals (Comments, Variables, etc.)
Lecture 2 Object Oriented Programming Basics of Java Language MBY.
1 Introduction to C# Programming Console applications No visual components Only text output Two types MS-DOS prompt - Used in Windows 95/98/ME Command.
Programming in C#. I. Introduction C# (or C-Sharp) is a programming language. C# is used to write software that runs on the.NET Framework. Although C#
CS 11 java track: lecture 1 Administrivia need a CS cluster account cgi-bin/sysadmin/account_request.cgi need to know UNIX
CSE 131 Computer Science 1 Module 1: (basics of Java)
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Netprog: Java Intro1 Crash Course in Java. Netprog: Java Intro2 Why Java? Network Programming in Java is very different than in C/C++ –much more language.
1 © 2002, Cisco Systems, Inc. All rights reserved. Arrays Chapter 7.
 JAVA Compilation and Interpretation  JAVA Platform Independence  Building First JAVA Program  Escapes Sequences  Display text with printf  Data.
Module 3: Working with Components. Overview An Introduction to Key.NET Framework Development Technologies Creating a Simple.NET Framework Component Creating.
Lecture Set 2 Part A: Creating an Application with Visual Studio – Solutions, Projects, Files.
Introduction to Exception Handling and Defensive Programming.
Applied Computing Technology Laboratory QuickStart C# Learning to Program in C# Amy Roberge & John Linehan November 7, 2005.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
C# EMILEE KING. HISTORY OF C# In the late 1990’s Microsoft recognized the need to be able to develop applications that can run on multiple operating system.
4.4 JavaScript (JS) Deitel Ch. 7, 8, 9, JavaScript & Java: Similarities JS (JavaScript) is case-sensitive Operators –arithmetic: unary +, unary.
CMP-MX21: Lecture 4 Selections Steve Hordley. Overview 1. The if-else selection in JAVA 2. More useful JAVA operators 4. Other selection constructs in.
1 Introduction to C# Programming Console applications No visual components Only text output Two types MS-DOS prompt - Used in Windows 95/98/ME Command.
Chapter 3 Syntax, Errors, and Debugging Fundamentals of Java.
CS101: Introduction to Computer Science Slides adapted from Sedgewick and Wayne Copyright © Your First Java.
Exceptions and Assertions Chapter 15 – CSCI 1302.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Session 1 C# Basics.
Spring 2009 Programming Fundamentals I Java Programming XuanTung Hoang Lecture No. 8.
Lecture Set 2 Part A: Creating an Application with Visual Studio – Solutions, Projects, Files 8/10/ :35 PM.
2: Basics Basics Programming C# © 2003 DevelopMentor, Inc. 12/1/2003.
An Introduction to Java – Part 1 Erin Hamalainen CS 265 Sec 001 October 20, 2010.
Chapter 1 Java Programming Review. Introduction Java is platform-independent, meaning that you can write a program once and run it anywhere. Java programs.
Session 02 Module 3: Statements and Operators Module 4: Programming constructs Module 5: Arrays.
Java Programming: From Problem Analysis to Program Design, Second Edition 1 Lecture 1 Objectives  Become familiar with the basic components of a Java.
JAVA Programming (Session 2) “When you are willing to make sacrifices for a great cause, you will never be alone.” Instructor: รัฐภูมิ เถื่อนถนอม
C# Fundamentals An Introduction. Before we begin How to get started writing C# – Quick tour of the dev. Environment – The current C# version is 5.0 –
Announcements Assignment 2 Out Today Quiz today - so I need to shut up at 4:25 1.
1 Handling Errors and Exceptions Chapter 6. 2 Objectives You will be able to: 1. Use the try, catch, and finally statements to handle exceptions. 2. Raise.
CS0007: Introduction to Computer Programming Primitive Data Types and Arithmetic Operations.
Object Oriented Programming Lecture 2: BallWorld.
Java and C# - Some Commonalities Compile into machine-independent, language- independent code which runs in a managed execution environment Garbage Collection.
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
 It is a pure oops language and a high level language.  It was developed at sun microsystems by James Gosling.
Information and Computer Sciences University of Hawaii, Manoa
Basic Introduction to C#
Tutorial C#.
Introduction to Programming in Java
Presentation transcript:

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

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

Writing applications in C#

Writing applications in C#

Writing applications in C# This program is considerably more complex than the previous example It uses the System.Drawing and System.Windows.Forms namespaces 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:library option

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#

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 .dll using 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); }

Writing applications in C#

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

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

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

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 our lab sessions

Visual Studio .NET

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 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.

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 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) Int32 x=10; String s=“Hello”;

Basic C# language concepts Arrays Array declaration and initialization is similar to other languages // 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];

Basic C# language concepts The array itself is an object The array in 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 simplifies 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 foreach (type identifier in arrayName)

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 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 Int32 x = 10; while(x--) DoSomething();

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 This is something we shall look at in a future lecture

Basic C# language concepts Operator 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 * -> [] &

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