SlideShare une entreprise Scribd logo
1  sur  23
Télécharger pour lire hors ligne
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

Contenu connexe

Tendances

classes and objects in C++
classes and objects in C++classes and objects in C++
classes and objects in C++HalaiHansaika
 
11. Java Objects and classes
11. Java  Objects and classes11. Java  Objects and classes
11. Java Objects and classesIntro C# Book
 
C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorialsFALLEE31188
 
Python unit 3 m.sc cs
Python unit 3 m.sc csPython unit 3 m.sc cs
Python unit 3 m.sc csKALAISELVI P
 
14. Java defining classes
14. Java defining classes14. Java defining classes
14. Java defining classesIntro C# Book
 
Lecture 4_Java Method-constructor_imp_keywords
Lecture   4_Java Method-constructor_imp_keywordsLecture   4_Java Method-constructor_imp_keywords
Lecture 4_Java Method-constructor_imp_keywordsmanish kumar
 
Defining classes-and-objects-1.0
Defining classes-and-objects-1.0Defining classes-and-objects-1.0
Defining classes-and-objects-1.0BG Java EE Course
 
Classes in c++ (OOP Presentation)
Classes in c++ (OOP Presentation)Classes in c++ (OOP Presentation)
Classes in c++ (OOP Presentation)Majid Saeed
 
20.5 Java polymorphism
20.5 Java polymorphism 20.5 Java polymorphism
20.5 Java polymorphism Intro C# Book
 
2CPP14 - Abstraction
2CPP14 - Abstraction2CPP14 - Abstraction
2CPP14 - AbstractionMichael Heron
 
20.2 Java inheritance
20.2 Java inheritance20.2 Java inheritance
20.2 Java inheritanceIntro C# Book
 
Introduce oop in python
Introduce oop in pythonIntroduce oop in python
Introduce oop in pythontuan vo
 
20.1 Java working with abstraction
20.1 Java working with abstraction20.1 Java working with abstraction
20.1 Java working with abstractionIntro C# Book
 
Object Oriented Programming using C++ Part III
Object Oriented Programming using C++ Part IIIObject Oriented Programming using C++ Part III
Object Oriented Programming using C++ Part IIIAjit Nayak
 

Tendances (20)

classes and objects in C++
classes and objects in C++classes and objects in C++
classes and objects in C++
 
Lecture 7 arrays
Lecture   7 arraysLecture   7 arrays
Lecture 7 arrays
 
11. Java Objects and classes
11. Java  Objects and classes11. Java  Objects and classes
11. Java Objects and classes
 
C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorials
 
Python unit 3 m.sc cs
Python unit 3 m.sc csPython unit 3 m.sc cs
Python unit 3 m.sc cs
 
14. Java defining classes
14. Java defining classes14. Java defining classes
14. Java defining classes
 
Lecture 4_Java Method-constructor_imp_keywords
Lecture   4_Java Method-constructor_imp_keywordsLecture   4_Java Method-constructor_imp_keywords
Lecture 4_Java Method-constructor_imp_keywords
 
OOPS Basics With Example
OOPS Basics With ExampleOOPS Basics With Example
OOPS Basics With Example
 
Defining classes-and-objects-1.0
Defining classes-and-objects-1.0Defining classes-and-objects-1.0
Defining classes-and-objects-1.0
 
Classes in c++ (OOP Presentation)
Classes in c++ (OOP Presentation)Classes in c++ (OOP Presentation)
Classes in c++ (OOP Presentation)
 
Templates
TemplatesTemplates
Templates
 
20.5 Java polymorphism
20.5 Java polymorphism 20.5 Java polymorphism
20.5 Java polymorphism
 
Op ps
Op psOp ps
Op ps
 
2CPP14 - Abstraction
2CPP14 - Abstraction2CPP14 - Abstraction
2CPP14 - Abstraction
 
C sharp chap5
C sharp chap5C sharp chap5
C sharp chap5
 
20.2 Java inheritance
20.2 Java inheritance20.2 Java inheritance
20.2 Java inheritance
 
Introduce oop in python
Introduce oop in pythonIntroduce oop in python
Introduce oop in python
 
20.1 Java working with abstraction
20.1 Java working with abstraction20.1 Java working with abstraction
20.1 Java working with abstraction
 
Object Oriented Programming using C++ Part III
Object Oriented Programming using C++ Part IIIObject Oriented Programming using C++ Part III
Object Oriented Programming using C++ Part III
 
Lecture 01 - Basic Concept About OOP With Python
Lecture 01 - Basic Concept About OOP With PythonLecture 01 - Basic Concept About OOP With Python
Lecture 01 - Basic Concept About OOP With Python
 

En vedette

Computational thinking in Egypt
Computational thinking in EgyptComputational thinking in Egypt
Computational thinking in Egyptmohamedsamyali
 
Presentation skills for Graduation projects
Presentation skills for Graduation projectsPresentation skills for Graduation projects
Presentation skills for Graduation projectsmohamedsamyali
 
Smalltalk, the dynamic language
Smalltalk, the dynamic languageSmalltalk, the dynamic language
Smalltalk, the dynamic languagemohamedsamyali
 
Themes for graduation projects 2010
Themes for graduation projects   2010Themes for graduation projects   2010
Themes for graduation projects 2010mohamedsamyali
 

En vedette (7)

Computational thinking in Egypt
Computational thinking in EgyptComputational thinking in Egypt
Computational thinking in Egypt
 
Spray intro
Spray introSpray intro
Spray intro
 
Erlang session2
Erlang session2Erlang session2
Erlang session2
 
Presentation skills for Graduation projects
Presentation skills for Graduation projectsPresentation skills for Graduation projects
Presentation skills for Graduation projects
 
Erlang session1
Erlang session1Erlang session1
Erlang session1
 
Smalltalk, the dynamic language
Smalltalk, the dynamic languageSmalltalk, the dynamic language
Smalltalk, the dynamic language
 
Themes for graduation projects 2010
Themes for graduation projects   2010Themes for graduation projects   2010
Themes for graduation projects 2010
 

Similaire à C# Summer course - Lecture 3

Object oriented programming using c++
Object oriented programming using c++Object oriented programming using c++
Object oriented programming using c++Hoang Nguyen
 
3 functions and class
3   functions and class3   functions and class
3 functions and classtrixiacruz
 
Introduction to csharp
Introduction to csharpIntroduction to csharp
Introduction to csharpvoegtu
 
Introduction to csharp
Introduction to csharpIntroduction to csharp
Introduction to csharphmanjarawala
 
Introduction to csharp
Introduction to csharpIntroduction to csharp
Introduction to csharpvoegtu
 
Mca 2nd sem u-2 classes & objects
Mca 2nd  sem u-2 classes & objectsMca 2nd  sem u-2 classes & objects
Mca 2nd sem u-2 classes & objectsRai University
 
Bca 2nd sem u-2 classes & objects
Bca 2nd sem u-2 classes & objectsBca 2nd sem u-2 classes & objects
Bca 2nd sem u-2 classes & objectsRai University
 
Constructor in c++
Constructor in c++Constructor in c++
Constructor in c++Jay Patel
 
C# Summer course - Lecture 2
C# Summer course - Lecture 2C# Summer course - Lecture 2
C# Summer course - Lecture 2mohamedsamyali
 
Chapter 6.6
Chapter 6.6Chapter 6.6
Chapter 6.6sotlsoc
 
Object oriented programming
Object oriented programmingObject oriented programming
Object oriented programmingRenas Rekany
 
Introduction To Csharp
Introduction To CsharpIntroduction To Csharp
Introduction To Csharpsarfarazali
 
Introduction to c#
Introduction to c#Introduction to c#
Introduction to c#singhadarsh
 
Intro to object oriented programming
Intro to object oriented programmingIntro to object oriented programming
Intro to object oriented programmingDavid Giard
 
object oriented programming using java, second sem BCA,UoM
object oriented programming using java, second sem BCA,UoMobject oriented programming using java, second sem BCA,UoM
object oriented programming using java, second sem BCA,UoMambikavenkatesh2
 

Similaire à C# Summer course - Lecture 3 (20)

Java class
Java classJava class
Java class
 
OOPs & Inheritance Notes
OOPs & Inheritance NotesOOPs & Inheritance Notes
OOPs & Inheritance Notes
 
Object oriented programming using c++
Object oriented programming using c++Object oriented programming using c++
Object oriented programming using c++
 
3 functions and class
3   functions and class3   functions and class
3 functions and class
 
C++ classes
C++ classesC++ classes
C++ classes
 
Closer look at classes
Closer look at classesCloser look at classes
Closer look at classes
 
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
 
Mca 2nd sem u-2 classes & objects
Mca 2nd  sem u-2 classes & objectsMca 2nd  sem u-2 classes & objects
Mca 2nd sem u-2 classes & objects
 
Bca 2nd sem u-2 classes & objects
Bca 2nd sem u-2 classes & objectsBca 2nd sem u-2 classes & objects
Bca 2nd sem u-2 classes & objects
 
Constructor in c++
Constructor in c++Constructor in c++
Constructor in c++
 
C# Summer course - Lecture 2
C# Summer course - Lecture 2C# Summer course - Lecture 2
C# Summer course - Lecture 2
 
Chapter 6.6
Chapter 6.6Chapter 6.6
Chapter 6.6
 
Object oriented programming
Object oriented programmingObject oriented programming
Object oriented programming
 
Introduction To Csharp
Introduction To CsharpIntroduction To Csharp
Introduction To Csharp
 
Introduction to c#
Introduction to c#Introduction to c#
Introduction to c#
 
Java Programming - 04 object oriented in java
Java Programming - 04 object oriented in javaJava Programming - 04 object oriented in java
Java Programming - 04 object oriented in java
 
Intro to object oriented programming
Intro to object oriented programmingIntro to object oriented programming
Intro to object oriented programming
 
object oriented programming using java, second sem BCA,UoM
object oriented programming using java, second sem BCA,UoMobject oriented programming using java, second sem BCA,UoM
object oriented programming using java, second sem BCA,UoM
 

Dernier

ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsNanddeep Nachan
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfOverkill Security
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024The Digital Insurer
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 

Dernier (20)

ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 

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