X hits on this document

821 views

0 shares

0 downloads

0 comments

24 / 396

Chapter ‎18   Unsafe code

throw and try statements

static double Divide(double x, double y) { if (y == 0) throw new DivideByZeroException(); return x / y; }

static void Main(string[] args) { try { if (args.Length != 2) { throw new Exception("Two numbers required"); } double x = double.Parse(args[0]); double y = double.Parse(args[1]); Console.WriteLine(Divide(x, y)); } catch (Exception e) { Console.WriteLine(e.Message); } }

checked and unchecked statements

static void Main() { int i = int.MaxValue; checked { Console.WriteLine(i + 1);// Exception } unchecked { Console.WriteLine(i + 1);// Overflow } }

lock statement

class Account { decimal balance;

public void Withdraw(decimal amount) { lock (this) { if (amount > balance) { throw new Exception("Insufficient funds"); } balance -= amount; } } }

using statement

static void Main() { using (TextWriter w = File.CreateText("test.txt")) { w.WriteLine("Line one"); w.WriteLine("Line two"); w.WriteLine("Line three"); } }

1.6 Classes and objects

Classes are the most fundamental of C#’s types. A class is a data structure that combines state (fields) and actions (methods and other function members) in a single unit. A class provides a definition for dynamically created instances of the class, also known as objects. Classes support inheritance and polymorphism, mechanisms whereby derived classes can extend and specialize base classes.

Copyright Microsoft Corporation 1999-2003. All Rights Reserved.11

Document info
Document views821
Page views821
Page last viewedSun Dec 04 09:06:12 UTC 2016
Pages396
Paragraphs9401
Words133190

Comments