Advanced C# Eric Gunnerson Program Manager Visual C#.NET Microsoft Corporation.

Slides:



Advertisements
Similar presentations
Error-handling using exceptions
Advertisements

CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics C# Language &.NET Platform 12 th -13 th Lecture Pavel Ježek.
Yoshi
CSE 332: C++ exceptions Overview of C++ Exceptions Normal program control flow is halted –At the point where an exception is thrown The program call stack.
Monday, Mar 24, 2003Kate Gregory with material from Deitel and Deitel Week 11 Exceptions.
Copyright © 2012 Pearson Education, Inc. Chapter 8 Exception Handling.
How to be a C# ninja in 10 easy steps. Benjamin Day.
API Design CPSC 315 – Programming Studio Fall 2008 Follows Kernighan and Pike, The Practice of Programming and Joshua Bloch’s Library-Centric Software.
Nov 10, Fall 2006IAT 8001 Debugging. Nov 10, Fall 2006IAT 8002 How do I know my program is broken?  Compiler Errors –easy to fix!  Runtime Exceptions.
11-Jun-15 Exceptions. 2 Errors and Exceptions An error is a bug in your program dividing by zero going outside the bounds of an array trying to use a.
Exceptions Used to signal errors or unexpected situations to calling code Should not be used for problems that can be dealt with reasonably within local.
16-Jun-15 Exceptions. Errors and Exceptions An error is a bug in your program dividing by zero going outside the bounds of an array trying to use a null.
Exceptions in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Exceptions. Errors and Exceptions An error is a bug in your program –dividing by zero –going outside the bounds of an array –trying to use a null reference.
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++
University of Virginia CSharp (© John Knight 2005) 1 What’s New In C#
Advanced Java Course Exception Handling. Throwables Class Throwable has two subclasses: –Error So bad that you never even think about trying to catch.
To define a class in Visual Basic.NET, you can follow this general procedure: 1. Add a class to the project. 2. Provide an appropriate file name for.
Unit Testing & Defensive Programming. F-22 Raptor Fighter.
A Moderately Directed Rant.  It’s very likely that you’ve been writing totally incorrect code without realizing it  Once you do realize it, it’s usually.
Overview of Previous Lesson(s) Over View  OOP  A class is a data type that you define to suit customized application requirements.  A class can be.
1 Exceptions and error handling. 2 Java exception mechanism when an error or exceptional condition occurs, you throw an exception which is caught by an.
COMPUTER PROGRAMMING 2 Exceptions. What are Exceptions? Unexpected events that happen when the code is executing (during runtime). Exceptions are types.
Exceptions Programming in C# Exceptions CSE 494R (proposed course for 459 Programming in C#) Prof. Roger Crawfis.
File I/O Applied Component-Based Software Engineering File I/O CSE 668 / ECE 668 Prof. Roger Crawfis.
Managed C++. Objectives Overview to Visual C++.NET Concepts and architecture Developing with Managed Extensions for C++ Use cases Managed C++, Visual.
Errors And How to Handle Them. GIGO There is a saying in computer science: “Garbage in, garbage out.” Is this true, or is it just an excuse for bad programming?
Exceptions Syntax, semantics, and pragmatics Exceptions1.
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.
Exceptions Handling Exceptionally Sticky Problems.
How to Design Error Steady Code Ivaylo Bratoev Telerik Corporation
Software Engineering in Robotics Interfacing to external functions Henrik I. Christensen –
DEV300: Advanced C# Eric Gunnerson Program Manager Visual C# Microsoft Corporation.
Effective.NET Framework based Development: Exception Handing and Memory Management Effective.NET Framework based Development: Exception Handing and Memory.
Introduction to Exception Handling and Defensive Programming.
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)
C# Classes and Inheritance CNS 3260 C#.NET Software Development.
Lecture 3 Classes, Structs, Enums Passing by reference and value Arrays.
Fall 2002CS 150: Intro. to Computing1 Streams and File I/O (That is, Input/Output) OR How you read data from files and write data to files.
Java Basics Opening Discussion zWhat did we talk about last class? zWhat are the basic constructs in the programming languages you are familiar.
Digging into the GAT API Comparing C, C++ and Python API‘s Hartmut Kaiser
PerlNET: The Camel Talks.NET Jan Dubois The Perl Conference 6 San Diego, July 26 th 2002.
Object Oriented Software Development 4. C# data types, objects and references.
ICS3U_FileIO.ppt File Input/Output (I/O)‏ ICS3U_FileIO.ppt File I/O Declare a file object File myFile = new File("billy.txt"); a file object whose name.
CSC 298 Streams and files.
Introduction to C# Anders Hejlsberg Distinguished Engineer Developer Division Microsoft Corporation.
(c) University of Washington10-1 CSC 143 Java Errors and Exceptions Reading: Ch. 15.
Announcements Assignment 2 Out Today Quiz today - so I need to shut up at 4:25 1.
CHAPTER 18 C – C++ Section 1: Exceptions. Error Handling with Exceptions Forces you to defend yourself Separates error handling code from the source.
Introduction to Exceptions in Java CS201, SW Development Methods.
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.
Garbage Collection It Is A Way To Destroy The Unused Objects. To do so, we were using free() function in C language and delete() in C++. But, in java it.
Java and C# - Some Commonalities Compile into machine-independent, language- independent code which runs in a managed execution environment Garbage Collection.
.NET Memory Primer Martin Kulov. "Out of CPU, memory and disk, memory is typically the most important for overall system performance." Mark Russinovich.
Jim Fawcett CSE681 – SW Modeling & Analysis Fall 2014
Module 9: Memory and Resource Management
Static data members Constructors and Destructors
Defensive Programming
Creating and Modifying Text part 2
Exceptions 10-Nov-18.
EE422C Software Implementation II
Finalization 17: Finalization
Exception Handling Imran Rashid CTO at ManiWeber Technologies.
Exceptions 19-Feb-19.
Error Handling.
Exceptions 25-Apr-19.
Exceptions 22-Apr-19.
Exceptions 10-May-19.
Exceptions 5-Jul-19.
Jim Fawcett CSE681 – SW Modeling & Analysis Fall 2018
Presentation transcript:

Advanced C# Eric Gunnerson Program Manager Visual C#.NET Microsoft Corporation

Advanced C# Topics Visual Studio “Everett” Features Visual Studio “Everett” Features Designing a New Type Designing a New Type Object Destruction Object Destruction Exception Handling Exception Handling Unsafe Code Unsafe Code

Visual Studio “Everett” Features Visual Studio “Everett” Features Designing a New Type Designing a New Type Object Destruction Object Destruction Exception Handling Exception Handling Unsafe Code Unsafe Code Advanced C# Topics

Everett Demo

Designing a New Type C# has both reference and value types C# has both reference and value types Which is the right one to use? Which is the right one to use?

What are they? Reference types: Reference types: Heap allocated Heap allocated Tracked by the GC Tracked by the GC Support inheritance, polymorphism, etc. Support inheritance, polymorphism, etc. Value types: Value types: Stack or inline allocated Stack or inline allocated Not tracked by the GC Not tracked by the GC No inheritance, limited polymorphism No inheritance, limited polymorphism

Other Languages Smalltalk only supports reference types Smalltalk only supports reference types Simple, consistent model Simple, consistent model Disadvantages Disadvantages “int j = 5;” does a heap allocation “int j = 5;” does a heap allocation 100 ints in an array is 100 allocations 100 ints in an array is 100 allocations Doesn’t interop well with existing primitive types Doesn’t interop well with existing primitive types

Value Types Advantages: Advantages: Allocation is very fast Allocation is very fast Arrays involve a single allocation Arrays involve a single allocation Reduced memory pressure Reduced memory pressure Less work for the GC Less work for the GC Disadvantages: Disadvantages: No inheritance No inheritance Only polymorphic when boxed Only polymorphic when boxed Boxing involves overhead Boxing involves overhead

Reference Types The basic type in.net The basic type in.net Advantages: Advantages: All object-oriented goodies All object-oriented goodies polymorphism, etc. polymorphism, etc. Good performance Good performance Disadvantages: Disadvantages: Always requires heap allocation Always requires heap allocation

Guidelines Use value types for: Use value types for: Building a new data type (ie Complex) Building a new data type (ie Complex) Lots of small objects Lots of small objects Only really useful if they’re in an array Only really useful if they’re in an array If not, boxing often means this isn’t worth it If not, boxing often means this isn’t worth it Size of type Size of type Framework guidelines say <= 16 bytes Framework guidelines say <= 16 bytes Depends on usage of the type Depends on usage of the type Benchmark to validate for your app Benchmark to validate for your app If you hit limitations, you’re using it wrong If you hit limitations, you’re using it wrong

Visual Studio “Everett” Features Visual Studio “Everett” Features Designing a New Type Designing a New Type Object Destruction Object Destruction Exception Handling Exception Handling Ref and foreach Ref and foreach Unsafe Code Unsafe Code Advanced C# Topics

Object Destruction Goal: Be able to control exactly when objects are destroyed Goal: Be able to control exactly when objects are destroyed You want it You want it You can’t have it You can’t have it A very complicated discussion A very complicated discussion See See Look for article on Resource management Look for article on Resource management

Object Destruction Garbage collection means you aren’t in control Garbage collection means you aren’t in control GC chooses: GC chooses: When objects are destroyed When objects are destroyed Order of destruction Order of destruction Garbage collector can’t clean up unmanaged objects Garbage collector can’t clean up unmanaged objects

How Bad is It? Mostly an issue for wrapper objects Mostly an issue for wrapper objects Database handles Database handles Files Files GDI objects (fonts, pens, etc.) GDI objects (fonts, pens, etc.) Any object the GC doesn’t track Any object the GC doesn’t track All objects get cleaned up All objects get cleaned up Some may take a bit longer Some may take a bit longer

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

Scenario 1 User Calls Dispose() Unmanaged Resource Font object 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 Wrap unmanaged resources You’ll need a destructor too You’ll need a destructor too or or Need to be able to clean up early Need to be able to clean up early

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); }}

Visual Studio “Everett” Features Visual Studio “Everett” Features Designing a New Type Designing a New Type Object Destruction Object Destruction Exception Handling Exception Handling Unsafe Code Unsafe Code Advanced C# Topics

Exception Handling Provides tremendous benefits Provides tremendous benefits Requires a different way of thinking Requires a different way of thinking

The old way RETVAL Process(int a, int x, int y, int z) { RETVAL retval; if ((retval = function(x, y, z)) != OK) return retval; if ((retval = function2(a, y)) != OK) return retval; }

Option 1 void Process(int a, int x, int y, int z) { try try { function(x, y, z); } catch (Exception e) { throw e; } try try { function2(a, y); } catch (Exception e) { throw e; }}

Option 2 void Process(int a, int x, int y, int z) { try try { function(x, y, z); function2(a, y); } catch (Exception e) { throw e; }}

Option 3 void Process(int a, int x, int y, int z) { function(x, y, z); function2(a, y); }

Exception Handling You get correct behavior by default You get correct behavior by default Only catch an exception when you can do something useful for the user Only catch an exception when you can do something useful for the user You can write lots of unnecessary code, but at least your code will be less robust You can write lots of unnecessary code, but at least your code will be less robust

When to catch Something specific happens, and we can help Something specific happens, and we can help try{ StreamReader s = File.OpenText(filename); StreamReader s = File.OpenText(filename);} catch (Exception e) { Console.WriteLine(“Invalid filename: {0}”, filename); Console.WriteLine(“Invalid filename: {0}”, filename);}try{ StreamReader s = File.OpenText(filename); StreamReader s = File.OpenText(filename);} catch (FileNotFoundException e) { Console.WriteLine(e); Console.WriteLine(e);}

try{ ExecuteBigProcess(); ExecuteBigProcess();} catch (Exception e) { log.WriteLine(e.ToString()); log.WriteLine(e.ToString()); throw; throw;}try{ ExecuteBigProcess(); ExecuteBigProcess();} catch (Exception e) { throw new MyException(“Error executing BigProcess”, e); throw new MyException(“Error executing BigProcess”, e);} When to catch We need to log or wrap an exception We need to log or wrap an exception

When to catch We’d die otherwise We’d die otherwise public static void Main() { while (true) while (true) { try try { MainLoop(); MainLoop(); } catch (Exception e) catch (Exception e) { Console.WriteLine(“Exception caught, trying to continue”); Console.WriteLine(“Exception caught, trying to continue”); Console.WriteLine(e); Console.WriteLine(e); } }}

Finally statement If an exception is thrown and If an exception is thrown and There’s something to clean up There’s something to clean up Close a file Close a file Release a DB handle Release a DB handle Using statement makes this easier Using statement makes this easier Works on anything that implements IDisposable Works on anything that implements IDisposable

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. 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); } }}

Exceptions vs Return Codes Exceptions are meant for exceptional cases Exceptions are meant for exceptional cases Invalid parameters Invalid parameters Can’t perform operation Can’t perform operation Should not occur during normal program operation Should not occur during normal program operation User interaction is a grey area User interaction is a grey area

Using Return Values Okay if your caller always will have to check and recover from something Okay if your caller always will have to check and recover from something Make sure you don’t force them to write: Make sure you don’t force them to write: Shouldn’t be possible to do the wrong thing Shouldn’t be possible to do the wrong thing File.Open() returns null on file not found File.Open() returns null on file not found You can’t ignore this You can’t ignore this bool success = TryOperation(param1, param2); if (!success) return success; return success;

Summary Understand how the model works Understand how the model works Don’t work too hard Don’t work too hard If you can’t do something useful, don’t catch If you can’t do something useful, don’t catch

Visual Studio “Everett” Features Visual Studio “Everett” Features Designing a New Type Designing a New Type Object Destruction Object Destruction Exception Handling Exception Handling Unsafe Code Unsafe Code Advanced C# Topics

Unsafe Code When pointers are a necessity When pointers are a necessity Advanced COM and P/Invoke interop Advanced COM and P/Invoke interop Existing binary structures Existing binary structures Performance extremes 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 See information page for my columns Sign up for C# Community Newsletter Sign up for C# Community Newsletter C# newsgroup C# newsgroup microsoft.public.dotnet.languages.csharp microsoft.public.dotnet.languages.csharp Me: Me:

Thank You Questions? Questions?