Presentation is loading. Please wait.

Presentation is loading. Please wait.

Object Oriented Programming in C# Keith Pijanowski.Net Developer Evangelist Microsoft Corporation.

Similar presentations


Presentation on theme: "Object Oriented Programming in C# Keith Pijanowski.Net Developer Evangelist Microsoft Corporation."— Presentation transcript:

1 Object Oriented Programming in C# Keith Pijanowski.Net Developer Evangelist KeithPij@microsoft.com Microsoft Corporation

2 Agenda Overview Overview Program Structure Program Structure Value Types and Reference Types Value Types and Reference Types Base Classes, Derived Classes, Abstract Classes, & Interfaces Base Classes, Derived Classes, Abstract Classes, & Interfaces Delegates and Events Delegates and Events Operator Overloading Operator Overloading Versioning Versioning

3 The.NET Framework Overview Base Class Library Common Language Specification Common Language Runtime ADO.NET: Data and XML VBC++C# Visual Studio.NET ASP.NET: Web Services And Web Forms JScript… Windows forms

4 Design Goals of C# A Component Oriented Language C# is the first “Component Oriented” language in the C/C++ family C# is the first “Component Oriented” language in the C/C++ family Component concepts are first class Component concepts are first class  Properties, methods, events  Design-time and run-time attributes  Integrated documentation using XML Enables one-stop programming Enables one-stop programming  No header files, IDL, etc.  Can be embedded in ASP pages

5 Design Goals of C# Everything Really Is an Object Traditional views Traditional views  C++, Java ™ : Primitive types are “magic” and do not interoperate with objects  Smalltalk, Lisp: Primitive types are objects, but at great performance cost C# unifies with no performance cost C# unifies with no performance cost  Deep simplicity throughout system Improved extensibility and reusability Improved extensibility and reusability  New primitive types: Decimal, SQL…  Collections, etc., work for all types

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

7 Design Goals of C# Preserving Your Investment C++ Heritage C++ Heritage  Namespaces, pointers (in unsafe code), unsigned types, etc.  No unnecessary sacrifices Interoperability Interoperability  What software is increasingly about  C# talks to XML, SOAP, COM, DLLs, and any.NET Framework language Millions of lines of C# code in.NET Millions of lines of C# code in.NET  Short learning curve  Increased productivity

8 Agenda Overview Overview Program Structure Program Structure Value Types and Reference Types Value Types and Reference Types Base Classes, Derived Classes, Abstract Classes, & Interfaces Base Classes, Derived Classes, Abstract Classes, & Interfaces Delegates and Events Delegates and Events Operator Overloading Operator Overloading Versioning Versioning

9 Program Structure Levels Namespaces Namespaces  Contain types and other namespaces Type declarations Type declarations  Classes, structs, interfaces, enums, and delegates Members Members  Constants, fields, methods, properties, indexers, events, operators, constructors, destructors Organization Organization  No header files, code written “in-line”  No declaration order dependence

10 Program Structure Namespaces Declare a scope Declare a scope Organize Code Organize Code Globally Unique Types Globally Unique Types Using {Some Namespace} Using {Some Namespace}  Imports the type members of a namespace.

11 Program Structure Example using System; namespace System.Collections { public class Stack public class Stack { Entry top; Entry top; public void Push(object data) public void Push(object data) { top = new Entry(top, data); top = new Entry(top, data); } public object Pop() public object Pop() { if (top == null) throw new InvalidOperationException(); if (top == null) throw new InvalidOperationException(); object result = top.data; object result = top.data; top = top.next; top = top.next; return result; return result; } }}

12 Agenda Overview Overview Program Structure Program Structure Value Types and Reference Types Value Types and Reference Types Base Classes, Derived Classes, Abstract Classes, & Interfaces Base Classes, Derived Classes, Abstract Classes, & Interfaces Delegates and Events Delegates and Events Operator Overloading Operator Overloading Versioning Versioning

13 Value and Reference Types Definition Value types Value types  Directly contain data  Cannot be null Reference types Reference types  Contain references to objects  May be null int i = 123; string s = "Hello world"; 123 i s "Hello world"

14 Value and Reference Types Example Value types Value types  Primitives int i;  Enumsenum State { Off, On }  Structsstruct Point { int x, y; } Reference types Reference types  Classesclass Foo: Bar, IFoo {...}  Interfaces interface IFoo: IBar {...}  Arraysstring[] a = new string[10];  Delegatesdelegate void Empty();

15 Value and Reference Types Predefined Types C# predefined types C# predefined types  Referenceobject, string  Signedsbyte, short, int, long  Unsigned byte, ushort, uint, ulong  Characterchar  Floating-pointfloat, double, decimal  Logicalbool Predefined types are simply aliases for system-provided types Predefined types are simply aliases for system-provided types  For example, int = System.Int32

16 Value and Reference Types Classes Single inheritance Single inheritance Multiple interface implementation Multiple interface implementation Class members Class members  Constants, fields, methods, properties, indexers, events, operators, constructors, destructors  Static and instance members  Nested types Member access Member access  Public, protected, internal, private

17 Value and Reference Types Structs Like classes, except Like classes, except  Stored in-line, not heap allocated  Assignment copies data, not reference  No inheritance Ideal for light weight objects Ideal for light weight objects  Complex, point, rectangle, color  int, float, double, etc., are all structs Benefits Benefits  No heap allocation, less GC pressure  More efficient use of memory

18 Value and Reference Types Classes and Structs class CPoint { int x, y;... } class CPoint { int x, y;... } struct SPoint { int x, y;... } CPoint cp = new CPoint(10, 20); SPoint sp = new SPoint(10, 20); 10 20 sp cp 10 20 CPoint

19 Value and Reference Types Unified Type System Everything is an object Everything is an object  All types ultimately inherit from object  Any piece of data can be stored, transported, and manipulated with no extra work Stream MemoryStreamFileStream Hashtabledoubleint object

20 Value and Reference Types Boxing and Unboxing Boxing Boxing  Allocates box, copies value into it Unboxing Unboxing  Checks type of box, copies value out int i = 123; object o = i; int j = (int)o; 123 i o 123 System.Int32 123 j

21 Language Features Unified Type System Benefits Benefits  Eliminates “wrapper classes”  Collection classes work with all types  Replaces OLE Automation's Variant Lots of examples in.NET framework Lots of examples in.NET framework string s = string.Format( "Your total was {0} on {1}", total, date); "Your total was {0} on {1}", total, date); Hashtable t = new Hashtable(); t.Add(0, "zero"); t.Add(1, "one"); t.Add(2, "two");

22 Demonstration 1 Program Structure Value Types Reference Types Demonstration 1 Program Structure Value Types Reference Types

23 Agenda Overview Overview Program Structure Program Structure Value Types and Reference Types Value Types and Reference Types Base Classes, Derived Classes, Abstract Classes, & Interfaces Base Classes, Derived Classes, Abstract Classes, & Interfaces Delegates and Events Delegates and Events Operator Overloading Operator Overloading Versioning Versioning

24 Base Classes Definition Synonymous with Superclass Synonymous with Superclass Derived Classes are created from Base classes. Derived Classes are created from Base classes. Base classes may also be derived classes Base classes may also be derived classes Keywords Keywords  private  public  internal  protected  virtual

25 Derived Classes Definition Synonymous with Subclass Synonymous with Subclass Single Inheritance Single Inheritance Extend base class functionality Extend base class functionality Replace base class functionality Replace base class functionality Augment existing functionality Augment existing functionality Keywords Keywords  private  public  internal  protected  override  base  sealed

26 Base & Derived Classes Syntax public class Mammal { public void Breathe() {…} public void Breathe() {…} public virtual void Walk() {…} public virtual void Walk() {…} public virtual void Eat() {…} public virtual void Eat() {…}} public class Dog: Mammal { override public void Walk() {…} override public void Walk() {…} public string Bark() {…} public string Bark() {…}}

27 Abstract Classes Definition A base class that can not be created A base class that can not be created Must be overridden Must be overridden Keywords Keywords  private  public  internal  protected  virtual  abstract (class and member level)

28 Abstract & Derived Classes Example public abstract class Mammal { public void Breathe() {…} public void Breathe() {…} public virtual void Walk() {…} public virtual void Walk() {…} public virtual void Eat() {…} public virtual void Eat() {…} public abstract bool Swim() public abstract bool Swim()} public class Dog: Mammal { override public void Walk() {…} override public void Walk() {…} public string Bark() {…} public string Bark() {…} override public bool Swim() {return false;} override public bool Swim() {return false;}}

29 Interfaces Definition Multiple inheritance Multiple inheritance Can contain methods, properties, indexers and events Can contain methods, properties, indexers and events Provides polymorphic behavior Provides polymorphic behavior Does not represent an ‘is-a’ relationship Does not represent an ‘is-a’ relationship Represents a contract between classes Represents a contract between classes

30 Interfaces Syntax interface IDataBound { void Bind(IDataBinder binder); void Bind(IDataBinder binder);} class EditBox: Control, IDataBound { void IDataBound.Bind(IDataBinder binder) {...} void IDataBound.Bind(IDataBinder binder) {...}}

31 Interfaces Interfaces in the.NET Framework IComparable IComparable IEnumerable and IEnumerator IEnumerable and IEnumerator IFormattable IFormattable IList IList ICloneable ICloneable IComponent IComponent IDataErrorInfo IDataErrorInfo

32 Demonstration 2 Base Classes Derived Classes Abstract Classes Interfaces

33 FAQs Do interface members get inherited? Do interface members get inherited?  Yes. Can you change the return value or parameter signature on an overridden member? Can you change the return value or parameter signature on an overridden member?  No. Can you override something not marked as ‘virtual’? Can you override something not marked as ‘virtual’?  No. Can an entire class be marked as ‘static’? Can an entire class be marked as ‘static’?  No.

34 Language Features Enums Strongly typed Strongly typed  No implicit conversions to/from int  Operators: +, -, ++, --, &, |, ^, ~ Can specify underlying type Can specify underlying type  Byte, short, int, long enum Color: byte { Red = 1, Red = 1, Green = 2, Green = 2, Blue = 4, Blue = 4, Black = 0, Black = 0, White = Red | Green | Blue, White = Red | Green | Blue,}

35 Agenda Overview Overview Program Structure Program Structure Value Types and Reference Types Value Types and Reference Types Base Classes, Derived Classes, Abstract Classes, & Interfaces Base Classes, Derived Classes, Abstract Classes, & Interfaces Delegates and Events Delegates and Events Operator Overloading Operator Overloading Versioning Versioning

36 Delegates Definition Object oriented function pointers Object oriented function pointers Multiple receivers Multiple receivers  Each delegate has an invocation list  Thread-safe + and - operations Foundation for framework events Foundation for framework events delegate void MouseEvent(int x, int y); delegate double Func(double x); Func MyFunc = new Func(Math.Sin); double x = MyFunc(1.0);

37 Delegates Syntax public delegate void MouseEvent(int x, int y); public delegate double Func(double x); Func MyFunc = new Func(Math.Sin); double x = MyFunc(1.0);

38 Custom Events Creating, Firing and Handle Event signature and firing logic Event signature and firing logic Handling the Event Handling the Event public class MyClass { public delegate void MyHandler(EventArgs e); public delegate void MyHandler(EventArgs e); public event MyHandler MyEvent; public event MyHandler MyEvent; if (MyEvent != null) MyEvent(e); if (MyEvent != null) MyEvent(e);} public event EventHandler Click; public event EventHandler Click; MyClass obj = new MyClass(); MyClass obj = new MyClass(); obj.MyEvent += new MyClass.MyHandler(MyFunc); obj.MyEvent += new MyClass.MyHandler(MyFunc);

39 Events System.EventHandler Define and register Event Handler Define and register Event Handler public class MyForm: Form { Button okButton; Button okButton; public MyForm() public MyForm() { okButton = new Button(...); okButton = new Button(...); okButton.Caption = "OK"; okButton.Caption = "OK"; okButton.Click += new EventHandler(OkButtonClick); okButton.Click += new EventHandler(OkButtonClick); } void OkButtonClick(object sender, EventArgs e) void OkButtonClick(object sender, EventArgs e) { ShowMessage("You pressed the OK button"); ShowMessage("You pressed the OK button"); }}

40 Demonstration 3 Delegates Events

41 Agenda Overview Overview Program Structure Program Structure Value Types and Reference Types Value Types and Reference Types Base Classes, Derived Classes, Abstract Classes, & Interfaces Base Classes, Derived Classes, Abstract Classes, & Interfaces Delegates and Events Delegates and Events Operator Overloading Operator Overloading Versioning Versioning

42 Operator Overloading Definition Allows for the specification of an operator in the context of a class you have defined. Allows for the specification of an operator in the context of a class you have defined. Binary Operators Binary Operators Unary Operators Unary Operators Implicit type Conversions Implicit type Conversions Explicit type conversions Explicit type conversions Only available in C#, not VB.NET Only available in C#, not VB.NET

43 Operator Overloading Syntax public struct DBInt {………. public static DBInt operator +(DBInt x, DBInt y) {...} public static DBInt operator +(DBInt x, DBInt y) {...} public static implicit operator DBInt(int x) {...} public static implicit operator DBInt(int x) {...} public static explicit operator int(DBInt x) {...} public static explicit operator int(DBInt x) {...}} DBInt x = 123; DBInt y = DBInt.Null; DBInt z = x + y;

44 Operator Overloading Binary and Unary Operators Binary Operators Binary Operators  + - * / % & | ^ > == != > = > == != > = <= Unary Operators Unary Operators  + - ! ~ ++ --

45 Agenda Overview Overview Program Structure Program Structure Value Types and Reference Types Value Types and Reference Types Base Classes, Derived Classes, Abstract Classes, & Interfaces Base Classes, Derived Classes, Abstract Classes, & Interfaces Delegates and Events Delegates and Events Operator Overloading Operator Overloading Versioning Versioning

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

47 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"); }} Language Features Versioning

48 Demonstration 4 Operator Overloading Version

49 MSDN Subscriptions THE way to get Visual Studio.NET Visual Studio.NET MSDN Subscriptions NEW Professional Tools to build applications and XML Web services for Windows and the Web Tools to build applications and XML Web services for Windows and the Web MSDN Professional $1199 new $899 renewal/upgrade MSDN Enterprise $2199 new $1599 renewal/upgrade MSDN Universal $2799 new $2299 renewal/upgrade Enterprise Developer Enterprise lifecycle tools Enterprise lifecycle tools Team development support Team development support Core.NET Enterprise Servers Core.NET Enterprise Servers Enterprise Architect Software and data modeling Software and data modeling Enterprise templates Enterprise templates Architectural guidance Architectural guidance

50 Questions?

51


Download ppt "Object Oriented Programming in C# Keith Pijanowski.Net Developer Evangelist Microsoft Corporation."

Similar presentations


Ads by Google