Distribution and Integration Technologies. C# Language

Similar documents
C# Java. C# Types Naming Conventions. Distribution and Integration Technologies. C# C++.NET A C# program is a collection of: C C++ C# Language

Introduction to.net, C#, and Visual Studio. Part I. Administrivia. Administrivia. Course Structure. Final Project. Part II. What is.net?

C#.Net. Course Contents. Course contents VT BizTalk. No exam, but laborations

C#: framework overview and in-the-small features

.Net Technologies. Components of.net Framework

Introduce C# as Object Oriented programming language. Explain, tokens,

NOIDATUT E Leaning Platform

3. Basic Concepts. 3.1 Application Startup

Introduction to C# Applications

Hierarchical inheritance: Contains one base class and multiple derived classes of the same base class.

Course Hours

C++\CLI. Jim Fawcett CSE687-OnLine Object Oriented Design Summer 2017

This tutorial has been prepared for the beginners to help them understand basics of c# Programming.

MCSA Universal Windows Platform. A Success Guide to Prepare- Programming in C# edusum.com

C# Programming in the.net Framework

DAD Lab. 1 Introduc7on to C#

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

C# Asynchronous Programming Model

C# Fundamentals. Hans-Wolfgang Loidl School of Mathematical and Computer Sciences, Heriot-Watt University, Edinburgh

Chapter 1 Getting Started

C# Types. Industrial Programming. Value Types. Signed and Unsigned. Lecture 3: C# Fundamentals

Industrial Programming

Introduction to Programming Using Java (98-388)

COPYRIGHTED MATERIAL. Contents. Part I: C# Fundamentals 1. Chapter 1: The.NET Framework 3. Chapter 2: Getting Started with Visual Studio

Object-Oriented Programming in C# (VS 2015)

SWE344. Internet Protocols and Client-Server Programming

Objectives. Introduce the core C# language features class Main types variables basic input and output operators arrays control constructs comments

Duhok Polytechnic University Amedi Technical Institute/ IT Dept. Halkawt Rajab Hussain

PES INSTITUTE OF TECHNOLOGY

Introduction To C#.NET

IT 528 Developing.NET Applications Using C# Gülşen Demiröz

Visual Studio.NET.NET Framework. Web Services Web Forms Windows Forms. Data and XML classes. Framework Base Classes. Common Language Runtime

Index COPYRIGHTED MATERIAL

Object-Oriented Programming in C# (VS 2012)

Microsoft Visual C# Step by Step. John Sharp

Table of Contents Preface Bare Necessities... 17

Asynchronous Functions in C#

Getting started 7. Storing values 21. Creating variables 22 Reading input 24 Employing arrays 26 Casting data types 28 Fixing constants 30 Summary 32

A Comparison of Visual Basic.NET and C#

Question And Answer.

The C# Programming Language. Overview

EEE-425 Programming Languages (2013) 1

Programming C# 5.0. Ian Griffiths O'REILLY' Beijing Cambridge * Farnham Kbln Sebastopol Tokyo

3. Java - Language Constructs I

Threads are lightweight processes responsible for multitasking within a single application.

Object-Oriented Programming

Contents. Figures. Tables. Examples. Foreword. Preface. 1 Basics of Java Programming 1. xix. xxi. xxiii. xxvii. xxix

Concurrent Programming

15CS45 : OBJECT ORIENTED CONCEPTS

C#: advanced object-oriented features

C# Syllabus. MS.NET Framework Introduction

INTRODUCTION TO.NET. Domain of.net D.N.A. Architecture One Tier Two Tier Three Tier N-Tier THE COMMON LANGUAGE RUNTIME (C.L.R.)

DC69 C# &.NET DEC 2015

Language Specification

Microsoft. Microsoft Visual C# Step by Step. John Sharp

VISUAL PROGRAMMING_IT0309 Semester Number 05. G.Sujatha & R.Vijayalakshmi Assistant professor(o.g) SRM University, Kattankulathur

02 Features of C#, Part 1. Jerry Nixon Microsoft Developer Evangelist Daren May President & Co-founder, Crank211

Asynchronous Programming

II. Programming Technologies

Sri Lanka Institute of Information Technology System Programming and Design II Year 3 Tutorial 06

TARGETPROCESS PLUGIN DEVELOPMENT GUIDE

Expert C++/CLI:.NET for Visual C++ Programmers

Java Primer 1: Types, Classes and Operators

C# Language Reference

C# in Unity 101. Objects perform operations when receiving a request/message from a client

Asynchronous Programming Model (APM) 1 Calling Asynchronous Methods Using IAsyncResult 4 Blocking Application Execution by Ending an Async Operation

Computing is about Data Processing (or "number crunching") Object Oriented Programming is about Cooperating Objects

DigiPen Institute of Technology

CSC Java Programming, Fall Java Data Types and Control Constructs

Java An Introduction. Outline. Introduction

1 Shyam sir JAVA Notes

CS260 Intro to Java & Android 03.Java Language Basics

Tokens, Expressions and Control Structures

EVALUATION COPY. Unauthorized reproduction or distribution is prohibitied C# ESSENTIALS

Programming Kotlin. Familiarize yourself with all of Kotlin s features with this in-depth guide. Stephen Samuel Stefan Bocutiu BIRMINGHAM - MUMBAI

C# Programming: From Problem Analysis to Program Design. Fourth Edition

Object Oriented Programming

THE CONCEPT OF OBJECT

Compiler Errors. Flash CS4 Professional ActionScript 3.0 Language Reference. 1 of 18 9/6/2010 9:40 PM

2. A GUI A. uses buttons, menus, and icons B. should be easy for a user to manipulate C. both (a) and (b) D. stands for Graphic Use Interaction

CHETTINAD COLLEGE OF ENGINEERING & TECHNOLOGY JAVA

DOT NET Syllabus (6 Months)

C#: advanced object-oriented features

Short Notes of CS201

Module 4: Data Types and Variables

Prerequisites: The student should have programming experience in a high-level language. ITCourseware, LLC Page 1. Object-Oriented Programming in C#

PES INSTITUTE OF TECHNOLOGY (BSC) V MCA, Second IA Test, OCTOBER 2017 Programming Using C#.NET (13MCA53) Solution Set Faculty: Jeny Jijo

Java Overview An introduction to the Java Programming Language

CS201 - Introduction to Programming Glossary By

Object Oriented Programming in C#

An Async Primer. By Bill Wagner August Introduction

Getting started with Java

BIT Java Programming. Sem 1 Session 2011/12. Chapter 2 JAVA. basic

A Fast Review of C Essentials Part I

{ JSL } phone +44 (0)

How to be a C# ninja in 10 easy steps. Benjamin Day

Exercise Session Week 8

STRUCTURING OF PROGRAM

Exercise Session Week 8

Introduction to C++/CLI 3. What C++/CLI can do for you 6 The rationale behind the new syntax Hello World in C++/CLI 13

Transcription:

Distribution and Integration Technologies C# Language

Classes Structs Interfaces Delegates Enums C# Java C C++ C# C++.NET A C# program is a collection of: (can be grouped in namespaces) One entry point (static int Main(string[ ] args)) Some aspects of the C# Language 2

C# Types CTS type intrinsic C# type (defined by a keyword) System.SByte sbyte (8 bits) System.Byte byte (8 bits) System.Int16 short (16 bits) System.UInt16 ushort (16 bits) System.Int32 int (32 bits) System.UInt32 uint (32 bits) System.Int64 long (64 bits) System.UInt64 ulong (64 bits) System.Char char (unicode) System.Single float (32 bits) System.Double double (64 bits) System.Boolean bool (true/false) System.Decimal decimal (128 bits - fixed point) System.Object object System.String string System.Array [ ] Some aspects of the C# Language 3

Naming Conventions Casing Words are capitalized (z.b. ShowDialog) First letter in upper case, except for local variables, private fields and constants constants upper case SIZE, MAX_VALUE local variables lower case i, top, sum private fields lower case data, lastelement public fields upper case Width, BufferLength properties upper case Length, FullName enumeration constants upper case Red, Blue methods upper case Add, IndexOf types upper case StringBuilder (predefined types in lower case: int, string) namespaces upper case System, Collections First word Names of void methods should start with a verb (e.g. GetHashCode) Other names should start with a noun (e.g. size, IndexOf, Collections) Enumeration constants or bool members may start with an adjective (Red, Empty) Some aspects of the C# Language 4

Operators and Statements Operators: Same as C/C++ plus some others: typeof(obj or type) (representation as Type), is (tests a type), as (cast or null) Statements: assignment; expression; if (bool_exp) { [ else { ] switch (expr) switch_block while (bool_expr) { do { while (bool_expr); for (init; cond; iter) { foreach (var in expr) { break; continue; throw [ expr ]; return [ expr ]; try { catch [ ( exception ) ] { finally { lock (obj) { using ( res_expr ) { Some aspects of the C# Language 5

C# Classes Each class can have: Fields and Constants (const and readonly) Methods + constructors (instance and type) Finalizers Properties and indexers Events Operators and converters Nested types Other class characteristics Simple inheritance (but multiple interfaces) Values can be treated as objects Much more Some aspects of the C# Language 6

Example C# - Value as an object int i = 123; object o = i; int j = (int) o; i 123 o? 123 System.Int32 Boxing j 123 Unboxing Some aspects of the C# Language 7

Boxing and unboxing struct Point { public int x, y; class App { static void Main( ) { ArrayList a = new ArrayList( ); Point p; for (int k = 0; k < 10; k++) { p.x = p.y = 1; a.add(p); Point p1 = (Point) a[4]; class App { static void Main( ) { Point p; p.x = 10; p.y = 20 ; Console.WriteLine(p.ToString()); Console.WriteLine(p.GetType()); Point p2 = (Point) p.clone(); public virtual void Add(object o); ICloneable c = p2; automatic boxing object o = c.clone(); explicit p = unboxing (Point) o; Another example Some aspects of the C# Language 8

C# Modifiers Type attributes abstract sealed Accessibility for types, fields and methods private (default for methods, fields) protected internal (default for non-nested) protected internal (or) public (protected and internal) (not supported in C#) Method attributes (none) - instance static virtual new override abstract Field attributes (none) - instance static const readonly Some aspects of the C# Language 9

Finalizers Execute before the destruction of objects by the garbage collector It is a non deterministic execution Don t have any modifiers class Test {... ~Test( ) { // finalization work // automatically calls the base class // finalizer Some aspects of the C# Language 10

Properties Smart Fields (methods used with a field syntax) class Data { FileStream s; public string FileName { set { s = new FileStream(value, FileMode.Create); get { return s.name; Usage: Data d = new Data(); d.filename = myfile.txt ; string name = d.filename; For a property that is simply a getter and/or a setter of a private field we don t need to write the code: public int SomeValue { get; set; Some aspects of the C# Language 11

Indexers methods that are used as an array element syntax Usage: class File { FileStream s;... public int this [int index] { get { s.seek(index, SeekOrigin.Begin); return s.readbyte(); set { s.seek(index, SeekOrigin.Begin); s.writebyte( (byte)value ); File f =... int x = f[10]; f[11] = (int) A ; It s possible to define several indexers with different index types Some aspects of the C# Language 12

Nested types It s possible to define types inside types (usually classes) class A { int x; B b = new B(this); public void f() { b.f(); public class B{ A a; public B(A a) { this.a = a; public void f() { a.x=...;... a.f(); Internal classes can access any member from the external one (even private) External classes can only access public members of the internal classes Other classes can access the internal classes only if they are public Structures, enumerations, interfaces and delegates can also be nested class C {... A a = new A(); A.B b = new A.B(a);... Some aspects of the C# Language 13

Generics Type parameters applied to classes, interfaces, methods, events or delegates public class MyStack<T> { T[] items = null; int top = 0; public MyStack(int capacity) { items = new T[capacity]; public void Push(T item) { public T Pop() { MyStack<double> astack = new MyStack<double>(100); Some aspects of the C# Language 14

Delegates (1) A delegate is a type representing a method (a smart, verifiable, method pointer type) They can be instantiated with any method corresponding to the declared signature When invoked executes the method used to instantiate it Declaration: delegate void Notifier( string sender ); Variable: Notifier greetings; Equal to the declaration of a method, but adding the delegate keyword Instantiation: void SayHello(string sender) { Console.WriteLine("Hello from " + sender); greetings = new Notifier(SayHello); greetings = SayHello; or Usage: greetings( Mike ); // invokes SayHello( Mike ) Some aspects of the C# Language 15

Delegates (2) The delegates are multicast: this means that they can contain several methods (they must have all the same signature) In this case, when invoked, they execute all the included methods Notifier greetings; greetings = SayHello; greetings += SayGoodBye; greetings("john"); // "Hello from John // "Good bye from John greetings -= SayHello; greetings( Mike"); // "Good bye from Mike" When a delegate returns a value and is multicast, only the value from the last call is returned (the same for out parameters) Some aspects of the C# Language 16

Anonymous Methods When needing or instantiating a delegate we can use anonymous methods: Some examples: delegate void SomeDel(int x); SomeDel adel = delegate(int k) { k // explicit delegate initialization // delegate method parameter void CreateAThread() { Thread t1 = new Thread(delegate() { ); t1.start(); button1.click += delegate(object sender, EventArgs e) { MessageBox.Show( Button pressed! ); // event handler Some aspects of the C# Language 17

Lambdas Simple forms to express anonymous methods used to instantiate delegates (input parameters) => expression (x, y) => x == y (int x, string s) => s.length > x () => SomeMethod() x => x * x (input parameters) => { statements n => { string s = n + " " + "World"; Console.WriteLine(s); Lambdas can be asynchronous if declared so async (input parameters) => { statements Some aspects of the C# Language 18

Events (1) An event is a member (variable) belonging to a special delegate type (keyword event) Can be subscribed by other classes Only the class that declares the event can fire it (invoke) class Model { public event Notifier notifyviews; public void Change() {... notifyviews("model"); // fire the event class View { public View(Model m) { m.notifyviews += Update; // subscribe the event void Update(string sender) { Console.WriteLine(sender + " was changed"); class Test { static void Main() { Model m = new Model(); new View(m); m.change(); Some aspects of the C# Language 19

Events (2) delegate void handler( ); public class event_gen { public event handler ev; void method( ) { if ( ) if (ev!= null) ev( ); public class use_event { use_event( ) { event_gen evg = new event_gen( ); evg.ev += new handler(ev_hdlr); void ev_hdlr( ) { // fire the event // register a listener Some aspects of the C# Language 20

Asynchronous Calls (1) The CLR allows that any method from any class or struct (including remote ones) could be invoked asynchronously. A new thread is automatically Synchronous Call created to execute the call. Caller call Callee Synchronous call Caller async call caller and callee run in parallel Callee Asynchronous call wait for result return result Some aspects of the C# Language 21

Asynchronous Calls (2) Classical code in C# (using a delegate) We only need to create a delegate instantiated with the method to call, and invoke the BeginInvoke( ) method from the delegate instance delegate name ( ); name del = new name ( f ); AsyncCallback cb = new AsyncCallback(Handler) IAsyncResult ar = del.begininvoke( params, ); ar.iscompleted void Handler(IAsyncResult ar) { v = del.endinvoke(ar); v = del.endinvoke(ar); Demo Sieve EndInvoke() collects the call result Some aspects of the C# Language 22

Asynchronous Calls (3) A recent version of C# (5.0) introduced the keywords async and await Can be used with the Task.NET class async marks methods that have asynchronous calls inside them await make an immediate return, and continues execution after the call completes the call can be a Task.Run or other async method async void MethodAsync(int par) { // preparation int res = await Task.Run<int>( () => MyTask(par) ); // do something with res - completion int MyTask(int par) { // some code MethodAsync(1000); async methods can return: void, Task or Task<T> Task has the property IsCompleted to test in the caller if the async method has already executed to completion Task<T> has the property Result. Getting it waits for completion. Some aspects of the C# Language 23

Keywords async and await async void FooAsync() {... Task<int> task = CalcAsync();...... int result = await task;...... Caller FooAsync(); Task<int> CalcAsync() { return Task.Run(() => {...); FooAsync() task = CalcAsync(); CalcAsync() If a method contains await it must be marked as async and should have the suffix Async task and section run in parallel meaning of await: - if task ready => get its result and continue with - if not ready => return to caller and continue there; execute ("continuation") when task gets ready Caller FooAsync(); FooAsync() task = CalcAsync(); CalcAsync() result = await task; threads marked by different colors result = await task; "continuation" Some aspects of the C# Language 24

Accessing native code Invoking native code from native dynamic libraries (DLL s) is very simple. The native functions run in the same application domain that calls them. We need only to declare the functions using the static extern modifiers, inside some class or struct class something { [DllImport( some.dll )] static extern int some_func(char ch, double d); void method( ) { v = some_func( b, 14.21); Simple types are transformed correctly by default. For more complex types we can use some.net attributes to guide their transformation and memory layout (for instance in structs) Some aspects of the C# Language 25

Framework Class Library (FCL) System Int32, String, UI Web Services Data Connection, DataSet, Windows Forms EnterpriseServices ServicedComponent, XML Runtime XmlDocument, Remoting FCL evolution Organized in nested namespaces System is the base Some aspects of the C# Language 26