SlideShare uma empresa Scribd logo
1 de 21
Writing Object
Oriented Software
with C#
C# and OOP
   C# is designed for the .NET Framework
     The   .NET Framework is Object Oriented
   In C#
     Your  access to the OS is through objects
     You have the ability to create first class
      objects
     The FCL is designed for extension and
      integration by your code
Defining Classes
class Name:BaseType{
   // Members
}

Namespace NameName{
   class Name:BaseType{
   }
}

class MyType{
   public static String someTypeState;
   public Int32 x;
   public Int32 y;
}
Accessibility
   In C#, private is the default accessibility
   Accessibilities options
       public – Accessible to all
       private – Accessible to containing class
       protected – Accessible to containing or derived classes
       internal – Accessible to code in same assembly
       protected internal – means protected or internal
   Classes can be marked as public or internal
     By default they are private
     Accessible only to code in the same source module
Type Members in C#
   Fields
     The    state of an object or type
   Methods
     Constructors
     Functions
     Properties      (smart fields)
   Members come in two basic forms
     Instance       – per object data and methods
          Default
     Static   – per type data and methods
          Use the static keyword
Methods
   Declared inline with type definition
class MyType{
   public Int32 SomeMethod(){
      return x;
   }

    public static void StaticMethod(){
       // Do something
    }
}

   No inline keyword, methods are inlined
    when appropriate by the JIT compiler
Properties
   Methods that look like fields (smart fields)
class Point{
   Int32 x;
   Int32 y;
   public Int32 X{
      get{return x;}
      set{x = value;}
   }
   public Int32 Y{
      get{return y;}
      set{y = value;}
   }
}

   Can have read-only or write-only properties
Demo Classes and Properties




Point-0.cs
Instance Constructors
   Constructors are used to initialize fields
   You can implement simpler constructors in terms of more
    complex ones with the this keyword (suggested)
    class Point{
       Int32 x;
       Int32 y;

            public Point():this(0, 0){}

            public Point(Int32 x, Int32 y){
               this.x = x;
               this.y = y;
            }
    }
   You can indicate which base constructor to call
           Use the base keyword
Type (static) Constructors
 Type constructors are used to initialize
  static fields for a type
 Only one static constructor per type
     Called by the Common Language Runtime
     Guaranteed to be called before any reference to
      the type or an instance of the type
     Must have no parameters
   Use the static keyword to indicate a type
    constructor
Derivation and Object
   All types in the system are derived from Object
   You can specify a base class
     Without   a base class the compiler assumes Object
   Object reference variables are used as generic
    references
     Collection   classes in the Framework Class Library
   Object implements useful methods like
     ToString(),GetType()
     ReferenceEquals()
Polymorphism and Virtual Functions
       Use the virtual keyword to make a method virtual
       In derived class, override method is marked with the
        override keyword
       Example
           ToString() method in Object class
          public virtual string ToString();
           Example derived class overriding ToString()

          class SomeClass:Object{
             public override String ToString(){
                return “Some String Representing State”;
             }
          }
Polymorphism.cs
C# and Events
   C# has built in support for events
   Great for dealing with objects in an event-driven
    operating system
   Improved performance and flexibility over an all-
    virtual-function solution
   More than one type can register interest in a
    single event
   A single type can register interest in any number
    of events
Handling an Event
EventHand.cs
using System;
using System.Windows.Forms;
class MyForm:Form{
   MyForm(){
      Button button = new Button();
      button.Text = "Button";
      button.Click += new EventHandler(HandleClick);
      Controls.Add(button);
   }
   void HandleClick(Object sender, EventArgs e){
      MessageBox.Show("The Click event fired!");
   }
   public static void Main(){
      Application.Run(new MyForm());
   }
}
Demo EventHand.cs
Defining an Event
       Based on a callback mechanism called a delegate
     class EventInt{
        Int32 val;
        public Int32 Value{
           get{return val;}
           set{
              if(Changed != null)
                 Changed(value, val);
              val = value;
           }
        }
        public event Callback Changed;
        public delegate
           void Callback(Int32 newVal, Int32 oldVal);
     }

EventInt.cs
Callback Methods (Delegates)
Delegates.cs
using System;
delegate void MyDelegate(String message);
class App{
   public static void Main(){
      MyDelegate call = new MyDelegate(FirstMethod);
      call += new MyDelegate(SecondMethod);
      call("Message A");
      call("Message B");
   }
   static void FirstMethod(String str){
      Console.WriteLine("1st method: "+str);
   }
   static void SecondMethod(String str){
      Console.WriteLine("2nd method: "+str);
   }
}
Interfaces
       C# supports interfaces
          Your     types can implement interfaces
                 Must implement all methods in the interface
          You     can define custom interfaces
       Interfaces can contain methods but no fields
          Propertiesand events included
          Constructors are not supported in interfaces

       Use the interface keyword
     interface Name{
        // Members
     }
Sortable.cs
Operator Overloading and Type
   Conversion
    C# allows you to write operator overload
     methods
    Called when a custom type is used in an
     expression with operators
        Can     overload:         +, -, *, |, etc.
      Can create custom cast methods
        Implicitlyor explicitly convert your type to
          another type

Overloading.cs TypeConverters.cs
C# and OOP
   C# and the .NET Framework promote
    component development
     Can use binary or pre-compiled objects
     More applications will use more components
     Creates a market for third-party component
      venders
     Strong security story allows for internet
      deployment of objects
   C# has a great set of tools for the object
    oriented programmer
Writing Object
Oriented Software
with C#

Mais conteúdo relacionado

Mais procurados

Introduction to objective c
Introduction to objective cIntroduction to objective c
Introduction to objective c
Sunny Shaikh
 
Introduction to csharp
Introduction to csharpIntroduction to csharp
Introduction to csharp
Raga Vahini
 
Introduction to csharp
Introduction to csharpIntroduction to csharp
Introduction to csharp
hmanjarawala
 
Introduction To Csharp
Introduction To CsharpIntroduction To Csharp
Introduction To Csharp
sarfarazali
 

Mais procurados (19)

Introduction to objective c
Introduction to objective cIntroduction to objective c
Introduction to objective c
 
Intake 37 1
Intake 37 1Intake 37 1
Intake 37 1
 
Objective c
Objective cObjective c
Objective c
 
Basic c#
Basic c#Basic c#
Basic c#
 
Net framework session01
Net framework session01Net framework session01
Net framework session01
 
Day02 01 Advance Feature in C# DH TDT
Day02 01 Advance Feature in C# DH TDTDay02 01 Advance Feature in C# DH TDT
Day02 01 Advance Feature in C# DH TDT
 
Chapter 2 c#
Chapter 2 c#Chapter 2 c#
Chapter 2 c#
 
Delegates and events in C#
Delegates and events in C#Delegates and events in C#
Delegates and events in C#
 
Constructors destructors
Constructors destructorsConstructors destructors
Constructors destructors
 
Introduction to c#
Introduction to c#Introduction to c#
Introduction to c#
 
Delegates and events
Delegates and events   Delegates and events
Delegates and events
 
OOP interview questions & answers.
OOP interview questions & answers.OOP interview questions & answers.
OOP interview questions & answers.
 
Explain Delegates step by step.
Explain Delegates step by step.Explain Delegates step by step.
Explain Delegates step by step.
 
Introduction to csharp
Introduction to csharpIntroduction to csharp
Introduction to csharp
 
Introduction to csharp
Introduction to csharpIntroduction to csharp
Introduction to csharp
 
Intake 38 12
Intake 38 12Intake 38 12
Intake 38 12
 
C++ classes
C++ classesC++ classes
C++ classes
 
Introduction To Csharp
Introduction To CsharpIntroduction To Csharp
Introduction To Csharp
 
Core Java Programming Language (JSE) : Chapter III - Identifiers, Keywords, ...
Core Java Programming Language (JSE) : Chapter III -  Identifiers, Keywords, ...Core Java Programming Language (JSE) : Chapter III -  Identifiers, Keywords, ...
Core Java Programming Language (JSE) : Chapter III - Identifiers, Keywords, ...
 

Semelhante a 03 oo with-c-sharp

Intro to object oriented programming
Intro to object oriented programmingIntro to object oriented programming
Intro to object oriented programming
David Giard
 
Introduction to csharp
Introduction to csharpIntroduction to csharp
Introduction to csharp
voegtu
 
Introduction to csharp
Introduction to csharpIntroduction to csharp
Introduction to csharp
voegtu
 
Introduction to c#
Introduction to c#Introduction to c#
Introduction to c#
singhadarsh
 
Introduction To Csharp
Introduction To CsharpIntroduction To Csharp
Introduction To Csharp
g_hemanth17
 
Introduction to-csharp-1229579367461426-1
Introduction to-csharp-1229579367461426-1Introduction to-csharp-1229579367461426-1
Introduction to-csharp-1229579367461426-1
Sachin Singh
 
Introduction to CSharp
Introduction to CSharpIntroduction to CSharp
Introduction to CSharp
Mody Farouk
 
Introduction to csharp
Introduction to csharpIntroduction to csharp
Introduction to csharp
Satish Verma
 
Introduction to csharp
Introduction to csharpIntroduction to csharp
Introduction to csharp
singhadarsh
 
classes object fgfhdfgfdgfgfgfgfdoop.pptx
classes object  fgfhdfgfdgfgfgfgfdoop.pptxclasses object  fgfhdfgfdgfgfgfgfdoop.pptx
classes object fgfhdfgfdgfgfgfgfdoop.pptx
arjun431527
 

Semelhante a 03 oo with-c-sharp (20)

Intro to object oriented programming
Intro to object oriented programmingIntro to object oriented programming
Intro to object oriented programming
 
Intake 38 5 1
Intake 38 5 1Intake 38 5 1
Intake 38 5 1
 
Introduction to csharp
Introduction to csharpIntroduction to csharp
Introduction to csharp
 
Introduction to csharp
Introduction to csharpIntroduction to csharp
Introduction to csharp
 
Introduction to c#
Introduction to c#Introduction to c#
Introduction to c#
 
OOC MODULE1.pptx
OOC MODULE1.pptxOOC MODULE1.pptx
OOC MODULE1.pptx
 
Notes(1).pptx
Notes(1).pptxNotes(1).pptx
Notes(1).pptx
 
Getting Started - Console Program and Problem Solving
Getting Started - Console Program and Problem SolvingGetting Started - Console Program and Problem Solving
Getting Started - Console Program and Problem Solving
 
SPF Getting Started - Console Program
SPF Getting Started - Console ProgramSPF Getting Started - Console Program
SPF Getting Started - Console Program
 
C#ppt
C#pptC#ppt
C#ppt
 
Chapter 1 Presentation
Chapter 1 PresentationChapter 1 Presentation
Chapter 1 Presentation
 
Microsoft dynamics ax 2012 development introduction part 2/3
Microsoft dynamics ax 2012 development introduction part 2/3Microsoft dynamics ax 2012 development introduction part 2/3
Microsoft dynamics ax 2012 development introduction part 2/3
 
Csharp generics
Csharp genericsCsharp generics
Csharp generics
 
Typescript language extension of java script
Typescript language extension of java scriptTypescript language extension of java script
Typescript language extension of java script
 
Introduction To Csharp
Introduction To CsharpIntroduction To Csharp
Introduction To Csharp
 
Introduction to-csharp-1229579367461426-1
Introduction to-csharp-1229579367461426-1Introduction to-csharp-1229579367461426-1
Introduction to-csharp-1229579367461426-1
 
Introduction to CSharp
Introduction to CSharpIntroduction to CSharp
Introduction to CSharp
 
Introduction to csharp
Introduction to csharpIntroduction to csharp
Introduction to csharp
 
Introduction to csharp
Introduction to csharpIntroduction to csharp
Introduction to csharp
 
classes object fgfhdfgfdgfgfgfgfdoop.pptx
classes object  fgfhdfgfdgfgfgfgfdoop.pptxclasses object  fgfhdfgfdgfgfgfgfdoop.pptx
classes object fgfhdfgfdgfgfgfgfdoop.pptx
 

Último

1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
QucHHunhnh
 
An Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdfAn Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdf
SanaAli374401
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
QucHHunhnh
 
Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.
MateoGardella
 

Último (20)

Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
An Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdfAn Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdf
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 

03 oo with-c-sharp

  • 2. C# and OOP  C# is designed for the .NET Framework  The .NET Framework is Object Oriented  In C#  Your access to the OS is through objects  You have the ability to create first class objects  The FCL is designed for extension and integration by your code
  • 3. Defining Classes class Name:BaseType{ // Members } Namespace NameName{ class Name:BaseType{ } } class MyType{ public static String someTypeState; public Int32 x; public Int32 y; }
  • 4. Accessibility  In C#, private is the default accessibility  Accessibilities options  public – Accessible to all  private – Accessible to containing class  protected – Accessible to containing or derived classes  internal – Accessible to code in same assembly  protected internal – means protected or internal  Classes can be marked as public or internal  By default they are private  Accessible only to code in the same source module
  • 5. Type Members in C#  Fields  The state of an object or type  Methods  Constructors  Functions  Properties (smart fields)  Members come in two basic forms  Instance – per object data and methods  Default  Static – per type data and methods  Use the static keyword
  • 6. Methods  Declared inline with type definition class MyType{ public Int32 SomeMethod(){ return x; } public static void StaticMethod(){ // Do something } }  No inline keyword, methods are inlined when appropriate by the JIT compiler
  • 7. Properties  Methods that look like fields (smart fields) class Point{ Int32 x; Int32 y; public Int32 X{ get{return x;} set{x = value;} } public Int32 Y{ get{return y;} set{y = value;} } }  Can have read-only or write-only properties
  • 8. Demo Classes and Properties Point-0.cs
  • 9. Instance Constructors  Constructors are used to initialize fields  You can implement simpler constructors in terms of more complex ones with the this keyword (suggested) class Point{ Int32 x; Int32 y; public Point():this(0, 0){} public Point(Int32 x, Int32 y){ this.x = x; this.y = y; } }  You can indicate which base constructor to call  Use the base keyword
  • 10. Type (static) Constructors  Type constructors are used to initialize static fields for a type  Only one static constructor per type  Called by the Common Language Runtime  Guaranteed to be called before any reference to the type or an instance of the type  Must have no parameters  Use the static keyword to indicate a type constructor
  • 11. Derivation and Object  All types in the system are derived from Object  You can specify a base class  Without a base class the compiler assumes Object  Object reference variables are used as generic references  Collection classes in the Framework Class Library  Object implements useful methods like  ToString(),GetType()  ReferenceEquals()
  • 12. Polymorphism and Virtual Functions  Use the virtual keyword to make a method virtual  In derived class, override method is marked with the override keyword  Example  ToString() method in Object class public virtual string ToString();  Example derived class overriding ToString() class SomeClass:Object{ public override String ToString(){ return “Some String Representing State”; } } Polymorphism.cs
  • 13. C# and Events  C# has built in support for events  Great for dealing with objects in an event-driven operating system  Improved performance and flexibility over an all- virtual-function solution  More than one type can register interest in a single event  A single type can register interest in any number of events
  • 14. Handling an Event EventHand.cs using System; using System.Windows.Forms; class MyForm:Form{ MyForm(){ Button button = new Button(); button.Text = "Button"; button.Click += new EventHandler(HandleClick); Controls.Add(button); } void HandleClick(Object sender, EventArgs e){ MessageBox.Show("The Click event fired!"); } public static void Main(){ Application.Run(new MyForm()); } }
  • 16. Defining an Event  Based on a callback mechanism called a delegate class EventInt{ Int32 val; public Int32 Value{ get{return val;} set{ if(Changed != null) Changed(value, val); val = value; } } public event Callback Changed; public delegate void Callback(Int32 newVal, Int32 oldVal); } EventInt.cs
  • 17. Callback Methods (Delegates) Delegates.cs using System; delegate void MyDelegate(String message); class App{ public static void Main(){ MyDelegate call = new MyDelegate(FirstMethod); call += new MyDelegate(SecondMethod); call("Message A"); call("Message B"); } static void FirstMethod(String str){ Console.WriteLine("1st method: "+str); } static void SecondMethod(String str){ Console.WriteLine("2nd method: "+str); } }
  • 18. Interfaces  C# supports interfaces  Your types can implement interfaces  Must implement all methods in the interface  You can define custom interfaces  Interfaces can contain methods but no fields  Propertiesand events included  Constructors are not supported in interfaces  Use the interface keyword interface Name{ // Members } Sortable.cs
  • 19. Operator Overloading and Type Conversion  C# allows you to write operator overload methods  Called when a custom type is used in an expression with operators  Can overload: +, -, *, |, etc.  Can create custom cast methods  Implicitlyor explicitly convert your type to another type Overloading.cs TypeConverters.cs
  • 20. C# and OOP  C# and the .NET Framework promote component development  Can use binary or pre-compiled objects  More applications will use more components  Creates a market for third-party component venders  Strong security story allows for internet deployment of objects  C# has a great set of tools for the object oriented programmer

Notas do Editor

  1. Sample Dialog: Speaker Instructions: You should introduce yourself on this slide. Briefly address the topic of the evening and mention the length of the presentation. You can also discuss the nature of your organization (user group, etc.) while on this slide.
  2. Sample Dialog: You probably already know that C# is one of the most popular programming language choices for writing software that targets the .NET Framework. The .NET Framework itself is a completely object oriented platform, and C# is a first class object oriented programming language to complement this platform. In C# your software’s access to the system is through objects, meanwhile your application and application logic is managed as objects. Finally, the Framework Class Library is designed for extendibility. It is natural to extend the classes in the FCL, so that your application’s objects blend right in with the library objects. Speaker Instructions: Anybody who knows about C# probably already knows that it is object oriented, etc. So this slide is really just here to introduce (briefly) the relationship between C# and the .NET Framework, etc, for those who know very little about the products.
  3. Sample Dialog: C# is a a language with C++-based syntax much like Java is derived from C++. To define a class you use the class keyword, your classes name, and base class. C# supports namespaces. Every type in the Framework Class Library exists in a namespace. You should give your reusable types a namespace as well, however it is less necessary for your application classes to be in a namespace. This last example shows a class that does not explicitly declare a base class, so it is implicitly derived from Object, and it also shows the definition of a couple of fields in the type. Speaker Instructions:
  4. Sample Dialog: Like C++ and Java, C# supports member and class accessibility. The default accessibility is private, and you must decorate members with an accessibility modifier to set a different accessibility. The most common accessibilities are public, private, and protected. However, C# introduces the idea of an internal accessibility which allows access by any class in the same binary assembly file. This is similar to, but more flexible than the C++ friend class. Speaker Instructions: You could spend forever talking about accessibility. If you like you can edge into the direction of design by saying that fields should be private, and methods can be public, etc. But be careful, because you could sink ten minutes on this slide alone.
  5. Sample Dialog: In C# like any other object oriented language, the members in a type are basically either fields or methods. However, C# has a rich selection of field and method options. Fields are the data or state of an object or type, and methods are the functionality. Members come in two basic forms, instance and static. Instance members are the most common, and there will be one per instance or object. Static members are shared amongst instances and are one per type. Instance methods require an instance to be called, but static methods can be called directly just using the name of the type. The automatic “this” parameter is passed to instance methods, but not static methods. In .NET or managed code it is a common design pattern to create a class that cannot be instantiated, with nothing but static methods. This is a way of creating methods that are sort-of global, but are still logically grouped with other related methods. The System.Console class is an example of this design pattern. Speaker Instructions: You don’t have to say the stuff in that last paragraph, but concrete examples like these do help to nail down the ideas for the listeners.
  6. Sample Dialog: Methods in C# are declared inline of the class definition. This means that the entire implementation of a class must exist in a single source module. In this example I define a MyType class which defines a single instance method and a single static method. Speaker Instructions: My of the slides in this presentation have little on them but code. In these slides you should point out the relevant pieces of the source code. Depending on your presentation equipment, you may be able to point to the code with your hand, or you can use the mouse pointer to run down the different parts. This helps the watcher to follow along.
  7. Sample Dialog: Properties are a cool kind of method that looks like a field when it is accessed in code. This makes for very readable code that still adheres to the object-oriented guideline of making all fields private. You can make your fields private, and allow access via public properties. In this example the Point class defines private x and y fields, and then it defines two public properties which just access the fields directly. You can put any kind of code that you like in the get and set methods of a property, including validation code, event notification code, or just about anything. In fact, it isn’t even necessary for a property to be backed by an actual field. Speaker Instructions: Properties are a great feature of C#. Be sure to understand them so that you can properly sell this idea. It is a strong feature for OO programmers.
  8. Sample Dialog: Now I am going to switch over to source code and show you the use of a simple class, that also defines properties. Speaker Instructions: You should compile the following code, and step through it. Take the time to explain how it works a bit, and show the code stepping into a property method. using System; class Point{ Int32 x; Int32 y; public Int32 X{ get{return x;} set{x = value;} } public Int32 Y{ get{return y;} set{y = value;} } } class App{ public static void Main(){ Point p = new Point(); p.X = 10; p.Y = p.X+5; Console.WriteLine(p.Y); } }
  9. Sample Dialog: C# supports constructor syntax much like C++. However, unlike C++ it is invalid to call a constructor method directly, so if you wish to implement a constructor in terms of another constructor you must use the special colon-this notation you see here. In this example, the simpler Point() constructor automatically calls the more complex constructor with the default x and y values of 0. Speaker Instructions: FYI, it is recommended that you have only one constructor for a type, and that the rest of the constructors be implemented in terms of this one. However, this is not always possible and must be handled on a type-by-type bases.
  10. Sample Dialog: Static or type constructors are a great feature of C# that did not exist in C++. Type constructors are used to initialize static data for a type. A type constructor is called before any other reference to a type is made. However, other than this promise, the Common Language Runtime does not make any promises of when type constructors will be called. The code in your type constructors should be kept simple, and should not block. Speaker Instructions: The type constructor gets rid of the need to check for static initialization in each call to an instance constructor before getting down to the business of initializing an instance. This simplifies type definitions in C# over C++.
  11. Sample Dialog: In C# all types are derived from Object. Often this is transparent to the developer, but sometimes it can be useful. For example, Object reference variables can be used as generic references that can reference any type. Also, Object itself implements several useful methods that can be used on any type, such as the GetType() method, that can be used for type checking of an object. The virtual ToString() method is also useful for debugging types. Finally, the Object class implements a couple of static methods, the most useful of which is the ReferenceEquals() methods which let you test two object references to see if they refer to the same instance in memory. Speaker Instructions:
  12. Sample Dialog: To create a virtual function in C# you must attribute your method with the virtual keyword. Virtual methods can be public, protected, or protected internal. To override a virtual method in a derived class you must explicitly indicate your intent using the override keyword. Your derived method must also match the base method signature exactly. Speaker Instructions: The override keyword is actually part of the versioning story in the .NET Framework. But this is probably a bit too much to explain in the discussion. However, for your own study you may want to look up the “override” and “new” keywords in the documentation, as this is an example of a feature that is much more well thought out than the equivalent feature in Java.
  13. Sample Dialog: C# has built in support for event notification and handling, which is great for dealing with OSs that are becoming increasingly event driven. Events in C# are very flexible compared to the virtual-function method of responding to system events. Speaker Instructions: We have several slides on this, so you don’t have to say everything on this slide.
  14. Sample Dialog: The source code on this slide shows a simple class derived from Form. The interesting part, however, is how the class registers its interest in the Click event defined by an instance of the Button class. The MyForm class indicates which of its methods (in this case the HandleClick method) should be called when the event is fired. Speaker Instructions: This code is a demo on the next slide
  15. Sample Dialog: Speaker Instructions: There is no dialog on this slide, because really the dialog from the last slide goes with this demo. You can do the two together. You should at least run this code, and perhaps step through it putting a break-point in the Handle method. This helps to drive the event concept home.
  16. Sample Dialog: Using events is common in C# code, but from time to time you will also want to define an event for your own type that you fire at the appropriate time. This code shows an example of a simple class that fires an event whenever a value of one of its properties is changed. (Normally events are fired as a result of external events, but this shows the idea here). The event is named Changed, and is of type Callback. The Callback type is actually a special type called a delegate, which is the managed code version of a function pointer. The delegate definition defines how the event-handler method must be defined, and what parameters it must accept. Then, when it is time to call the code, the event variable is checked for null, and if it is not null, it is used as though it were a method, which causes all of the registered handlers to be called. Speaker Instructions: This can be confusing, and you should definitely point out the code as you describe the different parts. By the way, if this is confusing to you, just compile and run this code, and try changing some things here and there, it becomes clear quickly when you do this.
  17. Sample Dialog: As I mentioned on the previous slide, callback methods themselves are actually implemented using a special type called a delegate. The delegate type can be used directly without events. The framework class library does this from time to time, when it needs a callback, such as when you start a thread, or fire-off an asynchronous method. When you use the delegate keyword in C#, even though it looks like a method definition, it is really a new type definition for maintaining a reference to a method that matches the parameter list and return type of the delegate. This code creates two instances of the MyDelegate delegate, one each for the two methods here. Then the delegate chain is called which is the same syntax as calling into an event. Each time the delegate chain is called, both methods are executed. Speaker Instructions: Again this is an example of code that becomes much more clear once you run it. I strongly suggest that you try this code before attempting to describe the ideas in front of a group of people.
  18. Sample Dialog: Interfaces are an excellent way for a type to take on a role without being derived from a type that defines this role. For example, two totally unrelated types can be sortable and therefore take on the well-defined ability to be sorted, even though they are not derived in the same derivation hierarchy. This is possible through interfaces. In C# you cannot have multiple base classes, but a type can implement any number of interfaces. You will find that you implement pre-existing interfaces often, but from time to time you will have to define your own interface. Interfaces can include only methods, properties, and events. It is not valid for an interface to include a field. Interfaces are defined using the interface keyword as shown here. Speaker Instructions:
  19. Sample Dialog: C# has support for operator overloading and type conversion methods. With operator overloading and conversion methods, you can make it so a custom type can be used in expressions with operators such as plus, minus, and assignment. Operator overloading can be very useful when defining custom math types, however, there are also uses unrelated to math types. For example, the C++ standard template library uses the left shift and right shift operators to indicate input and output from stream objects. This is a unique use of operator overloading that makes for readable code, and C# is flexible enough to be used in similar ways. Speaker Instructions:
  20. Sample Dialog: In general, C# is similar to but more feature-full than C++ in terms of its object oriented abilities. However, one area where C# far-outshines C++ is in the use of binary objects. C# is designed in such a way that you can define an object, and compile it into a binary or assembly file. Then programmers can still use the object in its binary form in their own code, they can derive from it, or do anything that they would be able to do if they actually had the sources. This kind of binary modularity really opens up the market for component development. Applications moving forward will be much more component based. The .NET Framework and C# also has a very strong security model that allows for derivation and use of objects from third parties that are deployed over the internet. And even though you are downloading code and running it locally, you need not worry about code modification, or tampering with your system. C# is a first class language for object oriented programming. Speaker Instructions:
  21. Sample Dialog: Speaker Instructions: Open the floor to questions