SlideShare a Scribd company logo
Introduction to C#




         Lecture 3
            FCIS
Summer training 2010, 1st year.
Contents

 
     Creating new classes
 
     Accessibility modifiers (private, public &
     protected)
 
     Constructors
 
     Method calls & this
 
     Static methods
 
     List boxes and combo boxes
 
     Parent and child forms
 
     Code example: contact list
Class Definition

 
     class <name>
 {
     <member 1>
     <member 2>
     ...
 }
     
           Members can be:
           −   Fields (member variables)
           −   Methods (member functions)
     
           Inside classes you could also define inner classes,
           structs, interfaces...
Class Definition - Example
 
     class Unit // strategy game
 {
     int health, maxHealth;
     int weaponDamage;
     Point location;
     Image img;


     void Attack(Unit otherUnit) {
           .......
      }
     void Draw(Graphics g) {
          ......
     }
 }
Accessibility modifiers

 
     public : visible to all code; inside and outside
     the class.
 
     private (default) : visible only to code inside the
     same class
 
     protected : visible only to code inside the class
     and derived classes [discussed in lecture 4].
 
     classes themselves have accessibility modifiers
     [public or internal (default) ]
Accessibility modifiers

 
     How should we decide to make something
     public or private?
     
         If it's part of the class's interface (how external code
         uses it) it should be public.
     
         If it's part of the implementation (how the class does
         it's job) it should be made private.
     
         In general, favor "private" over "public"
          −   Allows you to change implementation without breaking
              existing code.
          −   Reduces complexity of the code that uses the class
          −   Compatible with the principle of encapsulation.
Class Definition – Example 2
 public class Unit // strategy game
 {
     int health, maxHealth;
     int weaponDamage;
                                            Still private
     Point location;
     Image img;


     public void Attack(Unit otherUnit) {
          .......
     }
     public void Draw(Graphics g) {
         ......
     }
 }
Constructors

 
     Constructor are called automatically when you
     create an object with new
 
     They look like functions with the same name as
     the class and have no return value
 
     Usually, they need to be public (but private in
     some situations)
 
     A constructor can be overloaded by having
     multiple constructors with different parameter
     counts or different parameter types.
Constructors
class Point
{
    int x,y;
    public Point( ) { x = 0; y = 0; }
    public Point(int _x, int _y ) { x = _x; y = _y;}
}
class Person {
    string name, age;
    public Person(string theName, string theAge) {
         name = theName;
         age = theAge;
    }
    public Person(string name) : this(name, 10)
    {
    }
}
Method calls
 Point p = new Point(0, 0);
 Point p2 = new Point(30.0, 40.0);
 double d = p.DistanceFrom(p2);
 
     DistanceFrom takes only one parameter?
 string n = x.ToString( );
 
     ToString( ) takes no parameters?
 
     Remember: A method is called on an object.
     (Other languages say "A message is sent to an
     object”)
 
     The "object on which we called the method" is the
     call target. Like p or x in the examples.
Method calls
 
     When we call x.display( ), we are telling x to
     display itself.
 
     When we call k.ToString( ) we are asking k to give
     itself represented as a string.
 
     When we call p1.Distance(p2) we are asking the
     point p1 to give the distance between itself and
     p2.
 
     Does an object understand the concept of
     "myself"?
 
     ...Yes, only "myself" is known as this.
Method calls

    class Point {
    double x, y;
    public Point(double _x, double _y)
    {
        this.x = _x;
        this.y =_y;
    }
    public double Distance(Point p2)
    {
        double a = this.x – p2.x;
        double b = this.y – p2.y;
        return Math.Sqrt(a * a +    b * b);
    }
}
Method calls

The value of the target during method call is
 the same as the value of this during method
 execution.
Static methods
 
     Some things do are not members of objects...
     
         A function like Console.WriteLine(...) does not work
         on a specific object (the program assumes one
         console).
     
         Functions like Sin, Cos, Sqrt could be made
         members of the type Double, but they would make
         the type too big.
     
         A variable that records the count of Person object in
         the whole program does not belong to any specific
         person...
     
         A function that does some calculation before
         creating a Point object cannot be called on a point
         before it is created
Static methods
 
     class Point
 {
     double x, y;
     public Point(int _x, int _y)
     {
         x = _x;
         y = _y;
     }
     public static Point MakeFromR_Theta(double r,
                                         double theta)
     {
         int x = r * Math.Cos(theta);
         int y = r * Math.Sin(theta);
         return new Point(x, y);
     }
 }
Static methods
 
     class Test
 {
     static void Main()
     {
         Point p1 = new Point(40.0, 40.0);
         Point p2 = Point.MakeFromR_Theta(100.0, 0.3);
     }
 }
Static methods
 
     All of Methods, Variables and properties can be static
     
         An example of static properties is Color.White
 
     It is meaningless to use this in a static method, since
     there is no target for the method call.
 
     Static methods can directly call only other static
     methods. To call non-static methods it has to do this
     via an object. Non-static methods are free to call static
     methods.
 
     Similarly, static methods can access non-static
     variables only from an object, even in their own class.
 
     Static methods can access private members of objects
     in their own classes (since they are still part of the
     class).
The type 'object'

    In C# there's a special class, called 'object'

    Any other type is a subtype of object.

    A subtype can be assigned to a variable of it's supertype
    
        object obj1 = new Person( );
    
        object obj2 = 15;
    
        object obj3 = "Hello";

    The opposite is not generally true, unless there's a cast
    involved
    
        object obj4 = new Square( );
    
        Square s = obj4; // WRONG!!
    
        Square s2 = (Square) obj4; // CORRECT

    The cast means "perform a runtime type-check, and if it
    succeeds, continue".
List boxes

    list1.Items.Add("Item 1");           // Adding
    
        Actually you can pass any object to Add, not just strings:
          list1.Items.Add(15);
        list1.Items.Add(button1);

    object t =list1.Items[4];           // Accessing

    string s = list1.Items[1].ToString( ) // Converting to a string
                          // before usage

    Actually, the ListBox.Items property is a collection, so it
    has Add, Remove, RemoveAt, ...etc. It also supports
    enumeration with foreach

    You can also fill a list box's member in design-time by
    editing the "Items" property in the properties window
List box selection

    The SelectedIndex property
    
        -1 If no selection
    
        Otherwise a 0-based index of the selected item in the list.

    The SelectedItem property
    
        null if no selection
    
        Otherwise the selected item (as an object, not a string).

    The SelectedIndexChanged event: called when the user
    changes the selection (also called if the user re-selects the
    same item).

    Note: List boxes also have SelectedIndices and
    SelectedItems properties in case the user can select
    multiple items (can be set from the SelectionMode
    property).
Combo boxes

    A combo box has a Text property like a text box and
    an Items property like a list box. (This is why it's a
    combo box).

    It also has SelectedIndex, SelectedItem,
    SelectedIndexChanged...etc

    Since you already know text and list boxes, you can
    work with combo boxes.

    A combo box has a property called DropDownStyle, it
    has 3 values:
    
        Simple: Looks like a textbox on top of a listbox
    
        DropDown: Has a small arrow to show the listbox
    
        DropDownList: Allows you to open a list with the small
        arrow button, but you can select only and not edit.
Example

 
     The contact list
Next time...

 
     Inheritance
 
     Polymorphism
 
     Dynamic binding

More Related Content

What's hot (20)

PPTX
classes and objects in C++
HalaiHansaika
 
PPTX
Lecture 7 arrays
manish kumar
 
PPTX
11. Java Objects and classes
Intro C# Book
 
PPT
C++ classes tutorials
FALLEE31188
 
PDF
Python unit 3 m.sc cs
KALAISELVI P
 
PPTX
14. Java defining classes
Intro C# Book
 
PPTX
Lecture 4_Java Method-constructor_imp_keywords
manish kumar
 
PPTX
OOPS Basics With Example
Thooyavan Venkatachalam
 
PPT
Defining classes-and-objects-1.0
BG Java EE Course
 
PPTX
Classes in c++ (OOP Presentation)
Majid Saeed
 
PDF
Templates
Pranali Chaudhari
 
PPTX
20.5 Java polymorphism
Intro C# Book
 
PDF
Op ps
Shehzad Rizwan
 
PPTX
2CPP14 - Abstraction
Michael Heron
 
PDF
C sharp chap5
Mukesh Tekwani
 
PPTX
20.2 Java inheritance
Intro C# Book
 
PPTX
Introduce oop in python
tuan vo
 
PPTX
20.1 Java working with abstraction
Intro C# Book
 
PDF
Object Oriented Programming using C++ Part III
Ajit Nayak
 
PDF
Lecture 01 - Basic Concept About OOP With Python
National College of Business Administration & Economics ( NCBA&E)
 
classes and objects in C++
HalaiHansaika
 
Lecture 7 arrays
manish kumar
 
11. Java Objects and classes
Intro C# Book
 
C++ classes tutorials
FALLEE31188
 
Python unit 3 m.sc cs
KALAISELVI P
 
14. Java defining classes
Intro C# Book
 
Lecture 4_Java Method-constructor_imp_keywords
manish kumar
 
OOPS Basics With Example
Thooyavan Venkatachalam
 
Defining classes-and-objects-1.0
BG Java EE Course
 
Classes in c++ (OOP Presentation)
Majid Saeed
 
20.5 Java polymorphism
Intro C# Book
 
2CPP14 - Abstraction
Michael Heron
 
C sharp chap5
Mukesh Tekwani
 
20.2 Java inheritance
Intro C# Book
 
Introduce oop in python
tuan vo
 
20.1 Java working with abstraction
Intro C# Book
 
Object Oriented Programming using C++ Part III
Ajit Nayak
 
Lecture 01 - Basic Concept About OOP With Python
National College of Business Administration & Economics ( NCBA&E)
 

Viewers also liked (7)

PDF
Computational thinking in Egypt
mohamedsamyali
 
PDF
Spray intro
Suguru Hamazaki
 
PDF
Erlang session2
mohamedsamyali
 
PDF
Presentation skills for Graduation projects
mohamedsamyali
 
PDF
Erlang session1
mohamedsamyali
 
PDF
Smalltalk, the dynamic language
mohamedsamyali
 
PDF
Themes for graduation projects 2010
mohamedsamyali
 
Computational thinking in Egypt
mohamedsamyali
 
Spray intro
Suguru Hamazaki
 
Erlang session2
mohamedsamyali
 
Presentation skills for Graduation projects
mohamedsamyali
 
Erlang session1
mohamedsamyali
 
Smalltalk, the dynamic language
mohamedsamyali
 
Themes for graduation projects 2010
mohamedsamyali
 
Ad

Similar to C# Summer course - Lecture 3 (20)

PPT
Java class
Arati Gadgil
 
PDF
OOPs & Inheritance Notes
Shalabh Chaudhary
 
PPT
Object oriented programming using c++
Hoang Nguyen
 
PPT
3 functions and class
trixiacruz
 
PDF
Object Oriented Programming notes provided
dummydoona
 
PPT
C++ classes
imhammadali
 
PPTX
Closer look at classes
yugandhar vadlamudi
 
PPT
Introduction to csharp
voegtu
 
PPT
Introduction to csharp
voegtu
 
PPT
Introduction to csharp
hmanjarawala
 
PPT
Mca 2nd sem u-2 classes & objects
Rai University
 
PPT
Bca 2nd sem u-2 classes & objects
Rai University
 
PPTX
Constructor in c++
Jay Patel
 
PDF
C# Summer course - Lecture 2
mohamedsamyali
 
PPTX
Chapter 6.6
sotlsoc
 
PDF
Object oriented programming
Renas Rekany
 
PDF
Introduction To Csharp
sarfarazali
 
PDF
Introduction to c#
singhadarsh
 
PDF
Java Programming - 04 object oriented in java
Danairat Thanabodithammachari
 
PPTX
Intro to object oriented programming
David Giard
 
Java class
Arati Gadgil
 
OOPs & Inheritance Notes
Shalabh Chaudhary
 
Object oriented programming using c++
Hoang Nguyen
 
3 functions and class
trixiacruz
 
Object Oriented Programming notes provided
dummydoona
 
C++ classes
imhammadali
 
Closer look at classes
yugandhar vadlamudi
 
Introduction to csharp
voegtu
 
Introduction to csharp
voegtu
 
Introduction to csharp
hmanjarawala
 
Mca 2nd sem u-2 classes & objects
Rai University
 
Bca 2nd sem u-2 classes & objects
Rai University
 
Constructor in c++
Jay Patel
 
C# Summer course - Lecture 2
mohamedsamyali
 
Chapter 6.6
sotlsoc
 
Object oriented programming
Renas Rekany
 
Introduction To Csharp
sarfarazali
 
Introduction to c#
singhadarsh
 
Java Programming - 04 object oriented in java
Danairat Thanabodithammachari
 
Intro to object oriented programming
David Giard
 
Ad

Recently uploaded (20)

PPTX
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
PDF
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
PDF
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 
PDF
NewMind AI - Journal 100 Insights After The 100th Issue
NewMind AI
 
PDF
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PDF
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
PDF
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
PPTX
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
PDF
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 
PDF
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
PDF
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
PDF
From Code to Challenge: Crafting Skill-Based Games That Engage and Reward
aiyshauae
 
PDF
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
PDF
Chris Elwell Woburn, MA - Passionate About IT Innovation
Chris Elwell Woburn, MA
 
PPTX
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
PDF
HubSpot Main Hub: A Unified Growth Platform
Jaswinder Singh
 
PDF
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
PDF
Presentation - Vibe Coding The Future of Tech
yanuarsinggih1
 
PPTX
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
PDF
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 
NewMind AI - Journal 100 Insights After The 100th Issue
NewMind AI
 
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
From Code to Challenge: Crafting Skill-Based Games That Engage and Reward
aiyshauae
 
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
Chris Elwell Woburn, MA - Passionate About IT Innovation
Chris Elwell Woburn, MA
 
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
HubSpot Main Hub: A Unified Growth Platform
Jaswinder Singh
 
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
Presentation - Vibe Coding The Future of Tech
yanuarsinggih1
 
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 

C# Summer course - Lecture 3

  • 1. Introduction to C# Lecture 3 FCIS Summer training 2010, 1st year.
  • 2. Contents  Creating new classes  Accessibility modifiers (private, public & protected)  Constructors  Method calls & this  Static methods  List boxes and combo boxes  Parent and child forms  Code example: contact list
  • 3. Class Definition  class <name> { <member 1> <member 2> ... }  Members can be: − Fields (member variables) − Methods (member functions)  Inside classes you could also define inner classes, structs, interfaces...
  • 4. Class Definition - Example  class Unit // strategy game { int health, maxHealth; int weaponDamage; Point location; Image img; void Attack(Unit otherUnit) { ....... } void Draw(Graphics g) { ...... } }
  • 5. Accessibility modifiers  public : visible to all code; inside and outside the class.  private (default) : visible only to code inside the same class  protected : visible only to code inside the class and derived classes [discussed in lecture 4].  classes themselves have accessibility modifiers [public or internal (default) ]
  • 6. Accessibility modifiers  How should we decide to make something public or private?  If it's part of the class's interface (how external code uses it) it should be public.  If it's part of the implementation (how the class does it's job) it should be made private.  In general, favor "private" over "public" − Allows you to change implementation without breaking existing code. − Reduces complexity of the code that uses the class − Compatible with the principle of encapsulation.
  • 7. Class Definition – Example 2 public class Unit // strategy game { int health, maxHealth; int weaponDamage; Still private Point location; Image img; public void Attack(Unit otherUnit) { ....... } public void Draw(Graphics g) { ...... } }
  • 8. Constructors  Constructor are called automatically when you create an object with new  They look like functions with the same name as the class and have no return value  Usually, they need to be public (but private in some situations)  A constructor can be overloaded by having multiple constructors with different parameter counts or different parameter types.
  • 9. Constructors class Point { int x,y; public Point( ) { x = 0; y = 0; } public Point(int _x, int _y ) { x = _x; y = _y;} } class Person { string name, age; public Person(string theName, string theAge) { name = theName; age = theAge; } public Person(string name) : this(name, 10) { } }
  • 10. Method calls Point p = new Point(0, 0); Point p2 = new Point(30.0, 40.0); double d = p.DistanceFrom(p2);  DistanceFrom takes only one parameter? string n = x.ToString( );  ToString( ) takes no parameters?  Remember: A method is called on an object. (Other languages say "A message is sent to an object”)  The "object on which we called the method" is the call target. Like p or x in the examples.
  • 11. Method calls  When we call x.display( ), we are telling x to display itself.  When we call k.ToString( ) we are asking k to give itself represented as a string.  When we call p1.Distance(p2) we are asking the point p1 to give the distance between itself and p2.  Does an object understand the concept of "myself"?  ...Yes, only "myself" is known as this.
  • 12. Method calls  class Point { double x, y; public Point(double _x, double _y) { this.x = _x; this.y =_y; } public double Distance(Point p2) { double a = this.x – p2.x; double b = this.y – p2.y; return Math.Sqrt(a * a + b * b); } }
  • 13. Method calls The value of the target during method call is the same as the value of this during method execution.
  • 14. Static methods  Some things do are not members of objects...  A function like Console.WriteLine(...) does not work on a specific object (the program assumes one console).  Functions like Sin, Cos, Sqrt could be made members of the type Double, but they would make the type too big.  A variable that records the count of Person object in the whole program does not belong to any specific person...  A function that does some calculation before creating a Point object cannot be called on a point before it is created
  • 15. Static methods  class Point { double x, y; public Point(int _x, int _y) { x = _x; y = _y; } public static Point MakeFromR_Theta(double r, double theta) { int x = r * Math.Cos(theta); int y = r * Math.Sin(theta); return new Point(x, y); } }
  • 16. Static methods  class Test { static void Main() { Point p1 = new Point(40.0, 40.0); Point p2 = Point.MakeFromR_Theta(100.0, 0.3); } }
  • 17. Static methods  All of Methods, Variables and properties can be static  An example of static properties is Color.White  It is meaningless to use this in a static method, since there is no target for the method call.  Static methods can directly call only other static methods. To call non-static methods it has to do this via an object. Non-static methods are free to call static methods.  Similarly, static methods can access non-static variables only from an object, even in their own class.  Static methods can access private members of objects in their own classes (since they are still part of the class).
  • 18. The type 'object'  In C# there's a special class, called 'object'  Any other type is a subtype of object.  A subtype can be assigned to a variable of it's supertype  object obj1 = new Person( );  object obj2 = 15;  object obj3 = "Hello";  The opposite is not generally true, unless there's a cast involved  object obj4 = new Square( );  Square s = obj4; // WRONG!!  Square s2 = (Square) obj4; // CORRECT  The cast means "perform a runtime type-check, and if it succeeds, continue".
  • 19. List boxes  list1.Items.Add("Item 1"); // Adding  Actually you can pass any object to Add, not just strings: list1.Items.Add(15); list1.Items.Add(button1);  object t =list1.Items[4]; // Accessing  string s = list1.Items[1].ToString( ) // Converting to a string // before usage  Actually, the ListBox.Items property is a collection, so it has Add, Remove, RemoveAt, ...etc. It also supports enumeration with foreach  You can also fill a list box's member in design-time by editing the "Items" property in the properties window
  • 20. List box selection  The SelectedIndex property  -1 If no selection  Otherwise a 0-based index of the selected item in the list.  The SelectedItem property  null if no selection  Otherwise the selected item (as an object, not a string).  The SelectedIndexChanged event: called when the user changes the selection (also called if the user re-selects the same item).  Note: List boxes also have SelectedIndices and SelectedItems properties in case the user can select multiple items (can be set from the SelectionMode property).
  • 21. Combo boxes  A combo box has a Text property like a text box and an Items property like a list box. (This is why it's a combo box).  It also has SelectedIndex, SelectedItem, SelectedIndexChanged...etc  Since you already know text and list boxes, you can work with combo boxes.  A combo box has a property called DropDownStyle, it has 3 values:  Simple: Looks like a textbox on top of a listbox  DropDown: Has a small arrow to show the listbox  DropDownList: Allows you to open a list with the small arrow button, but you can select only and not edit.
  • 22. Example  The contact list
  • 23. Next time...  Inheritance  Polymorphism  Dynamic binding