Intro to .NET and C# Good study questions:http://www.indiabix.com/csharp-programming/questions-andanswers/ .NET Framework VB.NET C++.NET C# J# … Common Language Specification ASP.NET Windows Forms ADO.NET and XML Base Class Library Common Language Runtime (CLR) MSMQ COM+ IIS OS WMI .NET Framework VB.NET C++.NET C# J# … Common Language Specification ASP.NET Windows Forms ADO.NET and XML Windows platforms Base Class Library originally, others (such as Mono) later Common Language Runtime (CLR) MSMQ COM+ IIS OS WMI .NET Framework VB.NET C++.NET C# J# … Common Language Specification ASP.NET Windows Forms ADO.NET Access to OS services and XML Base Class Library Common Language Runtime (CLR) MSMQ COM+ IIS OS WMI .NET Framework VB.NET C#Base Class J# Library … Support C++.NET Thread Support COM Marshaler Type Checker Exception Manager Common Language Specification Debug Engine ASP.NET Security Engine Windows Forms Managed execution environment IL to Native Code ADO.NET and XML Compilers Manager Class Loader Base Class Library Common Language Runtime (CLR) MSMQ COM+ IIS OS WMI Garbage Collector .NET Framework VB.NET C++.NET C# J# … Common Language Specification ASP.NET Windows Forms ADO.NET and XML Base Class Library Common Language Runtime (CLR) Built-in .NET APIs; each MSMQ COM+ IIS OS block has a specific WMI purpose .NET Framework System.Web Services Description Discovery Protocols System.WinForms VB.NETUI C++.NET HtmlControls C# Design J# ComponentModel … WebControls Language Specification Common System.Drawing Caching Security Drawing2D Configuration SessionState Imaging ASP.NET System.Data ADO SQL Design SQLTypes Printing Windows Forms ADO.NET and XML Text System.Xml XSLT Serialization Base Class Library XPath Common Language Runtime (CLR) System Collections Configuration IO MSMQ Net Diagnostics Reflection Globalization Resources COM+ Security IIS ServiceProcess Text OS Threading Runtime WMI InteropServices Remoting Serialization .NET Framework VB.NET C++.NET C# J# … Common Language Specification ASP.NET Windows Forms Multi-language support ADO.NET and XML Base Class Library Common Language Runtime (CLR) MSMQ COM+ IIS OS WMI .NET Framework VB.NET APL Ada Asml Beta C# C++ Cobol Delphi ECMAScript Eiffel F# (CAML) C++.NET C# J# … Common Specification Pascal Language Fortran Perl Haskell Pizza Lua ASP.NET Windows Forms P# (Prolog) ILASM RPG lcc ADO.NET and Ruby J# XML Scheme Mercury Library S#Base Class Mixal (Smalltalk) ML (SML) Common Language Runtime (CLR) Visual Basic Mondrian Zonnon Oberon MSMQ Forth COM+ IIS WMI OS Multi-language, multi-platform .NET assemblies VB .NET Application .NET intermediate code C# Application Source code is compiled to intermediate language code (IL = CIL = MSIL) x86, etc. JIT compiler JIT-compiler compiles IL code to machine code Multi-language, multi-platform .NET assemblies VB .NET Application .NET intermediate code C# Application Source code is compiled to intermediate language code (IL = CIL = MSIL) x86, etc. JIT compiler JIT-compiler compiles IL code to machine code Multi-platform Increased Functionality Xbox 360 Pocket PC Phone Tablet PC Smart Personal Objects Smartphone .NET Compact Framework Notebook PC .NET Framework Servers Think about it… • Advantages / disadvantages of 2-step compilation and intermediate language? Advantages Disadvantages Portability Performance (at least in the first run) Multi-language support Intellectual property of the code (can be disassembled / reverse engineered) Only one CLR per platform Dependency on the .NET Framework Differences between Java and C# Demo VS • • • • • • http://msdn.microsoft.com/en-us/vstudio/gg132842 See breakpoints and code snippets. How to VS http://msdn.microsoft.com/en-us/vstudio/ff459609 How to C# http://msdn.microsoft.com/enus/vstudio/bb798022.aspx • VS code samples: • http://msdn.microsoft.com/en-us/vstudio/dd238515 • 16 17 18 19 20 21 22 23 Practice • Import the System.Diagnostics namespace to use the Debug class. • Comment the using directive. – Tip: CTRL K C to comment – Does the code compile? No! • Uncomment the using directive – CTRL K U • Delete the System assembly reference. – Does the code compile? No! Final notes on namespaces • Namespaces can also be nested namespace BugTracker { namespace GUI { public class FrmAddBug () { ... } } } • Or qualified namespace BugTracker.GUI { ... } using BugTracker.GUI; using BugTracker; using GUI; Visual Studio Symbols Icon Description Icon Description Namespace Method or Function Class Operator Interface Property Structure Field or Variable Union Event Enum Constant TypeDef Enum Item Module Map Item Intrinsic External Declaration Delegate Macro Exception Template Map Unknown or Error Global Type Forwarding Extension Method More C# C# program structure • Execution starts at Main( ) • The using keyword allows reusing types from the .NET Framework or 3rd party • Well-known C syntax: – Statements, semicolon, braces, ... using System; class WonderfulWorld { static void Main() { Console.WriteLine(“Hello, world!”); } } Practice – Bonus on Assignment 1 • Exploring basic input/output operations with System.Console – Access to standard input/output/error streams • Write/WriteLine • Read/ReadLine • ReadKey for advanced input – Change console colors and title – Random beeps! Practice • Formatting with Write/WriteLine Console.WriteLine("The sum of {0} and {1} is {2}", 5, 10, 5+10); Console.WriteLine("The book costs {0:C}", 23.49); //$23.49 Console.WriteLine("The value is {0:N}", 8888888.8); //8,888,888.80 Console.WriteLine("==>{0,3}<==", 9); // “==> Console.WriteLine("==>{0,-3}<==", 9); // “==>9 9<==” <==” Console.WriteLine("{0:(###) ###-####}", 8005551212); // (800) 555-1212 Console.WriteLine("{0:MM/dd/yyyy}", DateTime.Now); // 11/10/2008 Console.WriteLine("{0:MMM} {0:ddd}", DateTime.Now); // Oct Thu Console.WriteLine("{0:MMMM} {0:dddd}", DateTime.Now); // October Thursday Lot more at: http://blog.stevex.net/index.php/string-formatting-incsharp/ Note on string formatting • Formatting and placeholders { } are not specific to Console.WriteLine and Console Applications • You can also use the string.Format method to format a string string s = string.Format("The sum of {0} and {1} is {2}", 5, 10, 5+10); How to format C# code • • • • • Indentation improves readability C# is sensible to lower/upper case Blank spaces are ignored Multiple line comments: /* ... */ Preferred: one line comments: // – Remember: • Comment: CTRL + K + C • Uncomment: CTRL + K + U Built-in types C# is strongly typed. • Each variable belongs to a given type .NET Framework built-in types: • Integral: byte, sbyte, short, ushort, int, uint, long, ulong • Floating-point: float, double • Numerical precision: decimal • Boolean: bool • Character: char, string Note: string vs. String • Both are the same • string is just an alias to the String class. • Use string, not String (code convention) Declaring and initializing variables • Declaring uint age; • Declaring + initializing uint age = 28; • Generally, initialization should happen prior to usage Passing parameters by reference • By value is the default passing technique • Use the ref keyword in parameter (and method call) to pass by reference public void InitializeHitCount(ref int hitCount) { hitCount = 1; } int hitCount = 0; bug.HitCount = hitCount; // hitCount = 1, no changes to bug.HitCount InitializeHitCount(ref hitCount); Passing by “out” • Use out parameters to transfer data out of the method, but not in public void InitializeHitCount(out int hitCount) {...} InitializeHitCount(out hitCount); • The out variable doesn’t need to be initialized when method is called, but… – Parameter should be set before method leaves – Method cannot read parameter before initialization Literal values can have suffixes • Literal values can have suffixes Type Suffix Example uint U or u 100U decimal rate = 1.2345M; long L or l 100L ulong UL or ul 100UL long bigNum = 98768L; float F or f 123.45F decimal M or m 123.45M float miles = 7.25F; Practice • Does it compile? byte b = 45; int i = 45; byte b = i; • Conclusion: integer literals are implicitly converted to byte, sbyte, short and ushort – … assuming the assigned value fits byte b = 300; Variables: rules and recommendations • Name cannot start with digits – Underscore is allowed, but not recommended • Avoid int MAX_NUMBER; – All uppercase letters – Abbreviations string currMsg; • Use camelCasing for variables int numberOfOrders; String literals • Regular string literal: double quotes string s = "Hello, World"; // Hello, World • Escape char: quote string s = "\"Hello\""; // "Hello" • Escape char: new line string s = "Hello\nWorld"; // creates a new line • Verbatim strings – No escape chars – Useful to define a string in multiple lines string s = @"Hello\nWorld"; // Hello\nWorld More on escape chars Escape sequence Description \’ single quote \” double quote \\ back slash \a alert \b backspace \t (horizontal) tab \v vertical tab \n new line feed (LF) \r carriage return (CR) \f form feed \0 unicode character 0 (zero) "" double quote in verbatim strings Constants • Keyword const next to the type name • Value should be assigned when declaring the constant • PascalCase notation by convention const int EarthRadius = 6378; // km const long DistanceToSun = 149600000; // km const double OrbitalSpeed = 29.79D; // km/sec Type conversion • Implicit – Done by the compiler – Guaranteed: no information will be lost int x = 123456; // int is a 4 byte integer long y = x; // implicit conversion to long • Explicit – Programmer is aware of possible information loss int x = 65537; short z = (short) x; // explicit conversion to short: z == 1 Type conversion • Other interesting options: – System.Convert class methods int x = Convert.ToInt32(“3”); – <built-in type name>.Parse() int x = int.Parse(“3”); double d = double.Parse(“1.0”); – <built-in type name>.TryParse() Operators • Operators are symbols used to manipulate expressions • Can be overloaded (ex.: +) Common Operators Example Increment/Decrement ++ -- Arithmetic * / % + - Relational < > <= >= Equality == != Conditional && || ?: Assignment = *= /= %= += -= <<= >>= &= ^= |= For more information see: http://msdn.microsoft.com/en-us/library/ty67wk28 Operator precedence • Expressions are evaluated according to operator precedence 10 + 20 / 5 // = 14 • Parenthesis can be used to impose a specific order (10 + 20) / 5 10 + (20 / 5) // = 6 // = 14 • Operators can associate from left or right 10 / 5 * 20; x = y = z = 3; // left // right if statement • No big news here – if, if / else, if / else if – Good programming practice: always include the braces! if (sales > 10000) { bonus += .05 * sales; } else if (sales > 5000) { bonus = .01 * sales; } else { bonus = 0; if (previousBonus == 0) { //schedule meeting; } } Formatting tip • Braces on same or new line? Up to you! – Tools Options Text Editor C# Formatting New Lines • CTRL + K + D to apply formatting to current file Formatting tip • BTW, other 3 important things – CTRL+Enter to place cursor inside brackets – Copy and paste with no selection: applies to the entire line! – Line numbers switch statement • The same old switch… – … but with some news (in the next slide) byte bugSeverity; switch (bugSource) { case "MSRC": bugSeverity = 3; break; case "Hotfix": bugSeverity = 2; break; case "HappyHour": bugSeverity = 0; break; default: bugSeverity = 1; break; } Practice • Does it compile? – Allowed switch expressions: • char, integral types, string, enumerations – Case values should be constant or literal – No fall through allowed – But multiple labels are permitted float test = 1.0f; switch (test) { // ... } float test = 1.0f; switch (foo) { case test: //... } case "MSRC": bugSeverity = 3; case "Hotfix": bugSeverity = 2; break; case "MSRC": case "Hotfix": bugSeverity = 2; break; for loop • Again, no big news here for (initialization; check; iteration variable) { instructions; } Example initialize only or declare + initialize for (int i = 0; i < 10; i++) { Console.WriteLine("i = " + i); } multiple initializations, multiple iteration variables for (int i=5, j=100; i<j; j-=5, i+=5 ) { Console.WriteLine("i + j = " + (i + j)); } Productivity tip: Code Snippets • Type the snippet name • Press TAB to expand it renaming is propagated (SHIFT) TAB cycles through snippet elements ENTER places the cursor in the snippet ending position Productivity tip: Code Snippets • Finding snippets to use: or CTRL K + X Productivity tip: Code Snippets • Download powerful C# snippets! – http://msdn.microsoft.com/en-us/vstudio/aa718338.aspx – http://en.csharp-online.net/CSharp_Code_Snippets – Manage snippets from menu Tools Code Snippet Manager • Create your own snippets – http://msdn.microsoft.com/en-us/library/ms165393(VS.80).aspx – http://blogs.msdn.com/vseditor/archive/2004/07/14/183189.aspx foreach loop • Cleaner iteration syntax iteration without foreach iteration with foreach Liked foreach? Check Linq! while loop • The same while from C/C++/Java… bool foundEOF = false; // ... while (!foundEOF) { ProcessNewLine(); } do-while loop • Again, no news here – Useful when something has to be executed at least once do { ReportError(); } while (errorWasReceived == false); Brace Matching • Find the matching brace – CTRL + ] next to a brace moves the cursor to the matching brace – SHIFT + CTRL + ] can be used to select what’s in between Breakpoints in VS Power Tools / RockScroll .NET Debugging 101 • F9 to add a breakpoint • F5 to start debugging • Ways to break Restart (CTRL + SHIFT + F5) Stop (SHIFT + F5) – Breakpoint – CTRL + ALT + BREAK – Debugger.Break() Go (F5) Step into (F11) Step over (F10) Step out (SHIFT + F11) .NET Debugging 101 • Mouse hover to view and change values • Locals window shows local variables – Also allow value editing – Red means value change Other debugging windows • Watch windows – Allow you to enter variables and expressions to watch – Supports Intellisense Other debugging windows • Stack window • Output window – Debug.WriteLine and similar calls output here Other debugging commands Execution flows until the line is reached Can be started even without debugging! (CTRL + F10) Change execution flow to the current line You can continue debugging from the Disassembly window Conditional breakpoints/tracepoints Break only when something is true or has changed Break only when breakpoint is hit a given number of times Break based on machine/thread/process information Do something when hit (call a macro, print data, etc.) End for the day Classes and objects in C# • Complies to well-known OO definitions – Classes are factories or “blueprints” • Defines structure and behavior – Objects are instances • Each has a state and an identity Object Class Covered Porch kitchen Dining Room Living Room Bath Office Family Room Defining classes and creating objects • Initially, no news: public class Bug { //---- class fields ------private string title; private int hitCount; private bool isRegression; private Status status; ... } Bug newFoundBug; // not initialized newFoundBug = new Bug(); Initializing class fields • When a class is instantiated, default values are assigned to its fields – Mouse hover during debug session to explore field values Numeric types default to 0 (including char) Boolean type defaults to false Enums default to element of value 0 (generally the first one) Reference types default to null (including string) Initializing class fields • It is possible to declare + initialize fields public class Bug { private int hitCount = 1; ... } Initializing class fields • Constructors allow parameterized field initialization – Variable initialization happens first – this keyword refers to the current instance public class Bug { public Bug(string title, bool isRegression) { this.title = title; this.isRegression = isRegression; Console.WriteLine("Bug created... "); } } UI handling inside execution logic: not a good practice… Constructor: some notes • If you don’t specify any constructor, a default parameterless constructor is created by the compiler – That’s why we could call Bug newFoundBug = new Bug(); • readonly fields can be assigned only when declared or in a constructor public class Bug { private readonly string howFound; ... } Constructor: some notes • Calling a constructor from another public class Bug { public Bug(string title, bool isRegression, int hitCount) { // code to be reused by other constructors } public Bug( string title, bool isRegression) : this(title, isRegression, 1) { } } C# access modifiers • Context: a type (e.g. , class) can be related to others in different ways… class UIControl class Form class LibrarySystem (same assembly) (unrelated) class Button UI.dll OtherAssembly.exe/dll (child + same assembly) class MyControl CustomControls.dll (child) C# access modifiers: public • Public classes/types can be accessed by any other class/type public class UIControl class Form class LibrarySystem (same assembly) (unrelated) class Button UI.dll OtherAssembly.exe/dll (child + same assembly) class MyControl CustomControls.dll (child) C# access modifiers: internal • Internal classes/types can be accessed by other classes/types in the same assembly internal class UIControl class Form class LibrarySystem (same assembly) (unrelated) class Button UI.dll OtherAssembly.exe/dll (child + same assembly) class MyControl CustomControls.dll (child) C# access modifiers: public • Public members of a class can be accessed by the class itself + any other public class UIControl class Form public int x; public void M() { } (same assembly) class LibrarySystem (unrelated) class Button UI.dll OtherAssembly.exe/dll (child + same assembly) class MyControl CustomControls.dll (child) C# access modifiers: private • Private members of a class can be accessed only by the class itself public class UIControl class Form private int x; private void M() { } (same assembly) class LibrarySystem (unrelated) class Button UI.dll OtherAssembly.exe/dll (child + same assembly) class MyControl CustomControls.dll (child) C# access modifiers: internal • Access only from the class itself or others in the same assembly public class UIControl class Form internal int x; internal void M() { } (same assembly) class LibrarySystem (unrelated) class Button UI.dll OtherAssembly.exe/dll (child + same assembly) class MyControl CustomControls.dll (child) C# access modifiers: protected • Access only from the class itself or derived (child) classes public class UIControl class Form protected int x; protected void M() { } (same assembly) class LibrarySystem (unrelated) class Button UI.dll OtherAssembly.exe/dll (child + same assembly) class MyControl CustomControls.dll (child) C# access modifiers: protected internal • Access only from the class itself or derived (child) classes or others in the same assembly public class UIControl class Form protected internal int x; protected internal void M() { } (same assembly) class LibrarySystem (unrelated) class Button UI.dll OtherAssembly.exe/dll (child + same assembly) class MyControl CustomControls.dll (child) Understanding protected internal types in the same assembly of UIControl class class Form classes derived from UIControl class class Button class MyControl access to access to internal protected members members C# access modifiers: summary Modifier Scope public Unlimited access to member/type private Access to member/type only from within this class internal protected protected internal Access to member/type only from within the assembly of this class Access to member/type only from within this class or its derived classes* Access to member/type only from within this class, its derived classes or within the assembly of this class *more on inheritance later Note: how to implement “friend” assemblies in C# http://msdn.microsoft.com/en-us/library/0tke9fxk.aspx Methods • Define class behavior <access modifier> <return type> <Name>(<parameters>) { //statements //optional return } • Parameters are passed by value (copy) – But an object copy still points to the same data of the original object passed as parameter public void Close(Bug bug) { bug.Status = Status.Closed; bug.Comments = “bug closed”; } // this is buggy! public void InitializeBug(Bug bug) { bug = new Bug(); } Bug controlPanelBug = new Bug(); Close(controlPanelBug); // modifies controlPanelBug InitializeBug(controlPanelBug); // no effect! Passing parameters by reference • Use the ref keyword in method declaration and call public void Initialize(ref int hitCount) { hitCount = 1; } int hitCount = bug.HitCount = Initialize(ref Initialize(ref 0; hitCount; hitCount); // hitCount = 1, no changes to bug.HitCount bug.HitCount); //does not compile! • Use out parameters to transfer data out of the method, but not in public void InitializeHitCount(out int hitCount) {...} InitializeHitCount(out hitCount); Method overloading • Methods with the same name, but are differentiated by either one of those items: – Parameters’ types – Parameters’ order – Parameters’ passing technique (ref/out vs. by value) public void ResolveBug(Resolution r) {...} public void ResolveBug(Resolution r, string comments) {...} public void ResolveBug(Resolution r, ref string comments) {...} • Having only different return type or accessibility does not characterize overloading – It doesn’t even compile Static modifier • Makes a type’s member to be shared by all instances class Soldier { Point position; int damage; static Directive directive; } this.position = {2,2} this.damage = 2 enum Directive { Attack, Retreat, Scout, ... } if (this.damage > 10) { Soldier.directive = Directive.Retreat; } this.position = {5,3} this.damage = 2 Soldier.directive = Directive.Attack this.position = {8,1} this.damage = 8 Static members • Shared by all type instances – Fields, properties and methods can be static public class Bug { public static int totalClosed = 0; public void Close() { // ... totalClosed++; } public static void ResetClosedCount() { totalClosed = 0; } } • Cannot be accessed with an instance reference; qualify it with the type name instead controlPanelBug.ResetClosedCount(); //error Bug.ResetClosedCount(); //ok Static constructor • • • • Called only once (when class is loaded) No parameters, no access modifier Can co-exist with instance constructors Equivalent to Java’s static initialization blocks public class Bug { private static int totalClosed; static Bug() { totalClosed = 0; Console.WriteLine("Bug class loaded"); } } Inheritance • Defines an is-a relationship • Derived classes are a specialization of the base classes • Derived classes inherit fields, properties, methods – But not constructors • Multiple inheritance is not supported base class Bug TestBug HotfixBug derived classes Inheritance • Defining derived classes public class Bug { private string title; protected Status status; public void Close() { // ... } } public class HotfixBug : Bug { public void PrepareToHotfixShiproom() { // title is not accessible here // status is accessible here } } HotfixBug newCplBug = new HotfixBug(); newCplBug.PrepareToHotfixShiproom(); newCplBug.Close(); Practice public class Bug {...} public class HotfixBug : Bug { public void PrepareToHotfixShiproom() {...} } • Does it compile? Bug newCplBug = new HotfixBug(); implicit conversion! newCplBug.PrepareToHotfixShiproom(); CPL’s type (Bug) does not contain a definition for PrepareToHotfixShiproom! ((HotfixBug) newCplBug).PrepareToHotfixShiproom(); explicit conversion! Inheritance • Calling a base constructor from a derived class public class Bug { public Bug(string title) { } // ... } public class HotfixBug : Bug { public HotfixBug(string title, string kbArticle) : base(title) { // ... } } • No explicit call to base constructor implies in implicit call to the default (empty) base constructor Practice • Does it compile? public class Bug { public Bug(string title) { } // ... } public class HotFixBug : Bug { public HotFixBug() { // ... } } public class Bug { public Bug(string title) { } public class HotFixBug : Bug { // no constructors } // ... } Abstract classes • General base class – Can contain abstract methods/properties to be specialized by derived classes – Can contain implementation reused by derived classes – Cannot be instantiated public abstract class Employee { public abstract void Work(); public abstract string Name { get; set;} public abstract int Level { get;} public virtual void Triage() { ... } } Abstract classes • Deriving from abstract classes and implementing its abstract members – CTRL + . – Use override keyword Practice • Does it compile? public abstract class Employee { public abstract void Work(); public abstract void WorkMore(); } public class PM : Employee { public override void Work() { // PM work... } } public abstract class Dev : Employee { public override void Work() { // Dev work... } } Visual Studio Symbols Icon Description Icon Description Namespace Method or Function Class Operator Interface Property Structure Field or Variable Union Event Enum Constant TypeDef Enum Item Module Map Item Intrinsic External Declaration Delegate Macro Exception Template Map Unknown or Error Global Type Forwarding Extension Method Interfaces • An interface is a type that defines a contract that other types can comply to Animal Mamma l Dog class Gravity { void PullDown(??? anythingThatFlies) { ... } } Bird Bat Eagle Penguin What type can we have here to indicate instances that comply with this common flying behavior (contract)? Interfaces interface IFlier { void Fly(); int Weight {get;} } class Gravity { void PullDown(IFlier anythingThatFlies) { ... } } Animal Mamma l Dog class Bat : Mammal, IFlier {...} class Eagle : Bird, IFlier {...} class Helicopter : IFlier {...} Bird Bat Eagle Penguin Helicopter IFlier Interfaces • The “contract” is defined by means of methods and properties • No implementation in the interface itself • Interfaces cannot be instantiated public interface IPersistable { void Save(string toLocation); void Load(string fromLocation); bool IsDirty { get; } } Implementing interfaces Implementing interfaces and inheriting classes at the same time public interface IPersistable {...} public abstract class WorkItem {...} public class Bug : WorkItem, IPersistable {...} If we have a class in the list, it should come first. Everything else should be interfaces. is / as operators • is operator – Checks an object type if (workItem is IPersistable) { // ... } • as operator – Fail-safe type conversion IPersistable p = workItem as IPersistable; if (p != null) { p.Save(fileLocation); } .NET built-in interfaces • The .NET Framework contains some built-in interfaces – ICollection, IDictionary, IEnumerable, IEnumerator, IHashCodeProvider, IList, IComparable • Use them to provide broader compatibility and to not reinvent the wheel! Operator Overloading • Operator overloading permits user-defined operator implementations to be specified for operations where one or both of the operands are of a user-defined class or struct type • http://msdn.microsoft.com/enus/library/aa288467(v=VS.71).aspx Operator Overloading Continued • All unary and binary operators have pre-defined implementations, that are automatically available in any expressions. • In addition to this pre-defined implementations, user defined implementations can also be introduced in C#. • The mechanism of giving a special meaning to a standard C# operator with respect to a user defined data type such as classes or structures is known as operator overloading Implementing operator overloading Operator Notation Functional Notation op x operator op(x) x op operator op(x) x op y operator op(x,y) public static Bug operator ++(Bug b) { b.HitCount++; return b; } Bug kernelBug = new Bug(); // kernelBug.Hitcount is 1 kernelBug++; // kernelBug.Hitcount is 2 now Operator overloading • Will this work? if (bug1 > bug2) {...} No! This operator is not defined for Bug class • How to overload operators? – First of all, what can be overloaded? Overloadability (what a word!) source: http://msdn.microsoft.com/en-us/library/8edha89s(VS.71).aspx Error handling in .NET • Coming from C++, we are commonly used to methods returning success/failure bool ThemesTest::TestSetup() {...} HRESULT ThemesTest::ChangeTheme(PCWSTR pszName) • But what are the outputs of the following method? public bool IsBugOpened(long bugNumber) { // ... } Arithmetic Overflow int i = int.MaxValue; int j = i+1; //what happens?? • OverflowException is off by default • Turn it on – Use “checked” block – Or… checked { int i = int.MaxValue; int j = i+1; //System.OverflowException } Arithmetic Overflow … or enable the /checked+ C# compiler option Can be done via VS project properties Visual Studio Exception assistant • In debugging mode, VS helps you to figure out unhandled exceptions Visual Studio Exception assistant Exception: good practices • Debug Exceptions window – Tell which exceptions should break into the debugger – Add the entire CLR Exceptions tree there! Creating your own exceptions • Base rule: derive from System.Exception – Not from ApplicationException: sometimes it is accidentally eaten by the framework • Other rules: let the exception snippet do the job Exception: good practices • Never catch an exception more generic than you should • Don’t swallow exceptions unless you have a good reason ... } catch (Exception ex) {} // continue as if nothing has happened: bad • If you let the application live after an unknown error – It may be in a unstable state – It may be a hole for security and other issues! • Let it die! Array • Data structure containing (or pointing to) a collection of variables array of ints 5 – Unidimensional – Multidimensional – Jagged (array of arrays) 0 8 8 2 . . . . array of Bugs – Elements should be of the same type – Zero-based index • Has specific methods to manipulate its items • Array kinds in .NET: 7 . . null null Bug Title=“CPL bug” Description=… … Bug Title=“BSOD” Description=… … null Declaring and initializing arrays • Unidimensional array declaring syntax int[] myIntArray; • Initialization syntax int[] myIntArray = new int[5]; 0 0 0 0 0 value types are initialized to their default values Bug[] myBugArray = new Bug[3]; . null . . null null Reference types are initialized to null int[] emptyIntArray = new int[0]; Initializing array members • When declaring the array int[] myIntArray = {5,7,0,8,8,2}; Bug[] myBugArray = { new Bug("CPL Bug"), new Bug("BSOD"), new Bug("Mega crash") }; • After declaring int[] myIntArray; myIntArray = new int[6] {5,7,0,8,8,2}; myIntArray = new int[] {5,7,0,8,8,2}; //OK Manipulating array members Bug[] myBugs = new Bug[2]; indexing operation (set) new Bug("CPL myBugs[0] = Bug"); myBugs[1] = new Bug("BSOD"); indexing operation (get) Console.WriteLine(myBugs[1].Title); foreach (Bug bug in myBugs) { bug.Status = Status.Closed; } Practice • Does it print “CPL Bug” or “New Bug”? public void ChangeElement(Bug[] bugs) { bugs[0] = new Bug("New Bug"); } Bug[] myBugs = { new Bug("CPL Bug") }; ChangeElement(myBugs); Console.WriteLine(myBugs[0].Title); • “New Bug”! Arrays are reference types! . myBugs bugs . . . . . Multidimensional arrays • Use commas inside brackets to declare and manipulate members Bug[,] bugMatrix = new Bug[3,3]; bugMatrix[1,1] = new Bug("MiddleBug"); null null . . . . . . . . . Bug null • It gets as complicated as you want int[,,] tridimensionalInts = { { {1,2}, {3,4}, {5,6}, }, { {7,8}, {9,10}, {11,12} } }; Interesting array properties • Rank: number of array dimensions • Length: number of array elements – GetLength(): length in a given dimension . . . null null . . . . . . Bug Rank = 2 Length = 9 GetLength(1) = 3 2 Rank = 1 Length = 6 null 5 7 0 8 8 Jagged arrays • Array of arrays int[][] jaggedInts = new int[3][]; jaggedInts[0] = new int[3]; jaggedInts[1] = new int[2]; jaggedInts . 0 0 0 . 0 0 . null Practice • What is jaggedInts Rank? • And Length? jaggedInts . 0 0 0 . 0 0 . Rank = 1 Length = 3 null System.Collections.ArrayList • No pre-defined size • Easy element manipulation – – – – – .Add() .Insert() .Remove() .RemoveAt() .Clear() • Can be indexed using [] • Can be built from arrays ArrayList bugs = new ArrayList(); bugs.Add(cplBug); bugs.Add(taskbarBug); • Other interesting methods: – – – – – .Contains .Reverse() .Sort() .IndexOf() … • Its interface deals with… objects params keyword • Allow caller to pass as many parameters as desired public void CheckIn( string changeListName, int changeListid, params string[] files) { // ... } CheckIn("Control Panel AV Bugfix", 123, "File1.cpp", "File2.cpp", "File3.cpp"); Console.WriteLine("{0}-{1}-{2}", a, b, c); as many as you Command-line arguments • Main entry point receives command line arguments as a string array Command-line arguments • Setting command-line arguments when debugging Other C# subjects to explore • • • • Delegates Events Generics Threading Extra Slides – not on test Practice: IComparable • Use the IComparable .NET interface to provide comparing capabilities to the Bug class based on bug title public class Bug : IComparable { //... } Events • Every Control in C# is full of events like MouseButtonDown and KeyDown, but what happens when you want an object to fire an event that isn't already built in? • An event is a mechanism via which a class can notify its clients when something happens. For example when you click a button, a button-clickevent notification is sent to the window hosting the button. • http://www.switchonthecode.com/tutorials/cshar p-snippet-tutorial-custom-event-handlers Events cont. • http://www.dotnetperls.com/event