Advanced Programming C# Introduction.

Slides:



Advertisements
Similar presentations
Variables in C Amir Haider Lecturer.
Advertisements

 2005 Pearson Education, Inc. All rights reserved Introduction.
Primitive Data Types and Operations. Introducing Programming with an Example public class ComputeArea { /** Main method */ public static void main(String[]
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
CMT Programming Software Applications
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie June 27, 2005.
Fundamental Programming Structures in Java: Comments, Data Types, Variables, Assignments, Operators.
Chapter 2: Introduction to C++.
Hello, world! Dissect HelloWorld.java Compile it Run it.
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.
1. 2 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Decisions { class.
Advanced Programming LOOP.
Chapter 2: Basic Elements of Java J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
C Tokens Identifiers Keywords Constants Operators Special symbols.
Chapter 2 Basic Elements of Java. Chapter Objectives Become familiar with the basic components of a Java program, including methods, special symbols,
Introduction to Programming David Goldschmidt, Ph.D. Computer Science The College of Saint Rose Java Fundamentals (Comments, Variables, etc.)
Program A computer program (also software, or just a program) is a sequence of instructions written in a sequence to perform a specified task with a computer.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
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.
C#C# Introduction CS3260 Dennis A. Fairclough Version 1.0 Introduction CS3260 Dennis A. Fairclough Version 1.0.
JAVA Tokens. Introduction A token is an individual element in a program. More than one token can appear in a single line separated by white spaces.
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.
Keith Elder Microsoft MVP
Chapter 2: Java Fundamentals
Week 1 Algorithmization and Programming Languages.
C++ Programming: Basic Elements of C++.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
Using Data Within a Program Chapter 2.  Classes  Methods  Statements  Modifiers  Identifiers.
1 st Semester Module2 Basic C# Concept อภิรักษ์ จันทร์สร้าง Aphirak Jansang Computer Engineering.
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.
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,
Introducing C++ Programming Lecture 3 Dr. Hebbat Allah A. Elwishy Computer & IS Assistant Professor
 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 3 – Introduction to C# Programming Outline 3.1 Introduction 3.2 Simple Program: Printing a Line.
2: Basics Basics Programming C# © 2003 DevelopMentor, Inc. 12/1/2003.
C++ Basics Programming. COMP104 Lecture 5 / Slide 2 Introduction to C++ l C is a programming language developed in the 1970s with the UNIX operating system.
Variables in C Topics  Naming Variables  Declaring Variables  Using Variables  The Assignment Statement Reading  Sections
CMSC 104, Version 8/061L09VariablesInC.ppt Variables in C Topics Naming Variables Declaring Variables Using Variables The Assignment Statement Reading.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 2 Introduction to C++
Java Programming: From Problem Analysis to Program Design, Second Edition 1 Lecture 1 Objectives  Become familiar with the basic components of a Java.
Sudeshna Sarkar, IIT Kharagpur 1 Programming and Data Structure Sudeshna Sarkar Lecture 3.
1 st Semester Module2 Basic C# Concept อภิรักษ์ จันทร์สร้าง Aphirak Jansang Computer Engineering.
CS0007: Introduction to Computer Programming Primitive Data Types and Arithmetic Operations.
Introduction C# program is collection of classes Classes are collection of methods and some statements That statements contains tokens C# includes five.
CSE 110: Programming Language I Matin Saad Abdullah UB 1222.
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.
Chapter 1.2 Introduction to C++ Programming
Basic Introduction to C#
Chapter 1.2 Introduction to C++ Programming
Chapter 1.2 Introduction to C++ Programming
Chapter 1.2 Introduction to C++ Programming
BASIC ELEMENTS OF A COMPUTER PROGRAM
Lecture 2 Data Types Richard Gesick.
Computing with C# and the .NET Framework
Java Programming: From Problem Analysis to Program Design, 4e
Chapter 3: Understanding C# Language Fundamentals
Chapter 2.
Introduction to C++ Programming
Advanced Programming Lecture 02: Introduction to C# Apps
An overview of Java, Data types and variables
Module 2: Understanding C# Language Fundamentals
Chapter 3 – Introduction to C# Programming
Chapter 2: Introduction to C++.
Module 2 Variables, Assignment, and Data Types
Presentation transcript:

Advanced Programming C# Introduction

Application Types Console Application Windows Application Service Has standard streams (out, in, err) GUI can be added manually Windows Application GUI based No standard streams (out, in, err) Main thread is shared by the GUI message pump & your code Service Main thread is commandeered by the SCM No GUI

Start Visual Studio

New Project

Windows Application

Simple Program – console application // A first program in C#. using System; class Welcome1 { static void Main( string[] args ) Console.WriteLine( "Welcome to C# Programming!" ); } }

Constructions of Note using namespace class like import in Java: bring in namespaces namespace disambiguation of names like Internet hierarchical names and C++ naming class like in C++ or Java single inheritance up to object

Constructions of Note static void Main() Console.Write(Line) Defines the entry point for an assembly. Four different overloads – taking string arguments and returning int’s. Console.Write(Line) Takes a formatted string: “Composite Format” Indexed elements: e.g., {0} can be used multiple times only evaluated once {index [,alignment][:formatting]}

Common Type System (CTS) From MSDN

Atomic Data

Simple Program: Add Integers Primitive data types Data types that are built into C# string, int, double, char, long Console.ReadLine() Used to get a value from the user input Int32.Parse() Used to convert a string argument to an integer Allows math to be preformed once the string is converted

Built-in Types C# predefined types The “root” object Logical bool Signed sbyte, short, int, long Unsigned byte, ushort, uint, ulong Floating-point float, double, decimal Textual char, string Textual types use Unicode (16-bit characters)

Types Unified Type System Value types Directly contain data Cannot be null Reference types Contain references to objects May be null In C# you have value types that directly hold the data on the stack and reference types that keeps a reference on the stack, but allocates the real memory on the heap. Also have pointer types in unsafe code. Will discuss those in Part 2. int i = 123; string s = "Hello world"; 123 i s "Hello world"

Programs Write a C program to read three integer numbers and find their average.

Predefined Types Value Types All are predefined structs Signed sbyte, short, int, long Unsigned byte, ushort, uint, ulong Character char Floating point float, double, decimal Logical bool

Predefined Types Integral Types C# Type System Type Size (bytes) Signed? sbyte System.Sbyte 1 Yes short System.Int16 2 int System.Int32 4 long System.Int64 8 byte System.Byte No ushort System.UInt16 uint System.UInt32 ulong System.UInt64

Predefined Types Floating Point Types Follows IEEE 754 specification Supports ± 0, ± Infinity, NaN C# Type System Type Size (bytes) float System.Single 4 double System.Double 8

Predefined Types decimal 128 bits Essentially a 96 bit value scaled by a power of 10 Decimal values represented precisely Doesn’t support signed zeros, infinities or NaN C# Type System Type Size (bytes) decimal System.Decimal 16

Predefined Types bool Represents logical values Literal values are true and false Cannot use 1 and 0 as boolean values No standard conversion between other types and bool Eliminating implicit conversions between numbers and bool can help find subtle bugs. C# Type System Type Size (bytes) bool System.Boolean 1 (2 for arrays)

Predefined Types char Represents a Unicode character Literals ‘A’ // Simple character ‘\u0041’ // Unicode ‘\x0041’ // Unsigned short hexadecimal ‘\n’ // Escape sequence character C# Type System Type Size (bytes) Char System.Char 2

Predefined Types string An immutable sequence of Unicode characters Reference type Special syntax for literals string s = “I am a string”; C# Type System Type Size (bytes) String System.String 20 minimum

Type System Value types Reference types Primitives int i; Enums enum State { Off, On } Structs struct Point { int x, y; } Reference types Classes class Foo: Bar, IFoo {...} Interfaces interface IFoo: IBar {...} Arrays string[] a = new string[10]; Delegates delegate void Empty();

Example Assume you work for the Alexandria Electricity company and you need a program to help you calculate the electricity bill for each customer. The program input should be the old meter reading and the new meter reading. Given that the price is 0.10 pounds per kilowatt.

Program Structure Main Method Execution begins at the static Main() method Can have only one method with one of the following signatures in an assembly static void Main() static int Main() static void Main(string[] args) static int Main(string[] args)

C# Comments Comments can be created using //… Multi-lines comments use /* … */ Comments are ignored by the compiler

Program Structure Syntax Identifiers Names for types, methods, fields, etc. Must be whole word – no white space Unicode characters Begins with letter or underscore Case sensitive Must not clash with keyword Unless prefixed with @

Identifiers: Keywords Often we use special identifiers called keywords that already have a predefined meaning in the language Example: class A keyword cannot be used in any other way All C# keywords are lowercase!

Arithmetic Arithmetic operations Asterisk (*) is multiplication Slash (/) is division Percent sign (%) is the modulus operator Plus (+) and minus (-) are the same There are no exponents

Operators Associativity Assignment and ternary conditional operators are right-associative Operations performed right to left x = y = z evaluates as x = (y = z) All other binary operators are left-associative Operations performed left to right x + y + z evaluates as (x + y) + z Use parentheses to control order

C# Keywords Words that cannot be used as variable or class names Have a specific unchangeable function within the language Example: class

C# Classes Class names can only be one word long (i.e. no white space in class name ) Class names are capitalized, with each additional English word capitalized as well (e.g., MyFirstProgram ) Each class name is an identifier Can contain letters, digits, and underscores (_) Cannot start with digits Can start with the at symbol (@)

C# Class Methods Class bodies start with a left brace ({) Class bodies end with a right brace (}) Methods Building blocks of programs The Main method Each console or windows application must have exactly one All programs start by executing the Main method Braces are used to start ({) and end (}) a method

C# Statements Anything in quotes (“) is considered a string Every statement must end in a semicolon (;)

C#

NameSpaces You import namespaces when you want to be able to refer to classes by their short name, rather than full name For example, import System.XML allows XmlDataDocument and XmlNode rather than System.XML.XmlDataDocument and System.XML.XmlNode to be in your code.

Program Structure Namespaces namespace N1 {     // N1 class C1 {   // N1.C1 class C2 {   // N1.C1.C2 }     namespace N2 {    // N1.N2 class C2 { // N1.N2.C2     } The comments show the fully qualified names. A namespace called N3.N4 is like two nested namespaces.

Program Structure Namespaces The using statement lets you use types without typing the fully qualified name Can always use a fully qualified name using N1; C1 a; // The N1. is implicit N1.C1 b; // Fully qualified name C2 c; // Error! C2 is undefined N1.N2.C2 d; // One of the C2 classes C1.C2 e; // The other one Note that it is N1.C1, not N1::C1 The using statement is scoped by the namespace and/or compilation module containing it.

Program Structure Namespaces Best practice: Put all of your types in a unique namespace Have a namespace for your company, project, product, etc. Look at how the .NET Framework classes are organized

Namespaces Partition the name space to avoid name conflict! All .NET library code are organized using namespaces! By default, C# code is contained in the global namespace To refer to code within a namespace, must use qualified name (as in System.Console) or import explicitly (as in using System; ) using System; class HelloWorld { static void Main(string[] args) Console.WriteLine(“Hello World!”); } class HelloWorld { static void Main(string[] args) System.Console.WriteLine(“Hello World!”); }

Welcome4.cs // Printing multiple lines in a dialog Box. using System; using System.Windows.Forms; class Welcome4 { static void Main( string[] args ) MessageBox.Show( "Welcome \n to \n C# \n programming!" );} }

Statements Overview Loop Statements Statement lists Block statements while do for foreach Jump Statements break continue goto return throw Exception handling try Statement lists Block statements Labeled statements Declarations Constants Variables Expression statements checked, unchecked lock using Conditionals if switch

Statements Expression Statements Statements must do work Assignment, method call, ++, --, new static void Main() { int a, b = 2, c = 3; a = b + c; a++; Console.WriteLine(a + b + c); a == 2; // ERROR! } Expression statements must do work.

Events Events are a way for an object to communicate with those that are interested in what it has to offer, like a button has a click event Interested parties use Event Handlers, which are a way of subscribing to the event

Math Class Methods The Math class Allows the user to perform common math calculations Using methods ClassName.MethodName( argument1, arument2, … ) Constants Math.PI = 3.1415926535… Math.E = 2.7182818285…

Math Class Methods

Example A motor car uses 8 liters of fuel per 100 km on normal roads and 15% more fuel on rough roads. Write a program to print out the distance the car can travel on full tank of 40 liters of fuel on both normal and rough roads.

Statements Variables and Constants static void Main() { const float pi = 3.14f; const int r = 123; Console.WriteLine(pi * r * r); int a; int b = 2, c = 3; a = 1; Console.WriteLine(a + b + c); }

Example Write a program to ask you for the temperature in Fahrenheit and then convert it to Celsius. Given: C= 5/9 (F-32) Write a program to ask you for the temperature in Celsius and then convert it to Fahrenheit.

Programs Write a program to ask a person for his height in feet and inches and then tell them his height in cms. Given that 1 foot = 30 cms and 1 inch = 2.5 cms.

Examples Write a program to ask the user for the width and length of a piece of land and then tell him how many orange trees he can grow on it. Given that each orange tree requires 4 m2.

Examples Write a program to ask the user for the radius of a circle, and then display its area and circumference.