DEV300: Advanced C# Eric Gunnerson Program Manager Visual C# Microsoft Corporation.

Slides:



Advertisements
Similar presentations
Introduction to Java 2 Programming Lecture 3 Writing Java Applications, Java Development Tools.
Advertisements

C# Language Report By Trevor Adams. Language History Developed by Microsoft Developed by Microsoft Principal Software Architect Principal Software Architect.
Copyright © 2012 Pearson Education, Inc. Chapter 8 Exception Handling.
C# Types Tom Roeder CS fa. Administration CMS is up let me know if you can’t see the course Assignments are posted may not be able to do some.
CS 4800 By Brandon Andrews.  Specifications  Goals  Applications  Design Steps  Testing.
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#C# C#C# Kit Colbert Student Consultant representing Microsoft
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#
Shallow Versus Deep Copy and Pointers Shallow copy: when two or more pointers of the same types point to the same memory – They point to the same data.
Object-Oriented Programming in C# Object-Oriented CSE Prof. Roger Crawfis.
Platforms and tools for Web Services and Mobile Applications Introduction to C# Bent Thomsen Aalborg University 3rd and 4th of June 2004.
Java vs. C# By Abrar Siddiqui.
Differences between C# and C++ Dr. Catherine Stringfellow Dr. Stewart Carpenter.
OOP Languages: Java vs C++
Inheritance. Types of Inheritance Implementation inheritance means that a type derives from a base type, taking all the base type’s member fields and.
Java and C++, The Difference An introduction Unit - 00.
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
1 Review of Java Higher Level Language Concepts –Names and Reserved Words –Expressions and Precedence of Operators –Flow of Control – Selection –Flow of.
EECE 310: Software Engineering Lecture 2: Understanding Objects in Java and Types.
BIM313 – Advanced Programming Techniques Object-Oriented Programming 1.
Exceptions Programming in C# Exceptions CSE 494R (proposed course for 459 Programming in C#) Prof. Roger Crawfis.
Algorithm Programming Bar-Ilan University תשס"ח by Moshe Fresko.
Programming Language C++ Xulong Peng CSC415 Programming Languages.
Overloading Binary Operators Two ways to overload –As a member function of a class –As a friend function As member functions –General syntax Data Structures.
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.
Advanced C# Eric Gunnerson Program Manager Visual C#.NET Microsoft Corporation.
Effective.NET Framework based Development: Exception Handing and Memory Management Effective.NET Framework based Development: Exception Handing and Memory.
ILM Proprietary and Confidential -
More about Class 靜宜大學資工系 蔡奇偉副教授 ©2011. 大綱 Instance Class Members Class members can be associated with an instance of the class or with the class as a.
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.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
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)
CSC1401 Classes - 2. Learning Goals Computing concepts Adding a method To show the pictures in the slide show Creating accessors and modifiers That protect.
CS 376b Introduction to Computer Vision 01 / 23 / 2008 Instructor: Michael Eckmann.
C# Classes and Inheritance CNS 3260 C#.NET Software Development.
Computing with C# and the.NET Framework Chapter 2 C# Programming Basics ©2003, 2011 Art Gittleman.
Session 7 Methods Strings Constructors this Inheritance.
Bill Campbell, UMB Microsoft's.NET C# and The Common Language Runtime.
Introduction to Java Chapter 7 - Classes & Object-oriented Programming1 Chapter 7 Classes and Object-Oriented Programming.
C# Operator Overloading and Type Conversions C#.NET Software Development Version 1.0.
Chapter 10: Classes and Data Abstraction. Objectives In this chapter, you will: Learn about classes Learn about private, protected, and public members.
CS-1030 Dr. Mark L. Hornick 1 Basic C++ State the difference between a function/class declaration and a function/class definition. Explain the purpose.
PerlNET: The Camel Talks.NET Jan Dubois The Perl Conference 6 San Diego, July 26 th 2002.
Lecture 8: Object Oriented Programming. What is a Programming Object? An object is an instance of a class. A class is a template for an object. Everything's.
CSC 298 Streams and files.
Introduction to C# By: Abir Ghattas Michel Barakat.
DEV394.NET Framework: Migrating To Managed Code Adam Nathan QA Lead Richard Lander Program Manager Microsoft Corporation.
Chapter 10: Classes and Data Abstraction. Classes Object-oriented design (OOD): a problem solving methodology Objects: components of a solution Class:
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 Handling Errors and Exceptions Chapter 6. 2 Objectives You will be able to: 1. Use the try, catch, and finally statements to handle exceptions. 2. Raise.
 It is a pure oops language and a high level language.  It was developed at sun microsystems by James Gosling.
Java Programming: Guided Learning with Early Objects Chapter 9 Inheritance and Polymorphism.
INTRODUCTION BEGINNING C#. C# AND THE.NET RUNTIME AND LIBRARIES The C# compiler compiles and convert C# programs. NET Common Language Runtime (CLR) executes.
Konstantinos pantos Software solutions architect Techaholics
C# - OOP TTU IT College , Autumn SEMESTER Andres käver.
Jim Fawcett CSE681 – SW Modeling & Analysis Fall 2014
Static data members Constructors and Destructors
Computing with C# and the .NET Framework
CS360 Windows Programming
C# In many ways, C# looks similar to Java
.NET and .NET Core 5.2 Type Operations Pan Wuming 2016.
Java Programming Language
Module 2 Variables, Assignment, and Data Types
Jim Fawcett CSE681 – SW Modeling & Analysis Fall 2018
Chengyu Sun California State University, Los Angeles
Presentation transcript:

DEV300: Advanced C# Eric Gunnerson Program Manager Visual C# Microsoft Corporation

A data type of your very own A data type of your very own Deterministic finalization Deterministic finalization Versioning Versioning Language tips and tricks Language tips and tricks Interoperability Interoperability Advanced C# Topics

A data type of your very own A data type of your very own Deterministic finalization Deterministic finalization Versioning Versioning Language tips and tricks Language tips and tricks Interoperability Interoperability Advanced C# Topics

A Data Type Of Your Own A type that has A type that has  Operator Overloading  User-defined conversions  XML Documentation  Properties A type like Decimal… A type like Decimal…

Reference Or Value type? Data types all have value semantics Data types all have value semantics  val1 = val2 means copy value, not make val1 point at val2 Value type is the right choice unless Value type is the right choice unless  The type is of variable size (like string)  The type is big (> 16ish bytes) Reference types must be immutable Reference types must be immutable  Methods don’t modify value  Methods return new instance  Like string type

Two Data Types demo demo

Intro To Animation To animate a ball, we need to track: To animate a ball, we need to track:  Position (a point)  Velocity (a vector) Each frame, add velocity to position Each frame, add velocity to position Handle collisions as necessary Handle collisions as necessary

Collision With A Circle c v vc V vc = c * (c · v / |c| 2 ) v = ball velocity v = v – vc * 2 Vector c = new Vector(center, position); Float dot = Vector.DotProduct(c, v); Float len = c.Length; Vector vc = c * (dot / (len * len)); v = v - vc * 2; c = center to ball center

A data type of your very own A data type of your very own Deterministic finalization Deterministic finalization Versioning Versioning Language tips and tricks Language tips and tricks Interoperability Interoperability Advanced C# Topics

Deterministic Finalization Means “you know exactly when an object is destroyed” Means “you know exactly when an object is destroyed” You want it You want it You can’t have it You can’t have it  A very complicated discussion  See  Look for article on Resource management

Object Destruction Two main issues: Two main issues:  Garbage collection means non- deterministic finalization  GC chooses:  When objects are destroyed  Order of destruction  Garbage collector can’t clean up unmanaged objects

Solution Cleanup at GC time Cleanup at GC time  Objects with unmanaged resources implement a finalizer to free those resources Early Cleanup Early Cleanup  Objects implement IDisposable, users call Dispose() to clean up

Scenario 1 User Calls Dispose() Unmanaged Resource Font object Dispose() Dispose() free IntPtr myResource; Font font; Dispose() means free my resources, and call Dispose() on any contained objects

Scenario 2 Object Finalized by GC Unmanaged Resource Font object Finalize() Dispose()? free IntPtr myResource; Font font; Finalize() means free my resources only; other managed resources will also get finalized X Finalize()

Implementing IDisposable Design pattern for early cleanup Design pattern for early cleanup Only required when you: Only required when you:  Wrap unmanaged resources  You’ll need a destructor too OR OR  Need to be able to clean up early Not required for the vast majority of objects Not required for the vast majority of objects

Destructors Object.Finalize is not accessible in C# Object.Finalize is not accessible in C# public class Resource: IDisposable { ~Resource() {...} ~Resource() {...}} public class Resource: IDisposable { protected override void Finalize() { protected override void Finalize() { try { try { } finally { finally { base.Finalize(); base.Finalize(); } }}

Doing The Implementation public class Resource: IDisposable { IntPtr myResource; IntPtr myResource; Font font; Font font; protected virtual void Dispose(bool disposing) { protected virtual void Dispose(bool disposing) { if (disposing) { if (disposing) { font.Dispose(); font.Dispose(); GC.SuppressFinalize(this); GC.SuppressFinalize(this); } FreeThatResource(myResource); FreeThatResource(myResource); } public void Dispose() { Dispose(true); Dispose(true); } ~Resource() { ~Resource() { Dispose(false); Dispose(false); }}

Using Statement Acquire, Execute, Release pattern Acquire, Execute, Release pattern Works with any IDisposable object Works with any IDisposable object  Data access classes, streams, text readers and writers, network classes, etc. using (Resource res = new Resource()) { res.DoWork(); res.DoWork();} Resource res = new Resource(...); try { res.DoWork(); res.DoWork();} finally { if (res != null) ((IDisposable)res).Dispose(); if (res != null) ((IDisposable)res).Dispose();}

Using Statement static void Copy(string sourceName, string destName) { Stream input = File.OpenRead(sourceName); Stream input = File.OpenRead(sourceName); Stream output = File.Create(destName); Stream output = File.Create(destName); byte[] b = new byte[65536]; byte[] b = new byte[65536]; int n; int n; while ((n = input.Read(b, 0, b.Length)) != 0) { while ((n = input.Read(b, 0, b.Length)) != 0) { output.Write(b, 0, n); output.Write(b, 0, n); } output.Close(); output.Close(); input.Close(); input.Close();} static void Copy(string sourceName, string destName) { Stream input = File.OpenRead(sourceName); Stream input = File.OpenRead(sourceName); try { try { Stream output = File.Create(destName); Stream output = File.Create(destName); try { try { byte[] b = new byte[65536]; byte[] b = new byte[65536]; int n; int n; while ((n = input.Read(b, 0, b.Length)) != 0) { while ((n = input.Read(b, 0, b.Length)) != 0) { output.Write(b, 0, n); output.Write(b, 0, n); } } finally { finally { output.Close(); output.Close(); } } finally { finally { input.Close(); input.Close(); }} static void Copy(string sourceName, string destName) { using (Stream input = File.OpenRead(sourceName)) using (Stream input = File.OpenRead(sourceName)) using (Stream output = File.Create(destName)) { using (Stream output = File.Create(destName)) { byte[] b = new byte[65536]; byte[] b = new byte[65536]; int n; int n; while ((n = input.Read(b, 0, b.Length)) != 0) { while ((n = input.Read(b, 0, b.Length)) != 0) { output.Write(b, 0, n); output.Write(b, 0, n); } }}

A data type of your very own A data type of your very own Deterministic finalization Deterministic finalization Versioning Versioning Language tips and tricks Language tips and tricks Interoperability Interoperability Advanced C# Topics

Versioning What happens when base components are changed? What happens when base components are changed? Versioning an important design goal Versioning an important design goal  Virtual methods and overriding  Overload resolution  Explicit interface implementation  Const vs. readonly fields  Defaults for accessibility and virtuality

Versioning: Overriding class Derived: Base// version 1 { public virtual void Foo() { public virtual void Foo() { Console.WriteLine("Derived.Foo"); Console.WriteLine("Derived.Foo"); }} class Derived: Base// version 2a { new public virtual void Foo() { new public virtual void Foo() { Console.WriteLine("Derived.Foo"); Console.WriteLine("Derived.Foo"); }} class Derived: Base// version 2b { public override void Foo() { public override void Foo() { base.Foo(); base.Foo(); Console.WriteLine("Derived.Foo"); Console.WriteLine("Derived.Foo"); }} class Base// version 1 {} class Base // version 2 { public virtual void Foo() { public virtual void Foo() { Console.WriteLine("Base.Foo"); Console.WriteLine("Base.Foo"); }}

Versioning: Overloading public class Base// version 1 {} public class Derived: Base// version 1 { public void Add(double x) {...} public void Add(double x) {...}} Derived d = new Derived(...); d.Add(1); public class Base// version 2 { public void Add(int x) {...} public void Add(int x) {...}}

Versioning: Interfaces interface IGraphics { void Draw(); void Draw(); Brush Brush { get; set; } Brush Brush { get; set; } Pen Pen { get; set; } Pen Pen { get; set; }} interface IBandit { void Draw(); void Draw(); void Duel(IBandit opponent); void Duel(IBandit opponent); void Rob(Bank bank, IBandit[] sidekicks); void Rob(Bank bank, IBandit[] sidekicks);} class Bandit: IGraphics { public void Draw() {...} public void Draw() {...}} class Bandit: IGraphics, IBandit { public void Draw() {...} // Which interface? public void Draw() {...} // Which interface?} class Bandit: IBandit, IGraphics { public void Draw() {...} public void Draw() {...} void IGraphics.Draw() {...} void IGraphics.Draw() {...}} class Bandit: IBandit, IGraphics { void IBandit.Draw() {...} void IBandit.Draw() {...} void IGraphics.Draw() {...} void IGraphics.Draw() {...}}

A data type of your very own A data type of your very own Deterministic finalization Deterministic finalization Versioning Versioning Language tips and tricks Language tips and tricks Interoperability Interoperability Advanced C# Topics

Definite Assignment A variable must be definitely assigned before its value can be obtained A variable must be definitely assigned before its value can be obtained Auto-initialized vs. unassigned Auto-initialized vs. unassigned Static flow analysis looks at all possible execution paths Static flow analysis looks at all possible execution paths static int Mumble(int flags) { int n; int n; if (flags != 0){ if (flags != 0){ n = Something(); n = Something(); } return n; return n;}

void printf(string fmt, object[] args) { foreach (object x in args) { foreach (object x in args) { }} void printf(string fmt, params object[] args) { foreach (object x in args) { foreach (object x in args) { }} object[] args = new object[3]; args[0] = str; args[1] = int1; args[2] = int2; printf("%s %i %i", args); printf("%s %i %i", str, int1, int2); object[] args = new object[3]; args[0] = str; args[1] = int1; args[2] = int2; printf("%s %i %i", args); Parameter Arrays Methods with a variable number of parameters Methods with a variable number of parameters

Ref And Out Parameters Use “ref” for in/out parameter passing Use “ref” for in/out parameter passing Use “out” to return multiple values Use “out” to return multiple values Must repeat ref/out at call site Must repeat ref/out at call site static void Swap(ref int a, ref int b) {...} static void Divide(int dividend, int divisor, out int result, out int remainder) {...} out int result, out int remainder) {...} static void Main() { int x = 1, y = 2; int x = 1, y = 2; Swap(ref x, ref y); Swap(ref x, ref y);}

Is, As, And Typeof Operators Check if a conversion will succeed Check if a conversion will succeed Perform exception-free conversion Perform exception-free conversion Get System.Type object for a type Get System.Type object for a type if (o is string) { string s = (string)o; string s = (string)o; LogString(s); LogString(s);} string s = o as string; if (s != null) Console.WriteLine(s); if (o.GetType() == typeof(string)) Console.WriteLine("o is a string"); Console.WriteLine("o is a string");

Overflow Checking Integer arithmetic operations Integer arithmetic operations  C, C++, Java silently overflow checked vs. unchecked context checked vs. unchecked context  Default is unchecked, except for constants  Change with “/checked” compiler switch int i = checked(x * y); checked { int i = x * y; int i = x * y;}

Throw Statement Throw exception: throw e; Throw exception: throw e; Re-throw exception: throw; Re-throw exception: throw; try { DoSomething(); DoSomething();} catch (Exception e) { LogError(...); LogError(...); throw; throw;}

Foreach Statement Iteration of arrays Iteration of arrays Iteration of IEnumerable collections Iteration of IEnumerable collections foreach (Account a in Bank.GetAccounts(...)) { if (a.Balance < 0) Console.WriteLine(a.CustName); if (a.Balance < 0) Console.WriteLine(a.CustName);} public static void Main(string[] args) { foreach (string s in args) Console.WriteLine(s); foreach (string s in args) Console.WriteLine(s);}

Foreach Statement Can be modified with user-written classes Can be modified with user-written classes See my December 2001 column for more information See my December 2001 column for more information  foreach (string s in new IterReverse(names)) {...} foreach (DateTime t in new IterSort(times)) {...}

Lock Statement Use lock for mutual exclusion Use lock for mutual exclusion  Protect member vars from other threads Use typeof as lock for static methods Use typeof as lock for static methods class Cache { ArrayList objects = new ArrayList(); ArrayList objects = new ArrayList(); public void Add(object x) { public void Add(object x) { lock (this) { lock (this) { objects.Add(x); objects.Add(x); } } public static Cache Create() { public static Cache Create() { lock(typeof(Cache)) {...} lock(typeof(Cache)) {...} }}

A data type of your very own A data type of your very own Deterministic finalization Deterministic finalization Versioning Versioning Language tips and trick or treat Language tips and trick or treat Interoperability Interoperability Advanced C# Topics

Unsafe Code When pointers are a necessity When pointers are a necessity  Advanced COM and P/Invoke interop  Existing binary structures  Performance extremes Low-level code without leaving the box Low-level code without leaving the box Basically “inline C” Basically “inline C”

struct COFFHeader { public ushort MachineType; public ushort MachineType; public ushort NumberOfSections; public ushort NumberOfSections; … public ushort Characteristics; public ushort Characteristics;} private COFFHeader fileHeader; void ReadHeader(BinaryStream InFile) { fileHeader.MachineType = inFile.ReadUInt16(); fileHeader.MachineType = inFile.ReadUInt16(); fileHeader.NumberOfSections = inFile.ReadUInt16(); fileHeader.NumberOfSections = inFile.ReadUInt16(); // … // … fileHeader.Characteristics = inFile.ReadUInt16(); fileHeader.Characteristics = inFile.ReadUInt16();} private COFFHeader fileHeader; unsafe void ReadHeader(BinaryStream InFile) { byte[] buffer = InFile.ReadBytes(sizeof(COFFHeader)); byte[] buffer = InFile.ReadBytes(sizeof(COFFHeader)); fixed (byte* headerPtr = buffer) fixed (byte* headerPtr = buffer) { fileHeader = *((COFFHeader*)headerPtr); fileHeader = *((COFFHeader*)headerPtr); }} Existing Binary Structures

Image Processing demo demo

Additional Resources C# Community Sites C# Community Sites   See information page for my columns  C# newsgroup C# newsgroup  microsoft.public.dotnet.languages.csharp Me: Me:

August 19-23, 2002 Redmond, WA 5 days of training5 days of training 36 sessions, 3 tracks36 sessions, 3 tracks Fun evening activitiesFun evening activities

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