SlideShare a Scribd company logo
Classes Methods and Properties
Introduction to Classes and Objects In object-oriented programming terminology, a  class  is defined as a kind of  programmer-defined type From the natural language definition of the word “class”: Collection of members that share certain attributes and functionality Likewise classes in object-oriented programming In object oriented  programming languages (like C#, Java) classes are used to combine everything  for  a concept  (like date) Data  ( state / attributes )  (e.g.  date day ,  month, year ) Methods (behavior / tasks) (e.g.  display date, increment date )
An Overview of Object Oriented (OO) Programming  An example without OO programming - Calendar display program needs several utility functions/methods  leap year check day of week function … day day of week month MonthName leap year year Data  Functions  . . . Is this structure complex?  for some yes, for some no
An Overview of Object Oriented (OO) Programming OO version - Calendar display program Date concept is developed as a class data and methods combined together from the point of view of programmer Did you like this?  for some yes, for some no OO approach is more suitable for a human being human cognition is mostly based on objects Data  (day, month, year) Methods Day of the week Month name …
Introduction to Classes and Objects We define  variables  of  types  (like int, double). Similarly, we define  objects  of  classes an   object   is a member of a  class Why classes and objects? In other words, why object-oriented programming? It gives programmers the ability to write programs using off-the-shelf components without dealing with the complexity of those components Saves time and effort Objects are how real-world entities are represented. You may design and implement, and later use your own classes, but we will start with using other-programmers-defined classes Examples: we used the  Console  class this is what a programmer generally does
How to Use Classes? The behavior of a class is defined by its  methods  by which objects of that class are manipulated You should know about the methods and what they do name of the method parameters and parameter types return type functionality You don’t need to know how the method is implemented analogy: you can add two int variables using +, but you don’t need to know how computer really adds more analogy: you can drive cars, but you don’t need to know how the fuel injection works
The class  Dice Computer simulated dice not real dice, but have the same functionality random number between 1 and “number of sides”  in this class, we can have dice objects with any number of sides State number of sides roll count Methods Dice(int sides)  // constructor – constructs a die with given number of sides int Roll()  // return the random roll int NumSides()  // how many sides  int NumRolls()  // # of times this die rolled Dice objects will work as pseudo-random number generator  Random   class from .NET library
Using the class  Dice Console.WriteLine("Rolling {0} sided die.",  cube.NumSides()); Console.WriteLine(cube.Roll()); Console.WriteLine(cube.Roll()); Console.WriteLine("Rolled {0}   times.",   cube.NumRolls()); Dice   cube = new Dice(6);   // construct six-sided die Dice   dodeca  = new Dice( 12 ); // construct twelve-sided die   See  UseDice.cs  for full program methods constructor
State and Behavior Behavior  of a class is what a class does described in verbs babies eat, cry dice are rolled In OO programming terminology, behavior is defined by public  methods for  Dice   class, methods are the  Dice   constructor ,  NumRolls() ,  NumSides()   and  Roll() State  of a class depends on physical properties cars have four wheels, different colors dice have a number of sides In OO programming, State is defined by  private  data also called  member data ,  instance variables , or  data fields for Dice class,  mySides  and  myRollCount  (see  Dice.cs )
Objects An  object  is an instance of a class When created, in memory a set of private data members are allocated and initialized according to the constructor  method In other words, each object has a different state However, objects share  method  implementations The same function name is used on all objects of the same class When a me thod  is called on an object, that object’s private data members are accessed and/or modified
Anatomy of the Dice class The class Dice Objects: 6-sided dice, 32-sided dice, one-sided dice Methods:  Roll(),   NumSides(),   NumRolls() A Dice object has state and behavior Each object has its own state, just like each  int  has its own value Number of times rolled, number of sides All objects in a class share method implementations, but access their own state How to respond to  NumRolls() ? Return my own # of rolls
What to know? Client programmer (programmer who uses the classes) needs to know the interface public methods and constructors p arameters,  how they behave does not need to know private data does not need to know how the methods are implemented
From interface to use, the class Dice static void Main(string[] args) { Dice cube = new Dice(6); Dice dodeca = new Dice(12); Console.WriteLine(cube.Roll()); Objects constructed 0 myRollCount my Sides 6 cube 0 myRollCount my Sides 12 dodeca Method invoked 1 myRollCount my Sides 6 cube
Let’s look at the Dice.cs Definition and implementation of the Dice class
Understanding Class Implementations Private data members  are global such that   they  are  accessible  by   all  class member function s e.g. in the implementation of  Roll  function,  mySides  and  myRollCount  are not defined ,  but used
Understanding Class Implementations Constructors  should assign values to each instance variable this is what construction is not a rule, but a  general  programming style All data should be private Provide  propertied or methods  as needed
Random  class Objects of class  Random  can produce random byte, int and double values. Method Next of class Random generates a random int value. The values returned by Next are actually  pseudorandom numbers —a sequence of values produced by a complex mathematical calculation. The calculation uses the current time of day to  seed   the random-number generator.   If you provide Next with two int arguments, it returns a value from the first argument’s value up to, but not including, the second argument’s value. The calculation that produces the pseudorandom numbers  uses the time of day as a  seed   value  to change the sequence’s starting point. You can pass a seed value to the Random object’s  constructor. Given the same seed value, the Random object will produce the same sequence of random numbers.
Access Modifiers class Dice { private  int myRollCount;  // # times die rolled private  int mySides;  // # sides on die public  Dice(int sides) { } public  int Roll() { } } Default is  private . (if there is no access modifier)
Access modifiers public  Methods  and  Constructors  as seen by programmer Programmer can use  the  methods and properties defined in the public section only private Mostly the data part of the class  Necessary for internal implementation of class Not accessible by programmer protected we will see this in inheritance internal Accessible only by methods in the defining assembly protected internal we will see this in inheritance
Member Data (instance variables) class Dice { private  int myRollCount; private  int mySides;  } Will the following code compile? Dice cube = new Dice(6); Console.WriteLine("Number of sides: {0}",  cube. mySides ); How to fix this? Console.WriteLine("Number of sides: {0}",  cube. NumSides ()); Hiding data (encapsulation): why? you can drive cars, but you don’t need to know how the fuel injection works when the car’s fuel injection changes, you can still drive that new car
Properties private  int  myRollCount ;  // # times die rolled // property to get and set the number of sides public  int NumRolls {   get { return myRollCount;   }  // end get set {   myRollCount = value;   }  // end set }  // end property NumRolls Does  get  makes sense? How about  set ?
Properties private  int mySides;  // # sides on die // property to get and set the number of sides public  int NumSides {   get { return mySides;   }  // end get set { mySides = value;   }  // end set }  // end property NumSides Console.WriteLine("Number of sides: {0}", cube. NumSides ); Does  get  makes sense? How about  set ?
Autoimplemented Properties // property to get and set the roll count public int NumRolls  { get; private set; } // property to get and set the number of sides public int NumSides  { get; set; } public Dice(int sides) {   NumRolls = 0;   NumSides = sides; }
Methods The best way to develop and maintain a large application is to construct it from small, simple pieces     divide and conquer Methods allow you to  modularize  an application by separating its tasks into  reusable  units. Reuse the Framework Library, do not reinvent the wheel Divide your application into meaningful methods such that it is easier to debug and maintain. Methods == Worker analogy:
Methods syntax access_modifier   return_type   func_name ( parameter list ) { statement_1; … statement_n; return  return_type; } (type param 1 , type2 param 2 , …, type param n ) public, private Examples: public   int  Roll () public   Dice ( int sides ) public  static  void   Main ( string[] args )
Methods syntax (cont’d) There are three ways to return control to the statement that calls a method . Reaching the end of the method. A return statement without a value. A return statement with a value. There could be more than one return in a method. At least one return is required in a non-void method.
Method Overloading void DoSomething( int num1, int num2 ); void DoSomething( int num1, int num2, int num3 ); void DoSomething( float num1, float num2 ); void DoSomething( double num1, double num2 ); The compiler distinguishes overloaded methods by their  signature —a combination of the method’s name and the number, types and order of its parameters. Method calls cannot be distinguished by return type    compile error int  SquareRoot( int num ); double SquareRoot( int num ); Constructor can be overloaded too.
Scope of Variables The basic scope rules are as follows: The scope of a parameter declaration is the body of the method in which the declaration appears.  The scope of a local-variable declaration is from the point at which the declaration appears to the end of the block containing the declaration.  The scope of a non-static method, property or field of a class is the entire body of the class.  If a local variable or parameter in a method has the same name as a field, the field is hidden until the block terminates Let’s see an example:  scope.cs
Static Methods public class ScopeTest { public  static  void Main(string[] args)   … } public  static  class Math { …   public  static  int Max(int val1, int val2);   public  static  int Min(int val1, int val2); … } You do not need to create an object in memory to use the method, you simply use the class’s name to call the method Other methods of the class cannot be called from a static method, only static methods can be called from other static methods
Math  class example ( maximum3.cs ) Let’s write a program that finds the maximum of 3 numbers Randomly generate the numbers Then let’s use the Math class to find the maximum

More Related Content

PPT
Mca 2nd sem u-2 classes & objects
PPTX
Classes and objects1
PPT
C++ classes tutorials
PPT
C++ classes tutorials
PDF
PDF
Constructors destructors
PPTX
classes and objects in C++
DOCX
Advanced data structures using c++ 3
Mca 2nd sem u-2 classes & objects
Classes and objects1
C++ classes tutorials
C++ classes tutorials
Constructors destructors
classes and objects in C++
Advanced data structures using c++ 3

What's hot (20)

PPTX
Chap2 class,objects
PPTX
Constructor in java
PPTX
Functions, classes & objects in c++
PPT
Java: Objects and Object References
PDF
Lecture 5
PPTX
Classes in c++ (OOP Presentation)
PPTX
14 Defining Classes
PPTX
Classes and objects
PPTX
.NET F# Class constructor
PPTX
Learning C++ - Class 4
PPTX
Objective c slide I
PDF
04. constructor & destructor
PPTX
C++ classes
PDF
CLASSES, STRUCTURE,UNION in C++
PPT
Defining classes-and-objects-1.0
PPT
Basic c#
PDF
Csharp_Chap03
PPT
Swift Programming - Part 2
KEY
Parte II Objective C
PDF
01 objective-c session 1
Chap2 class,objects
Constructor in java
Functions, classes & objects in c++
Java: Objects and Object References
Lecture 5
Classes in c++ (OOP Presentation)
14 Defining Classes
Classes and objects
.NET F# Class constructor
Learning C++ - Class 4
Objective c slide I
04. constructor & destructor
C++ classes
CLASSES, STRUCTURE,UNION in C++
Defining classes-and-objects-1.0
Basic c#
Csharp_Chap03
Swift Programming - Part 2
Parte II Objective C
01 objective-c session 1
Ad

Viewers also liked (8)

PPT
Chapter 01 - Overview
PPT
Net Security Basic
PPT
Security Policies
PPT
Book storeonline it-slideshares.blogspot.com
PPT
Report password cracking (2)
PPT
Java Symmetric
PPTX
Xml For Dummies Chapter 12 Handling Transformations With Xsl it-slideshares...
PPTX
Xml For Dummies Chapter 15 Using Xml With Web Servicesit-slideshares.blogsp...
Chapter 01 - Overview
Net Security Basic
Security Policies
Book storeonline it-slideshares.blogspot.com
Report password cracking (2)
Java Symmetric
Xml For Dummies Chapter 12 Handling Transformations With Xsl it-slideshares...
Xml For Dummies Chapter 15 Using Xml With Web Servicesit-slideshares.blogsp...
Ad

Similar to Classes1 (20)

PPTX
11. Objects and Classes
PDF
C# Summer course - Lecture 3
PPTX
Chapter 4 Writing Classes
PPT
Visula C# Programming Lecture 6
PPTX
Java Chapter 04 - Writing Classes: part 2
PPTX
CSharp presentation and software developement
PPT
Object Oriented Programming In .Net
DOC
C# by Zaheer Abbas Aghani
DOC
C# by Zaheer Abbas Aghani
PPTX
PPTX
Object-oriented programming
PDF
1204csharp
PDF
C sharp chap5
PPTX
Intro to object oriented programming
PPTX
03 classes interfaces_principlesofoop
PPT
14. Defining Classes
PDF
Constructors and Method Overloading
DOCX
Question and answer Programming
PPTX
C# classes objects
DOC
Object oriented programming
11. Objects and Classes
C# Summer course - Lecture 3
Chapter 4 Writing Classes
Visula C# Programming Lecture 6
Java Chapter 04 - Writing Classes: part 2
CSharp presentation and software developement
Object Oriented Programming In .Net
C# by Zaheer Abbas Aghani
C# by Zaheer Abbas Aghani
Object-oriented programming
1204csharp
C sharp chap5
Intro to object oriented programming
03 classes interfaces_principlesofoop
14. Defining Classes
Constructors and Method Overloading
Question and answer Programming
C# classes objects
Object oriented programming

More from phanleson (20)

PDF
Learning spark ch01 - Introduction to Data Analysis with Spark
PPT
Firewall - Network Defense in Depth Firewalls
PPT
Mobile Security - Wireless hacking
PPT
Authentication in wireless - Security in Wireless Protocols
PPT
E-Commerce Security - Application attacks - Server Attacks
PPT
Hacking web applications
PPTX
HBase In Action - Chapter 04: HBase table design
PPT
HBase In Action - Chapter 10 - Operations
PPT
Hbase in action - Chapter 09: Deploying HBase
PPTX
Learning spark ch11 - Machine Learning with MLlib
PPTX
Learning spark ch10 - Spark Streaming
PPTX
Learning spark ch09 - Spark SQL
PPT
Learning spark ch07 - Running on a Cluster
PPTX
Learning spark ch06 - Advanced Spark Programming
PPTX
Learning spark ch05 - Loading and Saving Your Data
PPTX
Learning spark ch04 - Working with Key/Value Pairs
PPTX
Learning spark ch01 - Introduction to Data Analysis with Spark
PPT
Hướng Dẫn Đăng Ký LibertaGia - A guide and introduciton about Libertagia
PPT
Lecture 1 - Getting to know XML
PPTX
Lecture 4 - Adding XTHML for the Web
Learning spark ch01 - Introduction to Data Analysis with Spark
Firewall - Network Defense in Depth Firewalls
Mobile Security - Wireless hacking
Authentication in wireless - Security in Wireless Protocols
E-Commerce Security - Application attacks - Server Attacks
Hacking web applications
HBase In Action - Chapter 04: HBase table design
HBase In Action - Chapter 10 - Operations
Hbase in action - Chapter 09: Deploying HBase
Learning spark ch11 - Machine Learning with MLlib
Learning spark ch10 - Spark Streaming
Learning spark ch09 - Spark SQL
Learning spark ch07 - Running on a Cluster
Learning spark ch06 - Advanced Spark Programming
Learning spark ch05 - Loading and Saving Your Data
Learning spark ch04 - Working with Key/Value Pairs
Learning spark ch01 - Introduction to Data Analysis with Spark
Hướng Dẫn Đăng Ký LibertaGia - A guide and introduciton about Libertagia
Lecture 1 - Getting to know XML
Lecture 4 - Adding XTHML for the Web

Recently uploaded (20)

PDF
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PPTX
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
KodekX | Application Modernization Development
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
Spectral efficient network and resource selection model in 5G networks
PPTX
MYSQL Presentation for SQL database connectivity
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PPTX
Cloud computing and distributed systems.
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
cuic standard and advanced reporting.pdf
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
The Rise and Fall of 3GPP – Time for a Sabbatical?
Chapter 3 Spatial Domain Image Processing.pdf
Per capita expenditure prediction using model stacking based on satellite ima...
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
Reach Out and Touch Someone: Haptics and Empathic Computing
KodekX | Application Modernization Development
Dropbox Q2 2025 Financial Results & Investor Presentation
Spectral efficient network and resource selection model in 5G networks
MYSQL Presentation for SQL database connectivity
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
NewMind AI Weekly Chronicles - August'25 Week I
“AI and Expert System Decision Support & Business Intelligence Systems”
Cloud computing and distributed systems.
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Advanced methodologies resolving dimensionality complications for autism neur...
cuic standard and advanced reporting.pdf

Classes1

  • 1. Classes Methods and Properties
  • 2. Introduction to Classes and Objects In object-oriented programming terminology, a class is defined as a kind of programmer-defined type From the natural language definition of the word “class”: Collection of members that share certain attributes and functionality Likewise classes in object-oriented programming In object oriented programming languages (like C#, Java) classes are used to combine everything for a concept (like date) Data ( state / attributes ) (e.g. date day , month, year ) Methods (behavior / tasks) (e.g. display date, increment date )
  • 3. An Overview of Object Oriented (OO) Programming An example without OO programming - Calendar display program needs several utility functions/methods leap year check day of week function … day day of week month MonthName leap year year Data Functions . . . Is this structure complex? for some yes, for some no
  • 4. An Overview of Object Oriented (OO) Programming OO version - Calendar display program Date concept is developed as a class data and methods combined together from the point of view of programmer Did you like this? for some yes, for some no OO approach is more suitable for a human being human cognition is mostly based on objects Data (day, month, year) Methods Day of the week Month name …
  • 5. Introduction to Classes and Objects We define variables of types (like int, double). Similarly, we define objects of classes an object is a member of a class Why classes and objects? In other words, why object-oriented programming? It gives programmers the ability to write programs using off-the-shelf components without dealing with the complexity of those components Saves time and effort Objects are how real-world entities are represented. You may design and implement, and later use your own classes, but we will start with using other-programmers-defined classes Examples: we used the Console class this is what a programmer generally does
  • 6. How to Use Classes? The behavior of a class is defined by its methods by which objects of that class are manipulated You should know about the methods and what they do name of the method parameters and parameter types return type functionality You don’t need to know how the method is implemented analogy: you can add two int variables using +, but you don’t need to know how computer really adds more analogy: you can drive cars, but you don’t need to know how the fuel injection works
  • 7. The class Dice Computer simulated dice not real dice, but have the same functionality random number between 1 and “number of sides” in this class, we can have dice objects with any number of sides State number of sides roll count Methods Dice(int sides) // constructor – constructs a die with given number of sides int Roll() // return the random roll int NumSides() // how many sides int NumRolls() // # of times this die rolled Dice objects will work as pseudo-random number generator Random class from .NET library
  • 8. Using the class Dice Console.WriteLine("Rolling {0} sided die.", cube.NumSides()); Console.WriteLine(cube.Roll()); Console.WriteLine(cube.Roll()); Console.WriteLine("Rolled {0} times.", cube.NumRolls()); Dice cube = new Dice(6); // construct six-sided die Dice dodeca = new Dice( 12 ); // construct twelve-sided die See UseDice.cs for full program methods constructor
  • 9. State and Behavior Behavior of a class is what a class does described in verbs babies eat, cry dice are rolled In OO programming terminology, behavior is defined by public methods for Dice class, methods are the Dice constructor , NumRolls() , NumSides() and Roll() State of a class depends on physical properties cars have four wheels, different colors dice have a number of sides In OO programming, State is defined by private data also called member data , instance variables , or data fields for Dice class, mySides and myRollCount (see Dice.cs )
  • 10. Objects An object is an instance of a class When created, in memory a set of private data members are allocated and initialized according to the constructor method In other words, each object has a different state However, objects share method implementations The same function name is used on all objects of the same class When a me thod is called on an object, that object’s private data members are accessed and/or modified
  • 11. Anatomy of the Dice class The class Dice Objects: 6-sided dice, 32-sided dice, one-sided dice Methods: Roll(), NumSides(), NumRolls() A Dice object has state and behavior Each object has its own state, just like each int has its own value Number of times rolled, number of sides All objects in a class share method implementations, but access their own state How to respond to NumRolls() ? Return my own # of rolls
  • 12. What to know? Client programmer (programmer who uses the classes) needs to know the interface public methods and constructors p arameters, how they behave does not need to know private data does not need to know how the methods are implemented
  • 13. From interface to use, the class Dice static void Main(string[] args) { Dice cube = new Dice(6); Dice dodeca = new Dice(12); Console.WriteLine(cube.Roll()); Objects constructed 0 myRollCount my Sides 6 cube 0 myRollCount my Sides 12 dodeca Method invoked 1 myRollCount my Sides 6 cube
  • 14. Let’s look at the Dice.cs Definition and implementation of the Dice class
  • 15. Understanding Class Implementations Private data members are global such that they are accessible by all class member function s e.g. in the implementation of Roll function, mySides and myRollCount are not defined , but used
  • 16. Understanding Class Implementations Constructors should assign values to each instance variable this is what construction is not a rule, but a general programming style All data should be private Provide propertied or methods as needed
  • 17. Random class Objects of class Random can produce random byte, int and double values. Method Next of class Random generates a random int value. The values returned by Next are actually pseudorandom numbers —a sequence of values produced by a complex mathematical calculation. The calculation uses the current time of day to seed the random-number generator. If you provide Next with two int arguments, it returns a value from the first argument’s value up to, but not including, the second argument’s value. The calculation that produces the pseudorandom numbers uses the time of day as a seed value to change the sequence’s starting point. You can pass a seed value to the Random object’s constructor. Given the same seed value, the Random object will produce the same sequence of random numbers.
  • 18. Access Modifiers class Dice { private int myRollCount; // # times die rolled private int mySides; // # sides on die public Dice(int sides) { } public int Roll() { } } Default is private . (if there is no access modifier)
  • 19. Access modifiers public Methods and Constructors as seen by programmer Programmer can use the methods and properties defined in the public section only private Mostly the data part of the class Necessary for internal implementation of class Not accessible by programmer protected we will see this in inheritance internal Accessible only by methods in the defining assembly protected internal we will see this in inheritance
  • 20. Member Data (instance variables) class Dice { private int myRollCount; private int mySides; } Will the following code compile? Dice cube = new Dice(6); Console.WriteLine("Number of sides: {0}", cube. mySides ); How to fix this? Console.WriteLine("Number of sides: {0}", cube. NumSides ()); Hiding data (encapsulation): why? you can drive cars, but you don’t need to know how the fuel injection works when the car’s fuel injection changes, you can still drive that new car
  • 21. Properties private int myRollCount ; // # times die rolled // property to get and set the number of sides public int NumRolls { get { return myRollCount; } // end get set { myRollCount = value; } // end set } // end property NumRolls Does get makes sense? How about set ?
  • 22. Properties private int mySides; // # sides on die // property to get and set the number of sides public int NumSides { get { return mySides; } // end get set { mySides = value; } // end set } // end property NumSides Console.WriteLine("Number of sides: {0}", cube. NumSides ); Does get makes sense? How about set ?
  • 23. Autoimplemented Properties // property to get and set the roll count public int NumRolls { get; private set; } // property to get and set the number of sides public int NumSides { get; set; } public Dice(int sides) { NumRolls = 0; NumSides = sides; }
  • 24. Methods The best way to develop and maintain a large application is to construct it from small, simple pieces  divide and conquer Methods allow you to modularize an application by separating its tasks into reusable units. Reuse the Framework Library, do not reinvent the wheel Divide your application into meaningful methods such that it is easier to debug and maintain. Methods == Worker analogy:
  • 25. Methods syntax access_modifier return_type func_name ( parameter list ) { statement_1; … statement_n; return return_type; } (type param 1 , type2 param 2 , …, type param n ) public, private Examples: public int Roll () public Dice ( int sides ) public static void Main ( string[] args )
  • 26. Methods syntax (cont’d) There are three ways to return control to the statement that calls a method . Reaching the end of the method. A return statement without a value. A return statement with a value. There could be more than one return in a method. At least one return is required in a non-void method.
  • 27. Method Overloading void DoSomething( int num1, int num2 ); void DoSomething( int num1, int num2, int num3 ); void DoSomething( float num1, float num2 ); void DoSomething( double num1, double num2 ); The compiler distinguishes overloaded methods by their signature —a combination of the method’s name and the number, types and order of its parameters. Method calls cannot be distinguished by return type  compile error int SquareRoot( int num ); double SquareRoot( int num ); Constructor can be overloaded too.
  • 28. Scope of Variables The basic scope rules are as follows: The scope of a parameter declaration is the body of the method in which the declaration appears. The scope of a local-variable declaration is from the point at which the declaration appears to the end of the block containing the declaration. The scope of a non-static method, property or field of a class is the entire body of the class. If a local variable or parameter in a method has the same name as a field, the field is hidden until the block terminates Let’s see an example: scope.cs
  • 29. Static Methods public class ScopeTest { public static void Main(string[] args) … } public static class Math { … public static int Max(int val1, int val2); public static int Min(int val1, int val2); … } You do not need to create an object in memory to use the method, you simply use the class’s name to call the method Other methods of the class cannot be called from a static method, only static methods can be called from other static methods
  • 30. Math class example ( maximum3.cs ) Let’s write a program that finds the maximum of 3 numbers Randomly generate the numbers Then let’s use the Math class to find the maximum