SEG Object Oriented Analysis, Design and Programming

Slides:



Advertisements
Similar presentations
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 12 Introduction to ASP.NET.
Advertisements

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Inheritance and Polymorphism.
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++
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
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++
Advanced Object-Oriented Programming Features
History  We first begin with Java which was released in 1995 by Sun Microsystems  Initially Java was 100% interpreted at runtime and was very slow 
C#/.NET Jacob Lewallen. C# vs.NET.NET is a platform. Many languages compile to.NET: –VB.NET –Python.NET –Managed C++ –C#
1 Inheritance and Polymorphism. 2 Motivations Suppose you will define classes to model circles, rectangles, and triangles. These classes have many common.
Java CourseWinter 2009/10. Introduction Object oriented, imperative programming language. Developed: Inspired by C++ programming language.
Tahir Nawaz Visual Programming C# Week 2. What is C#? C# (pronounced "C sharp") is an object- oriented language that is used to build applications for.
Peter Juszczyk CS 492/493 - ISGS. // Is this C# or Java? class TestApp { static void Main() { int counter = 0; counter++; } } The answer is C# - In C#
Platforms and tools for Web Services and Mobile Applications Introduction to C# Bent Thomsen Aalborg University 3rd and 4th of June 2004.
Java versus C# An introduction to C# and Visual Studio.
Java vs. C# By Abrar Siddiqui.
Differences between C# and C++ Dr. Catherine Stringfellow Dr. Stewart Carpenter.
Programming in C# Language Overview
Principles of Computer Programming (using Java) Review Haidong Xue Summer 2011, at GSU.
Programming Languages and Paradigms Object-Oriented Programming.
Java and C++, The Difference An introduction Unit - 00.
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.
CSM-Java Programming-I Spring,2005 Objects and Classes Overview Lesson - 1.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
Distributed Systems (236351) Tutorial 1 - Getting Started with Visual Studio C#.NET.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Algorithm Programming Bar-Ilan University תשס"ח by Moshe Fresko.
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#
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.
C# D1 CSC 298 Elements of C# code (part 2). C# D2 Writing a class (or a struct)  Similarly to Java or C++  Fields: to hold the class data  Methods:
Tuc Goodwin  Object and Component-Oriented Programming  Classes in C#  Scope and Accessibility  Methods and Properties  Nested.
VB and C# Programming Basics. Overview Basic operations String processing Date processing Control structures Functions and subroutines.
Introduction to Exception Handling and Defensive Programming.
ILM Proprietary and Confidential -
Hoang Anh Viet Hà Nội University of Technology Chapter 1. Introduction to C# Programming.
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.
Introduction to C#. Why C#? Develop on the Following Platforms ASP.NET Native Windows Windows 8 / 8.1 Windows Phone WPF Android (Xamarin) iOS (Xamarin)
Programming in Java CSCI-2220 Object Oriented Programming.
Object Oriented Software Development
Computing with C# and the.NET Framework Chapter 2 C# Programming Basics ©2003, 2011 Art Gittleman.
Bill Campbell, UMB Microsoft's.NET C# and The Common Language Runtime.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
CMSC 341 Java Packages, Classes, Variables, Expressions, Flow Control, and Exceptions.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 9 Inheritance and.
PROGRAMMING IN C#. Collection Classes (C# Programming Guide) The.NET Framework provides specialized classes for data storage and retrieval. These classes.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Object Oriented Software Development 4. C# data types, objects and references.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Classes, Interfaces and Packages
Introduction to C# By: Abir Ghattas Michel Barakat.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
Introduction to C# Anders Hejlsberg Distinguished Engineer Developer Division Microsoft Corporation.
1 C# - Inheritance and Polymorphism. 2 1.Inheritance 2.Implementing Inheritance in C# 3.Constructor calls in Inheritance 4.Protected Access Modifier 5.The.
© 2006 Pearson Addison-Wesley. All rights reserved 1-1 Chapter 1 Review of Java Fundamentals.
Session 02 Module 3: Statements and Operators Module 4: Programming constructs Module 5: Arrays.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
Author: DoanNX Time: 45’.  OOP concepts  OOP in Java.
Reference Types CSE301 University of Sunderland Harry R Erwin, PhD.
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 –
METADATA IN.NET Presented By Sukumar Manduva. INTRODUCTION  What is Metadata ? Metadata is a binary information which contains the complete description.
Java and C# - Some Commonalities Compile into machine-independent, language- independent code which runs in a managed execution environment Garbage Collection.
 It is a pure oops language and a high level language.  It was developed at sun microsystems by James Gosling.
INTRODUCTION BEGINNING C#. C# AND THE.NET RUNTIME AND LIBRARIES The C# compiler compiles and convert C# programs. NET Common Language Runtime (CLR) executes.
C# for C++ Programmers 1.
CS360 Windows Programming
Introduction to C# AKEEL AHMED.
C# In many ways, C# looks similar to Java
Chapter 9 Inheritance and Polymorphism
Java Programming Language
Chengyu Sun California State University, Los Angeles
Presentation transcript:

SEG4110 - Object Oriented Analysis, Design and Programming Topic K C# (C-Sharp)

What is C#? C# (pronounced "C sharp") is an object-oriented language that is used to build applications for the Microsoft .NET platform C# is designed by Microsoft to combine the power of C/C++, Java and the productivity of Visual Basic The goal of C# and the .NET platform is to shorten development time by allowing developers to spend their time working on the application logic instead of low level programming details SEG4110 - Topic K - C#

Common Language Runtime C# code compiled to an Intermediate Language (IL) which then runs in the Common Language Runtime (CLR) just like Java is compiled to Java byte code which then runs in the Java Virtual Machine (JVM) The Common Language Runtime (CLR) provides a solid foundation for developers to build various types of applications such as web services, mobile code application etc The CLR provides the following benefits for application developers: simplified development integration of code written in various languages assembly-based deployment a better versioning of reusable components code reuse through implementation inheritance etc. SEG4110 - Topic K - C#

Compiling C# Source Code C# file names have the extension .cs To create the IL file, we need to compile the .cs file using the csc (using the command line), followed by the name of the source file The result is a file with the same name but the .exe extension, which is called an assembly The assembly file contains all the information that the common runtime needs to know to execute the program We can also create multi-file assemblies using an assembly linker, see the following link for more details: http://longhorn.msdn.microsoft.com/lhsdk/ndp/tskhowtobuildmultfileassembly.aspx SEG4110 - Topic K - C#

Features of C# C# syntax is very similar to Java (and thus C++) C# features are very similar to Java Object-orientation with single inheritance Support of interfaces No pointers (except for unsafe code) Exceptions Threads Namespaces (like Packages) Strong typing Garbage Collection Reflection Dynamic loading of code SEG4110 - Topic K - C#

A First C# Program: 'Hello World' using System; public class HelloWorld { public static void Main(string[] args) // This is a single line comment /* This is a multiple line comment */ Console.WriteLine("Hello World"); } SEG4110 - Topic K - C#

About the Hello World program C# is case sensitive using System consists of importing the System package Entry point of C# program must be called Main and not main .NET naming conventions use a capital letter for method names C# Main method can have a void parameter as well as an array of strings Console.WriteLine is equivalent to System.out.println Unlike Java, the file name does not need to be the same as the class name The same file can have many classes SEG4110 - Topic K - C#

Data Types C# supports the following types Value Types: primitive types: bool, char, int, short, long, byte, float, double. They can be signed or unsigned (e.g. ulong means unsigned long, etc) Enumeration using the enum keyword Structures using the struct keyword Reference Types: Classes, Interfaces, Arrays and Delegates Pointers: C# restricts the use of pointers to unsafe code only (see next slide) SEG4110 - Topic K - C#

Pointers It is possible to have pointer types if the C# code is executing in an unsafe context When C# code is executing in an unsafe context, a lot of runtime checking is disabled the program must have full trust on the machine it is running on The syntax and semantics for writing pointers is similar to the syntax and semantics for using pointers in C and C++ To write unsafe code, the unsafe keyword must be used to specify the code block as unsafe and the program must be compiled with the /unsafe compiler switch SEG4110 - Topic K - C#

General Statements Conditional statements if – else switch - default Loop statements while loops do-while loops for loops foreach loops Note that foreach is very useful for traversing collections. Example: string[] alphabet = {"a", "b", “c", "d", "e“…}; foreach(string str in alphabet) Console.WriteLine(str + " is a letter of the alphabet"); SEG4110 - Topic K - C#

The Class Object C# has a single rooted class hierarchy where all classes in C# are subclasses of System.Object the same way all Java classes are subclasses of java.lang.Object Java and C# Object share some common methods such as the toString() (ToString() in C#) method C# uses aliases to refer to some class names. For example the class System.Object can be written object (with small ‘o’) string is an alias for System.String SEG4110 - Topic K - C#

Boxing and Unboxing Value types (struct, enum, int..) can be transformed into reference types using Boxing and Unboxing Boxing: the following assignment wraps up the value 3 into an object object obj = 3; Unboxing: this assignment unwraps the value int x = (int) obj; This is similar in principle to Java wrapping classes SEG4110 - Topic K - C#

Rectangular and Jagged Arrays C# allows both jagged and rectangular arrays to be created Jagged arrays are the same as Java arrays. They are arrays of arrays. Example: int [][] array = new int [3][4]; // creates 1+3 = 4 arrays Rectangular arrays are more efficient but less flexible. The arrays have to be of the same dimension: int [,] array = new int [3, 4]; // creates only 1 array SEG4110 - Topic K - C#

The System.String Class This is the same as the Java String class Strings can be concatenated with + They can be indexed: s[i] String length: s.Length Strings are reference types => reference semantics in assignments Their values can be compared with == and != Class String defines many useful operations: CompareTo, IndexOf, StartsWith, Substring, etc SEG4110 - Topic K - C#

Classes C# classes are similar to Java classes C# allows the following class members (most of them are explained in the coming slides) Constructors Destructors Fields Methods Properties Indexers Delegates Events Nested Classes SEG4110 - Topic K - C#

Example of a class in C# // The class Example using System; class Example {   private string myString;    // Constructor   public Example(string myString)   {      this.myString = myString;   }   // Instance Method   public void printString()   {      Console.WriteLine(myString);   } } // Creating objects of the class Example // Program start class class ExampleClass { // Main begins program execution   public static void Main()   {      // Instance of Example    Example obj = new Example(“Message");      // Call Output class' method      obj.printString();     } } SEG4110 - Topic K - C#

The is operator The C# is operator is completely analogous to Java's instanceof operator. The two following code fragments are equivalent. C# Code if(x is MyClass) MyClass mc = (MyClass) x; Java Code if(x instanceof MyClass) MyClass mc = (MyClass) x; SEG4110 - Topic K - C#

Access Modifiers C# access modifiers public: accessible by any other class private: accessible only by the class in which it is declared protected: accessible only by the class in which it is declared, as well as any derived classes internal: accessible only from within the same assembly protected internal: accessible only from within the same assembly and the derived classes of the containing class If the modifier is not specified then it is considered private by default (similar to C++) SEG4110 - Topic K - C#

Constructors Constructors in C# works similarly to those in C++ and Java. Multiple constructors can be defined C# also provides a mechanism to  initialize static members of a class. This is done suing a static constructor: static MyClass() {   ... } Static constructors are implicitly public and necessarily take no input parameters SEG4110 - Topic K - C#

Destructors They are similar to the concepts of finalizers in Java. They are called before the object is removed by the garbage collector Destructors (as well as Java finalizers) should be avoided because there is no way to control the order of finalization of inter-related objects Syntax: class Test { ~Test() { ... finalization work ... // automatically calls the destructor of the superclass } SEG4110 - Topic K - C#

Fields Modifiers Fields modifiers include all access modifiers seen earlier To declare constants in C# the const keyword is used for compile time constants while the readonly keyword is used for runtime constants Example of a run time constant static readonly uint var = (uint) DateTime.Now.Ticks; Recall that to declare constants in Java the final keyword is used in both cases SEG4110 - Topic K - C#

Methods Modifiers There are ten modifiers that can be used with methods Four of these are the access modifiers seen before The rest are the following: abstract: determines abstract methods (similar to Java) static: C# supports static fields and methods just like Java new, virtual, override: used for method overriding, we will see these when we cover inheritance extern: used to call methods that are written in other languages. this is similar to Java native methods C# supports method overloading just like Java Unlike Java, C# supports also operator overloading (similar to C++) SEG4110 - Topic K - C#

Parameter Passing The parameter modifiers ref specifies that a parameter is passed by reference (similar to VB) If no modifier is specified then the parameter is passed by value C# defines output parameters to specify parameters that return values. This is done using the out modifier this is useful if multiple values are returned from a method SEG4110 - Topic K - C#

Variable Number of Parameters C# uses the params modifier to pass an arbitrary number of arguments to a method It is not necessary to place these arguments into an array before calling the method: using System; class ParamsTest { public static void Print(string title, params int[] args) { Console.WriteLine(title + ":"); foreach(int num in args) Console.WriteLine(num); } public static void Main(string[] args) { Print("First 4 positive numbers", 0, 1, 2, 3); SEG4110 - Topic K - C#

Properties Properties are used to represent getter/setter methods in a more flexible way this concept exists in Delphi and Visual Basic It is possible to create read-only, write-only or read and write properties Java does not have a mechanism for implicitly defining getter and setter methods it is up to the programmer to define these methods SEG4110 - Topic K - C#

Example of C# properties //read-write property for age public int Age{ get{ return age; } set{ age = value; public static void Main(string[] args){ Person pers = new Person("Bob"); pers.Age = 60; Console.WriteLine("Name: " + pers.Name + " " + pers.Age); using System; public class Person { private string name; private int age; public Person(string name){ this.name = name; } //read-only property for name public string Name{ get{ return name; SEG4110 - Topic K - C#

Indexers An indexer is a special syntax for overloading the [] operator for a class Java does not support this feature. C++ does by overloading the [] operator An indexer is useful when a class is a container for another kind of object It is also possible to create indexers that allow multidimensional array syntax Indexers can also be overloaded SEG4110 - Topic K - C#

Example of using indexers public class Building { Floor[] allFloors; // the name of an indexer is always this public Floor this [int index] { get { return allFloors[index]; } set { if (value != null) { allFloors[index] = value; ... How to use it in a program: Building aBuilding = new Building(parameters); aBuilding[10] = new Floor(parameters); SEG4110 - Topic K - C#

Inheritance C# does not support multiple inheritance just like Java C# does not support C++ different kinds of inheritance private and protected The following example shows a class B that inherits from A and implements the interface IComparable using System; class B : A, IComparable { int CompareTo() {} public static void Main(String[] args) { Console.WriteLine("Hello World"); } SEG4110 - Topic K - C#

Calling the Superclass Constructor The operator base is used to call a constructor of the superclass as shown is the following example: public MySubClass(string s) : base(s) {     .... }  C# explicitly enforces the call to the superclass constructor before the class constructor (similar to C++) base is similar to super in Java SEG4110 - Topic K - C#

Overriding Methods and Polymorphism In order to be overriden by a derived class, a method must be declared either abstract or virtual   In addition, developers of a subclass can decide to either explicitly override the virtual method by using the override keyword or explicitly choose not to by using the new keyword instead if you choose not to override a virtual method is like you create a new method the is independent from the superclass method SEG4110 - Topic K - C#

Interfaces Interfaces in C# are similar to Java interfaces they are denoted using the keyword interface C# interfaces contain only abstract methods In Java, interfaces may contain variables In .NET naming conventions, interface names start with an upper-case "I" (as in IClonable) As shown previously, the class that implements an interface does not use the Java keyword implements It is used as a normal superclass SEG4110 - Topic K - C#

Unextendable Classes Both Java and C# provide mechanisms to specify that a class cannot be used as a superclass In Java this is done by preceding the class declaration with the final keyword while In C# this is done by preceding the class declaration with the sealed keyword SEG4110 - Topic K - C#

Namespaces A C# namespace is a way to group classes and is used in a manner similar to Java's package construct C# namespaces are similar to C++ namespaces and syntax Unlike Java, C# namespaces do not dictate the directory structure of source files in an application Namespaces can be nested similar to Java packages SEG4110 - Topic K - C#

Namespaces (cont.) C# Code namespace GUI { public class MyClass { int x; public void m(){…} } Equivalent Java Code package GUI; public class MyClass { int x; public void m(){…} } SEG4110 - Topic K - C#

Exceptions Exceptions in C# and Java share a lot of similarities. Both languages support the use of the try and catch blocks for handling thrown exceptions and the finally block for releasing resources before leaving the method Both languages have an inheritance hierarchy where all exceptions are derived from a single Exception class Exceptions can be caught and rethrown SEG4110 - Topic K - C#

Exceptions (cont) Checked exceptions are typically used to indicate to a calling method that the callee generated an exception Java supports checked exceptions In C#, all exceptions are unchecked and there is no support to the throws clause a major drawback is that it is not possible for a programmer to know what exceptions to catch in their code SEG4110 - Topic K - C#

Example of a user defined exception using System; class MyException: Exception { public MyException(string message): base(message){ } public MyException(string message, Exception innerException): base(message, innerException){ } } SEG4110 - Topic K - C#

Synchronization in C# C# provides the lock statement which is semantically identical to the synchronized statement in Java to ensure that only one thread can access a particular object at a time Example public void Withdraw(int num){ lock(this){ if(num < this.amount) this.amount -= num; } SEG4110 - Topic K - C#

Collections The C# collections framework consists of the classes in the System.Collections namespace Java collections framework is more sophisticated than that available in .NET via C# System.Collections contain several interfaces and abstract classes such as IList, IEnumerable, IDictionary, ICollection, and CollectionBase which enable developers to manipulate data structures independently of their implementation The System.Collections namespace also contains some concrete implementations such as ArrayList, Queue, SortedList and Stack SEG4110 - Topic K - C#

Reflection Reflection in C# is done at the assembly level while in Java it is done at the class level Since classes are stored in assemblies then we need to load the assemblies while in Java one needs to be able to load the class file for the targeted class C# Reflection library is found in System.Reflection; SEG4110 - Topic K - C#

File I/O C# and Java support performing I/O via Stream classes C# IO classes are found in System.IO The following example displays the content of the file "input.txt“ using System; using System.IO; public class FileIOExample { public static void Main(string[] args){ FileStream inputFile = new FileStream("input.txt", FileMode.Open); StreamReader sr = new StreamReader(inputFile); String str; while((str = sr.ReadLine())!= null) Console.WriteLine(str); sr.Close(); } SEG4110 - Topic K - C#

References Microsoft MSDN http://msdn.microsoft.com/ Dare Obasanjo, “A Comparison Of Microsoft's C# Programming Language To Sun Microsystems' Java Programming Language” http://www.25hoursaday.com/CsharpVsJava.html#checked SEG4110 - Topic K - C#