Introduction to C # – Part 2 Stephen Turner Software Design Engineer Microsoft UK.

Slides:



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

Introduction to C# Anders Hejlsberg Distinguished Engineer Developer Division Microsoft Corporation.
The C ++ Language BY Shery khan. The C++ Language Bjarne Stroupstrup, the language’s creator C++ was designed to provide Simula’s facilities for program.
C# Language Report By Trevor Adams. Language History Developed by Microsoft Developed by Microsoft Principal Software Architect Principal Software Architect.
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.
6/10/2015C++ for Java Programmers1 Pointers and References Timothy Budd.
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
1.NET and C# Peter Groenewegen Vrije Universiteit
AP 08/01 Component Programming with C# and.NET 1st Class Component Support Robust and Versionable Creating and using attributes API integration –DLL import.
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++
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++
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 
CS-341 Dick Steflik Introduction. C++ General purpose programming language A superset of C (except for minor details) provides new flexible ways for defining.
C#/.NET Jacob Lewallen. C# vs.NET.NET is a platform. Many languages compile to.NET: –VB.NET –Python.NET –Managed C++ –C#
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.
Reference Types. 2 Objectives Introduce reference types –class –array Discuss details of use –declaration –allocation –assignment –null –parameter –aggregation.
Platforms and tools for Web Services and Mobile Applications Introduction to C# Bent Thomsen Aalborg University 3rd and 4th of June 2004.
Differences between C# and C++ Dr. Catherine Stringfellow Dr. Stewart Carpenter.
OOP Languages: Java vs C++
Programming Languages and Paradigms Object-Oriented Programming.
1 Inheritance and Polymorphism Chapter 9. 2 Polymorphism, Dynamic Binding and Generic Programming public class Test { public static void main(String[]
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics C# Language &.NET Platform 7 th & 8 th Lecture Pavel Ježek.
EECE 310: Software Engineering Lecture 2: Understanding Objects in Java and Types.
EE4E. C++ Programming Lecture 1 From C to C++. Contents Introduction Introduction Variables Variables Pointers and references Pointers and references.
MESDA Conference 2002 MESDA Annual Conference 2002 Software Development Track Java vs. C#
Java Implementation: Part 3 Software Construction Lecture 8.
Managed C++. Objectives Overview to Visual C++.NET Concepts and architecture Developing with Managed Extensions for C++ Use cases Managed C++, Visual.
Algorithm Programming Bar-Ilan University תשס"ח by Moshe Fresko.
Programming Language C++ Xulong Peng CSC415 Programming Languages.
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.
Applied Computing Technology Laboratory QuickStart C# Learning to Program in C# Amy Roberge & John Linehan November 7, 2005.
Constructors CMSC 202. Object Creation Objects are created by using the operator new in statements such as… The following expression invokes a special.
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.
CS 376b Introduction to Computer Vision 01 / 23 / 2008 Instructor: Michael Eckmann.
ISBN Chapter 6 Data Types Introduction Primitive Data Types User-Defined Ordinal Types.
C# Classes and Inheritance CNS 3260 C#.NET Software Development.
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
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,
Bill Campbell, UMB Microsoft's.NET C# and The Common Language Runtime.
1 9/6/05CS360 Windows Programming CS360 Windows Programming.
Operator Overloading Week 5.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
SOEN 343 Software Design Section H Fall 2006 Dr Greg Butler
Object Oriented Software Development 4. C# data types, objects and references.
CMSC 202 Advanced Section Classes and Objects: Object Creation and Constructors.
How to execute Program structure Variables name, keywords, binding, scope, lifetime Data types – type system – primitives, strings, arrays, hashes – pointers/references.
DEV394.NET Framework: Migrating To Managed Code Adam Nathan QA Lead Richard Lander Program Manager Microsoft Corporation.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
Classes Single inheritance Single inheritance Multiple interface implementation Multiple interface implementation Class members Class members  Constants,
Introduction to C# Anders Hejlsberg Distinguished Engineer Developer Division Microsoft Corporation.
© 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.
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 –
1 Statements © University of Linz, Institute for System Software, 2004 published under the Microsoft Curriculum License.
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.
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics Advanced.NET Programming II 3 rd Lecture Pavel Ježek
Value Types. 2 Objectives Discuss concept of value types –efficiency –memory management –value semantics –boxing –unboxing –simple types Introduce struct.
EECE 309: Software Engineering
Object Lifetime and Pointers
The 100% Inspiration Tour.
Advanced .NET Programming II 4th Lecture
Java Primer 1: Types, Classes and Operators
CS360 Windows Programming
.NET and .NET Core 5.2 Type Operations Pan Wuming 2016.
Conditional Statements
Pointers C#, pointers can only be declared to hold the memory addresses of value types int i = 5; int *p; p = &i; *p = 10; // changes the value of i to.
Paul Stubbs MCSD, MCSE 4.0, MCP+I, MCT, MCAD .Net
CMSC 202 Constructors Version 9/10.
Presentation transcript:

Introduction to C # – Part 2 Stephen Turner Software Design Engineer Microsoft UK

Agenda Design goals – Part 2  Fully extensible type system  Enable robust and durable applications  Leverage existing software Standardization

Extending the Type System Most users think of two types of objects  “Real” objects – Customer, Order, etc.  Primitive types – int, float, bool Different expectations for each  Real objects are more expensive to create  Primitives always have a value  Primitives have operator support Classes and Structs – best of both worlds! Natural semantics  Operator overloading & User conversions Interface support

Rational Numbers (½, ¾, 1½) Rational r1 = new Rational(1,2); Rational r2 = new Rational(2,1); Rational r3 = r1.AddRational(r2); double d = Rational.ConvertToDouble(r3); Rational r1 = new Rational(1,2); Rational r2 = 2; Rational r3 = r1 + r2; double d = (double) r3;

Rational Number – Class? Heap allocated Can be null “=” assigns reference not value Arrays allocate references not values public class Rational { public Rational(int n, int d) { … } } … Rational[] array = new Rational[100];

Structs Provide an Answer Behavior differences versus Classes  Stored in-line, not heap allocated  Never null  Assignment copies data, not reference Implementation differences  Always inherit from object  Always has a default constructor

Rational Number – Struct public struct Rational { public Rational(int n, int d) { … } public int Numerator { get{…} } public int Denominator { get{…} } public override string ToString() { … } } Rational r = new Rational(1,2); string s = r.ToString();

Implicit Conversions No loss of data public struct Rational { … public static implicit operator Rational(int i) { return new Rational(i,1); } Rational r = 2;

Explicit Conversions Possible loss of precision and can throw exceptions public struct Rational { … public static explicit operator double(Rational r) { return (double) r.Numerator / r.Denominator; } Rational r = new Rational(2,3); double d = (double) r;

Operator Overloading Static operators Must take its type as a parameter public struct Rational { … public static Rational operator+ ( Rational lhs, Rational rhs) { return new Rational( … ); } Rational r3 = r1 + r2; r3 += 2;

Equality Operators.NET Framework equality support.Equals() should use operator==() public override bool Equals(object o) public static bool operator== (Rational lhs, Rational rhs) public static bool operator!= (Rational lhs, Rational rhs) if ( r1.Equals(r2) ) { … }if ( !r1.Equals(r2)) { … } if ( r1 == r2 ) { … }if ( r1 != r2 ) { … }

Structs and Interfaces Structs can implement interfaces to provide additional functionality Why? The same reasons classes can! Examples  System.IComparable  Search and sort support in collections  System.IFormattable  Placeholder formatting

System.IFormattable Types can support new formatting options through IFormattable Rational r1 = new Rational(2,4); Console.WriteLine(“Rational {0}", r1); Console.WriteLine(“Rational {0:reduced}", r1);

Implementing IFormattable public struct Rational : IFormattable { public string Format( string formatStr, IServiceObjectProvider isop) { s = this.ToString(); if ( formatStr == “reduced" ) { s = … } return s; } Rational r1 = new Rational(2,4); Console.WriteLine("No Format = {0}", r1); Console.WriteLine("Reduced Format = {0:reduced}", r1); No Format = 2/4 Reduced Format = 1/2

Agenda Design goals – Part 2  Fully extensible type system  Enable robust and durable applications  Leverage existing software Standardization

Robust and Durable Software Garbage collection  No memory leaks and stray pointers Exceptions  Error handling is not an afterthought Type-safety  No uninitialized variables, unsafe casts Versioning  Pervasive versioning considerations in all aspects of language design

Language Safety vs. C++ If, while, do require bool condition Goto can’t jump into blocks Switch statement  No fall-through  Break, goto or goto default Checked and unchecked statements Expression statements must do work void Foo() { i == 1; // error }

Versioning Overlooked in most languages  C++ and Java produce fragile base classes  Users unable to express versioning intent C# allows intent to be expressed  Methods are not virtual by default  C# keywords “virtual”, “override” and “new” provide context But C# can't guarantee versioning  Can enable (e.g., explicit override)  Can encourage (e.g., smart defaults)

Method Versioning in Java class Derived extends Base // v1.0 { public void Foo() public void Foo() { System.out.println("Derived.Foo"); System.out.println("Derived.Foo"); }} class Base // v1.0 {} class Base // v2.0 { public void Foo() public void Foo() { Database.Log("Base.Foo"); Database.Log("Base.Foo"); }} class Base // v2.0 { public int Foo() public int Foo() { Database.Log("Base.Foo"); Database.Log("Base.Foo"); }}

Method Versioning in C# class Derived : Base // v1.0 { public virtual void Foo() public virtual void Foo() { Console.WriteLine("Derived.Foo"); Console.WriteLine("Derived.Foo"); }} class Base // v1.0 {} class Base // v2.0 { public virtual void Foo() public virtual void Foo() { Database.Log("Base.Foo"); Database.Log("Base.Foo"); }} class Base // v2.0 { public virtual int Foo() public virtual int Foo() { Database.Log("Base.Foo"); return 0; Database.Log("Base.Foo"); return 0; }} class Derived : Base // v2.0 { public new virtual void Foo() public new virtual void Foo() { Console.WriteLine("Derived.Foo"); Console.WriteLine("Derived.Foo"); }} class Derived : Base // v2.0 { public override void Foo() public override void Foo() { super.Foo(); super.Foo(); Console.WriteLine("Derived.Foo"); Console.WriteLine("Derived.Foo"); }}

Agenda Design goals – Part 2  Fully extensible type system  Enable robust and durable applications  Leverage existing software Standardization

Calling Into Existing DLLs Runtime enables calling “C-Style” functions Feature known as “Platform Invoke” Attributes define how things work Which library to use [DllImport] How to marshal data [MarshalAs] Structure layout in memory [StructLayout] [FieldOffset]

DLL Import Examples [DllImport("gdi32.dll", CharSet=CharSet.Auto)] public static extern int GetObject( int hObject, int nSize,[In, Out] ref LOGFONT lf); [DllImport("gdi32.dll")] public static extern int CreatePen( int style, int width, int color);

Platform Invoke Limitations Marshaler can’t handle every case  Ugly dealing with memory allocation  Complex structures can’t be marshalled Complex P/Invoke is hard to debug  Play “convince the marshaller”… Can’t use C++ objects Can waste lots of time and effort  Did I say it was tough to debug? Solution:  Use unsafe C# or Managed C++

COM Support.NET Framework provides great COM support  TLBIMP imports existing COM classes  TLBEXP exports.NET types Sometimes you need more control  Methods taking complicated structures  Large TLB – only using a few classes System.Runtime.Interopservices  COM object identification  Parameter and return value marshalling  HRESULT behavior

COM Support Sometimes you need more control  Methods with complicated structures as arguments  Large TLB – only using a few classes System.Runtime.InteropServices  COM object identification  Parameter and return value marshalling  HRESULT behavior

COM Support Example [Guid(“56A868B1-0AD4-11CE-B03A-0020AF0BA770”)] interface IMediaControl { void Run(); void Pause(); void Stop(); … void RenderFile(string strFilename); }

Unsafe Code – Pointers Developers sometime need total control  Performance extremes  Dealing with existing binary structures  Advanced COM Support, DLL Import C# “unsafe” = limited “inline C”  Pointer types, pointer arithmetic  unsafe casts  Declarative pinning (fixed statement) Power comes at a price!  Unsafe means unverifiable code

Unsafe Code & P/Invoke class FileStream: Stream { int handle; public unsafe int Read( byte[] buffer, int index, int count) { int n = 0; fixed (byte* p = buffer) { ReadFile(handle, p + index, count, &n, null); } return n; } [dllimport("kernel32", SetLastError=true)] static extern unsafe bool ReadFile( int hFile, void* lpBuffer, int nBytesToRead, int* nBytesRead, Overlapped* lpOverlapped); }

Agenda Extending the type system  Creating a fully functional rational number type Enable robust and durable applications  Language safety & code versioning Leverage existing software investment  COM & DLL interop  Unsafe code and pointers Standardization

C# and CLI Standardization Work begun in September 2000  Intel, HP, IBM, Fujitsu, Plum Hall, and others ECMA ratified in December 2001 ISO ratified in April 2003 Several CLI and C# implementations .NET Framework and Visual Studio.NET  SSCLI – Shared source on XP, FreeBSD, OS X  Mono – Open source on Linux Standardization of new features ongoing

Useful Resources Web sites    Newsgroups   microsoft.public.dotnet.languages.csharp Books  C# Language Specification” – MS Press  Inside C# – MS Press

C# Momentum Over 50 trade books published  O’Reilly, Addison-Wesley, Prentice Hall, APress, Osborne, Sams, Wrox, MS Press Over 15 dedicated Web sites     Other site can be found at 

© 2003 Microsoft Ltd. All rights reserved. This presentation is for informational purposes only. Microsoft makes no warranties, express or implied, in this summary.