Spring 2007NOEA: Computer Science Programme 1 C# - Introduction Language Fundamentals: Data Types string Objects and Classes Methods Iteration and Selection.

Slides:



Advertisements
Similar presentations
C# Language Report By Trevor Adams. Language History Developed by Microsoft Developed by Microsoft Principal Software Architect Principal Software Architect.
Advertisements

Language Fundamentals in brief C# - Introduction.
Introduction to Computing Concepts Note Set 7. Overview Variables Data Types Basic Arithmetic Expressions ▫ Arithmetic.
C#: Data Types Based on slides by Joe Hummel. 2 UCN Technology: Computer Science Content: “.NET is designed around the CTS, or Common Type System.
Introduction to the C# Programming Language for the VB Programmer.
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
1 9/20/06CS150 Introduction to Computer Science 1 Review: Exam 1.
Java Syntax Primitive data types Operators Control statements.
Data types and variables
3. Data Types. 2 Microsoft Objectives “.NET is designed around the CTS, or Common Type System. The CTS is what allows assemblies, written in different.
Fundamental Programming Structures in Java: Comments, Data Types, Variables, Assignments, Operators.
Chapter 2 Data Types, Declarations, and Displays
Review Java.
4. Statements and Methods. 2 Microsoft Objectives “With regards to programming statements and methods, C# offers what you would come to expect from a.
CMSC 341 Introduction to Java Based on tutorial by Rebecca Hasti at
Differences between C# and C++ Dr. Catherine Stringfellow Dr. Stewart Carpenter.
Programming in C# Language Overview
Performing Simple Calculations with C# Svetlin Nakov Telerik Corporation
1 Chapter Two Using Data. 2 Objectives Learn about variable types and how to declare variables Learn how to display variable values Learn about the integral.
Objectives You should be able to describe: Data Types
11 Values and References Chapter Objectives You will be able to: Describe and compare value types and reference types. Write programs that use variables.
JavaServer Pages Syntax Harry Richard Erwin, PhD CSE301/CIT304.
Introduction to Java Appendix A. Appendix A: Introduction to Java2 Chapter Objectives To understand the essentials of object-oriented programming in Java.
Introduction to Classes and Objects (Through Ch 5) Dr. John P. Abraham Professor UTPA.
.NET Data types. Introduction ٭ A "data type" is a class that is primarily used just to hold data. ٭ This is different from most other classes since they're.
1. 2 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Decisions { class.
C#: Statements and Methods Based on slides by Joe Hummel.
Java Primitives The Smallest Building Blocks of the Language (corresponds with Chapter 2)
FEN 2012 UCN Technology: Computer Science1 C# - Introduction Language Fundamentals in Brief.
C#C# Classes & Methods CS3260 Dennis A. Fairclough Version 1.1 Classes & Methods CS3260 Dennis A. Fairclough Version 1.1.
C# Intro Programming languages and programs: Source code and object code Editors and compilers C# fundamentals: Program structure Classes and Objects Variables.
CIS 260: App Dev I. 2 Programs and Programming n Program  A sequence of steps designed to accomplish a task n Program design  A detailed _____ for implementing.
Chapter 2: Using Data.
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.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
Java development environment and Review of Java. Eclipse TM Intergrated Development Environment (IDE) Running Eclipse: Warning: Never check the “Use this.
Controlling Program Flow. Data Types and Variable Declarations Controlling Program Flow.
CS 376b Introduction to Computer Vision 01 / 23 / 2008 Instructor: Michael Eckmann.
Computing with C# and the.NET Framework Chapter 2 C# Programming Basics ©2003, 2011 Art Gittleman.
CSCI 3328 Object Oriented Programming in C# Chapter 4: C# Control Statement – Part I 1 Xiang Lian The University of Texas Rio Grande Valley Edinburg, TX.
C# C1 CSC 298 Elements of C# code (part 1). C# C2 Style for identifiers  Identifier: class, method, property (defined shortly) or variable names  class,
Copyright Curt Hill Variables What are they? Why do we need them?
School of Computer Science & Information Technology G6DICP - Lecture 4 Variables, data types & decision making.
 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.
Performing Simple Calculations with C# Telerik Corporation
C++ for Java Programmers Chapter 2. Fundamental Daty Types Timothy Budd.
CSM-Java Programming-I Spring,2005 Fundamental Data Types Lesson - 2.
Introduction to C# By: Abir Ghattas Michel Barakat.
2: Basics Basics Programming C# © 2003 DevelopMentor, Inc. 12/1/2003.
Chapter 1 Java Programming Review. Introduction Java is platform-independent, meaning that you can write a program once and run it anywhere. Java programs.
Operators and Expressions
Introduction C# program is collection of classes Classes are collection of methods and some statements That statements contains tokens C# includes five.
CompSci 100E JB1.1 Java Basics (ala Goodrich & Tamassia)  Everything is in a class  A minimal program: public class Hello { public static void main(String[]
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.
Value Types. 2 Objectives Discuss concept of value types –efficiency –memory management –value semantics –boxing –unboxing –simple types Introduce struct.
Basic Introduction to C#
Types CSCE 314 Spring 2016.
Chapter 7: Expressions and Assignment Statements
Java Primer 1: Types, Classes and Operators
Chapter 7: Expressions and Assignment Statements
Multiple variables can be created in one declaration
Computing with C# and the .NET Framework
Chapter 2.
CSCI 3328 Object Oriented Programming in C# Chapter 4: C# Control Statement – Part I UTPA – Fall 2012 This set of slides is revised from lecture slides.
Java Programming Language
Java Basics Data Types in Java.
In this class, we will cover:
Presentation transcript:

Spring 2007NOEA: Computer Science Programme 1 C# - Introduction Language Fundamentals: Data Types string Objects and Classes Methods Iteration and Selection Arrays

Spring 2007NOEA: Computer Science Programme 2 C# All program logic must be embedded in (typically) a class. Like Java. Every executable program must contain a Main-method. The Main-method is the starting point of the application. The Main-method has several overloads: –static int Main(string[] args), static void Main(string[] args), static void Main() or static int Main() C# is case-sensitive C# supports operator and method overloading No multiple enhiritance (only interfaces – as in Java) All classes inherit object – as in Java Garbage-collection

Spring 2007NOEA: Computer Science Programme 3 A class public class Book { private string title; private string author; public Book(string t, string a) //Constructor { title= t; author= a; } public override string ToString(){ return (title+" "+author); }

Spring 2007NOEA: Computer Science Programme 4 Driver Program (Main) public class BookMain { public static void Main() { Book b1= new Book("C#","Troelsen"); Book b2= new Book("Java","Kölling"); System.Console.WriteLine(b1.ToString()); System.Console.WriteLine(b2); }

Spring 2007NOEA: Computer Science Programme 5 C# - data types KeywordDescriptionSpecial format for literals bool Boolean true false char 16 bit Unicode character 'A' '\x0041' '\u0041' sbyte 8 bit signed integernone byte 8 bit unsigned integernone short 16 bit signed integernone ushort 16 bit unsigned integernone int 32 bit signed integernone uint 32 bit unsigned integer U suffix long 64 bit signed integer L or l suffix ulong 64 bit unsigned integer U/u and L/l suffix float 32 bit floating point F or f suffix double 64 bit floating pointno suffix decimal 128 bit high precision M or m suffix string character sequence

Spring 2007NOEA: Computer Science Programme 6 C# - the string data type string is an alias for System.String – so string is a class Many useful properties and methods are offered by string: –Length (property) –Concat() –CompareTo() –Etc.

Spring 2007NOEA: Computer Science Programme 7 Exercise Architecture – Exercise: Arkitektur.htm

Spring 2007NOEA: Computer Science Programme 8 C# - using types in C# Declaration before use (compiler checked) Initialisation before use (compiler checked) public class App { public static void Main() { int width, height; width = 2; height = 4; int area = width * height; int x; int y = x * 2;... } declarations declaration + initialization error, x is not initialised

Spring 2007NOEA: Computer Science Programme 9 Arithmetics I C# offers the usual arithmetic operations: +, -, *, / and % (modulus) +, - and * are defined as usual / is overloaded: –If the operand are integers, the integer division is applied: 23 / 4 gives 5 –If one of the operands is a floating point, the result also is a floating point: 23.0 / 4 gives 5.75 –typecasting may be necessary

Spring 2007NOEA: Computer Science Programme 10 Arithmetics II The modulus operator yields the remainder with integer division: –23 % 4 gives 3, because 23 divide by 4 yields the quotient 5 and the remainder 3 The usual rules of operator precedence are valid in C#: –2 + 3 * 4 = 2 + (3 * 4) = 14 –(2+3) * 4 = 20

Spring 2007NOEA: Computer Science Programme 11 Arithmetics and Data Types In C# the result of an arithmetic operation has the “larger” type of the two operands: –int + long yields a long –float + double yields a double –byte + float yields a float –etc. It is always possible to assign a variable of a “larger” type a value of a “smaller” type –int x = 23; –long y = x;

Spring 2007NOEA: Computer Science Programme 12 An Example using System; public class Arithmetic { public static void Main() { int a = 1; int b = 3; float x = 2.0; Console.WriteLine(”a+b equals ” + (a+b)); Console.WriteLine(”and not ” + a + b); Console.WriteLine(”a+x equals ” + (a+x)); } What’s wrong here?

Spring 2007NOEA: Computer Science Programme 13 Type Casting One can change the type of an expression using explicit casting: int count = 24; int total = 100; float average = (float) total / count ; Syntax:(data type) variable name Type casting has higher precedence than arithmetic operations

Spring 2007NOEA: Computer Science Programme 14 C# - type conversion Some type conversions are done automatically –from “smaller” to “larger” type Otherwise explicit casting og conversion must be applied: –Type cast: prefix the type name in parentheses –Conversion: use the System.Convert-class int i = 5; double d = 3.2; string s = "496"; d = i; i = (int) d; i = System.Convert.ToInt32(s); implicit cast Explicit cast is needed Conversion

Spring 2007NOEA: Computer Science Programme 15 Exercises 1.Lookup System.Convert in msdn2.microsoft.commsdn2.microsoft.com 2.Write a small program that reads decimal number from the console (ReadLine()) and convert it to a double. 3.Round the number, so it has two decimals. (use integer division) 4.Write a small program that prints the number of 1000s, the number of 100s, the number of 10s and the number of 1s in the number 4623.

Spring 2007NOEA: Computer Science Programme 16 C# - objects and classes The class is a type definition –Class members are: constructors, methods and instance variables (like Java) and properties The object is the actual instance Every class inherits from System.Object (object) – also like Java –The class Object offers among other: ToString() and Equals() Objects are created using the new operator (like Java)

Spring 2007NOEA: Computer Science Programme 17 C# - Sample class class HelloClass // class definition { private string name; //instance variable public HellolClass(string name) //constructor { this.name = name; } public void SayHello()//method { Console.WriteLine("Hello "+name); }

Spring 2007NOEA: Computer Science Programme 18 C# - use of the HelloClass using System;//using classes in namespace System namespace ConsoleApplication1{//definition of a namespace class HelloClass{ //Class definition private string name;//instance variable public HelloClass(string name){//constructor this.name = name; } public void SayHello(){//method Console.WriteLine("Hello "+name); } class MainClass{//Main-class containing the Main-method static void Main(string[] args){ HelloClass h = new HelloClass("Carl"); //instantiation or //creation of an object h.SayHello(); //calling a method //on the object }

Spring 2007NOEA: Computer Science Programme 19 C# - Namespaces and Using Namespaces is a tool for structuring programs and systems Makes it possible to use the same names (identifiers) in different parts of an application. Namespaces may be nested Visual Studio creates default a namespace with the same name as the project using tells the compiler where to look for definitions that our program refers to Namespaces are not the same as Java-packages, but they are used for the same things and there are similarities

Spring 2007NOEA: Computer Science Programme 20 C# - constructors Are called when an object is created: –HelloClass h = new HelloClass("Carl"); –This constructor takes a parameter of type string The constructor’s job is to initialise the object, that is to assign valid values to the instance variables of the object A default-constructor is created automatically: –The default-constructor takes no arguments and initialises the instance variables to their default values –The default-constructor may be overridden be writing a constructor with no parameters

Spring 2007NOEA: Computer Science Programme 21 C# - value- and reference-types Objects of value-type are stack allocated – objects of reference type are allocated on the heap Value types dies, when control goes out of the scope, where they are declared – reference types removed by the garbage collector Value types are copied with assignment – with reference types a reference (the address) is copied

Spring 2007NOEA: Computer Science Programme 22 C# - reference types - example creation, assignment and comparison: Customer c1, c2, c3; string s1, s2; c1 = new Customer("Flemming Sander", 36259); c2 = new Customer(”Bjarne Riis", 55298); c3 = null; // c3 refers to nothing c3 = c1; // c3 refers to the same object as c1 if (c1 == null)... // is c1 referring to something? if (c1 == c2)... // compare references if (c1.Equals(c2))... // compares object-values

Spring 2007NOEA: Computer Science Programme 23 C# - When are objects equal? Classes ought to override the Equals-method public class Customer {. public override bool Equals(object obj) { Customer other; if ((obj == null) || (!(obj is Customer))) return false; // surely not equal other = (Customer) obj; // explicit typecast return this.id == other.id; // equal if ids are... }

Spring 2007NOEA: Computer Science Programme 24 C# - Boxing and Unboxing C# converts automatically between simple value and object –value => object = "boxing“ (the value is “wrapped in a box”) –object => value = "unboxing“ (the value is unwrapped again) int i, j; object obj; string s; i = 32; obj = i; // boxing (copy) i = 19; j = (int) obj; // unboxing! s = j.ToString(); // boxing! s = 99.ToString(); // boxing!

Spring 2007NOEA: Computer Science Programme 25 C# - arrays Arrays are reference types –Created from the Array-class in FCL –Created using the new-operator –0-based indexing –Are initialised with default value (0 if numeric, null if reference) int[] a; a = new int[5]; a[0] = 17; a[1] = 32; int x = a[0] + a[1] + a[4]; int l = a.Length; Access element 1 Creation Number of elements

Spring 2007NOEA: Computer Science Programme 26 C# - enumerations Originally a C/C++ construction used to assigning symbolic names to numerical values: enum Month { January= 1, February = 2,…,December = 12 } public static void GetSeason(Month m) { switch(m) { case Month.January: Console.WriteLine(”Winter”); ……

Spring 2007NOEA: Computer Science Programme 27 C# - structs In some ways like a class, but there are differences: –Can have instance variables and methods –Cannot have a default constructor –Variables of a struct-type are value types and as such stack allocated –Can only inherit from interfaces –Cannot be inherited from Can be used to implement ADTs, but no inheritance and polymorphism

Spring 2007NOEA: Computer Science Programme 28 Decision Constructs To control the flow of program execution, C# defines two simple constructs to alter the flow of your program –The if/else statement –The switch statement Like Java

Spring 2007NOEA: Computer Science Programme 29 C# - selection and iteration x = obj.foo(); if (x > 0 && x < 10) count++; else if (x == -1)... else {... } while (x > 0) {... x--; } for (int k = 0; k < 10; k++) {... }

Spring 2007NOEA: Computer Science Programme 30 C# - foreach-loop foreach loop is used to sweep over collections as arrays –Reduces the risk of indexing errors int[] data = { 1, 2, 3, 4, 5 }; int sum = 0; foreach (int x in data) { sum += x; } foreach type value collection

Spring 2007NOEA: Computer Science Programme 31 C# - methods Much like Java – Example (Consider an Account- class with an instance variable bal): public float GetBalance() { return bal; } Called on an object: iAccount myAccount= new Account(); int saldo = minKonto.GetSaldo();

Spring 2007NOEA: Computer Science Programme 32 Method Parameter Modifiers C# provides a set of parameter modifiers that control how arguments are sent into (and possibly returned from) a given method.

Spring 2007NOEA: Computer Science Programme 33 The Default Parameter-Passing // Arguments are passed by value by default. public static int Add(int x, int y) { int ans = x + y; // Caller will not see these changes // as you are modifying a copy of the // original data. x = 10000; y = 88888; return ans; }

Spring 2007NOEA: Computer Science Programme 34 The out Modifier // Output parameters are allocated by the member. public static void Add(int x, int y, out int ans) { ans = x + y; } static void Main(string[] args) { // No need to assign local output variables. int ans; Add(90, 90, out ans); Console.WriteLine(" = {0} ", ans); }

Spring 2007NOEA: Computer Science Programme 35 The ref Modifier public static void SwapStrings(ref string s1, ref string s2) { string tempStr = s1; s1 = s2; s2 = tempStr; } static void Main(string[] args) { string s = "First string"; string s2 = "My other string"; Console.WriteLine("Before: {0}, {1} ", s, s2); SwapStrings(ref s, ref s2); Console.WriteLine("After: {0}, {1} ", s, s2); }

Spring 2007NOEA: Computer Science Programme 36 The params Modifier // Return average of 'some number' of doubles. static double CalculateAverage(params double[] values) { double sum = 0; for (int i = 0; i < values.Length; i++) sum += values[i]; return (sum / values.Length); } static void Main(string[] args) { // Pass in a comma-delimited list of doubles... double average; average = CalculateAverage(4.0, 3.2, 5.7); Console.WriteLine("Average of 4.0, 3.2, 5.7 is: {0}", average); //...or pass an array of doubles. double[] data = { 4.0, 3.2, 5.7 }; average = CalculateAverage(data); Console.WriteLine("Average of data is: {0}", average); }

Spring 2007NOEA: Computer Science Programme 37 C# - Methods A class may have two kind of methods: –Instance methods –Static methods (class methods) –Instance methods need an object to be invoked –Static methods are called using the class name only

Spring 2007NOEA: Computer Science Programme 38 C# - Example The array-class in BCL (FCL) –The class is a member of namespace System (System.Array) namespace System { public class Array { public int GetLength(int dimension) {... } public static void Sort(Array a) {... }. } instance method static method

Spring 2007NOEA: Computer Science Programme 39 C# - calling the methods /* main.cs */ using System; public class App { public static void Main() { int[] data = { 11, 7, 38, 55, 3 }; Array.Sort(data); for (int i=0; i<data.GetLength(0); i++) Console.WriteLine(i + ": " + data[i]); } Class-method Instance-method

Spring 2007NOEA: Computer Science Programme 40 Exercises Write a driver-class that test the following methods: 1.A method that returns the sum the elements in an array 2.A method that returns the average of the elements in an array 3.A method that returns the number of elements with the value 7 in an array 4.A method that returns true if the value 3 is contained in the array and false otherwise 5.Generalise your solution to exercise 2 and 3, so the value in question (7 and 3 resp.) is passed as an argument to the method. 6.Cpr.htmCpr.htm 7.Find some of your old Java-programs and translate them into C#