SlideShare a Scribd company logo
1 of 27
Methods
Writing and using methods,
overloads, ref, out
SoftUni Team
Technical Trainers
Software University
http://softuni.bg
Table of Contents
1. Using Methods
 What is a Method? Why Use Methods?
 Declaring and Creating Methods
 Calling Methods
2. Methods with Parameters
 Passing Parameters
 Returning Values
3. Best Practices
2
Methods
Declaring and Invoking Methods
 A method is a named piece of code
 Each method has:
Declaring Methods
static void PrintHyphens(int count)
{
Console.WriteLine(
new string('-', count));
}
NameReturn type Parameters
Body
5
 Methods can be invoked (called) by their name
Invoking Methods
static void PrintHyphens(int count)
{
Console.WriteLine(new string('-', count));
}
static void Main()
{
for (int i = 1; i <= 10; i++)
{
PrintHyphens(i);
}
}
Method body always
surrounded by { }
Method called by name
Methods
Live Demo
7
 Method parameters can be of any type
 Separated by comma
Method Parameters
static void PrintNumbers(int start, int end)
{
for (int i = start; i <= end; i++)
{
Console.Write("{0} ", i);
}
}
static void Main()
{
PrintNumbers(5, 10);
}
Declares the use of
int start and int end
Passed concrete values
when called
Method Parameters – Example
8
static void PrintSign(int number)
{
if (number > 0)
Console.WriteLine("The number {0} is positive.", number);
else if (number < 0)
Console.WriteLine("The number {0} is negative.", number);
else
Console.WriteLine("The number {0} is zero.", number);
}
static void Main()
{
PrintSign(5);
PrintSign(-3);
PrintSign(0);
}
 C# 4.0 supports optional parameters with default values:
 The above method can be called in several ways:
Optional Parameters
static void PrintNumbers(int start = 0, int end = 100)
{
for (int i = start; i <= end; i++)
{
Console.Write("{0} ", i);
}
}
PrintNumbers(5, 10);
PrintNumbers(15);
PrintNumbers();
PrintNumbers(end: 40, start: 35);
Method Parameters
Live Demo
Exercises in Class
Printing Triangle
 Create a method for printing triangles as shown below:
12
1
1 1 2
1 2 1 2 3
1 2 3 1 2 3 4
1 2 3 4 1 2 3 4 5
n=5  1 2 3 4 5 n=6  1 2 3 4 5 6
1 2 3 4 1 2 3 4 5
1 2 3 1 2 3 4
1 2 1 2 3
1 1 2
1
Returning Values From
Methods
15
 Type void - does not return a value (only executes code)
 Other types - return values, based on the return type of the method
Method Return Types
static void AddOne(int n)
{
n += 1;
Console.WriteLine(n);
}
static int PlusOne(int n)
{
return n + 1;
}
16
Methods with Parameters and Return Value
static double CalcTriangleArea(double width, double height)
{
return width * height / 2;
}
static void Main()
{
Console.Write("Enter triangle width: ");
double width = double.Parse(Console.ReadLine());
Console.Write("Enter triangle height: ");
double height = double.Parse(Console.ReadLine());
Console.WriteLine(CalcTriangleArea(width, height));
}
17
Power Method
static double Power(double number, int power)
{
double result = 1;
for (int i = 0; i < power; i++)
{
result *= number;
}
return result;
}
static void Main()
{
double powerTwo = Power(5, 2);
Console.WriteLine(powerTwo);
double powerThree = Power(7.45, 3);
Console.WriteLine(powerThree);
}
18
 Convert temperature from Fahrenheit to Celsius:
Temperature Conversion – Example
static double FahrenheitToCelsius(double degrees)
{
double celsius = (degrees - 32) * 5 / 9;
return celsius;
}
static void Main()
{
Console.Write("Temperature in Fahrenheit: ");
double t = Double.Parse(Console.ReadLine());
t = FahrenheitToCelsius(t);
Console.Write("Temperature in Celsius: {0}", t);
}
Returning Values From
Methods
Live Demo
Overloading Methods
Multiple Methods
with the Same Name
21
 Method Overloading
 Use the same method name for multiple methods with different
signature (return type and parameters)
Overloading Methods
static void Print(string text)
{
Console.WriteLine(text);
}
static void Print(int number)
{
Console.WriteLine(number);
}
static void Print(string text, int number)
{
Console.WriteLine(text + ' ' + number);
}
Why Use Methods?
 More manageable programming
 Splits large problems into small pieces
 Better organization of the program
 Improves code readability
 Improves code understandability
 Avoiding repeating code
 Improves code maintainability
 Code reusability
 Using existing methods several times
22
23
 Each method should perform a single, well-defined task
 Method's name should describe that task in a clear and non-
ambiguous way
 Good examples: CalculatePrice, ReadName
 Bad examples: f, g1, Process
 In C# methods should start with a capital letter (PascalCase)
 Avoid methods longer than one screen
 Split them to several shorter methods
Methods – Best Practices
24
 Break large programs into simple
methods that solve small sub-problems
 Methods consist of declaration and body
 Methods are invoked by their name
 Methods can accept parameters
 Parameters take actual values when calling a method
 Methods can return a value or nothing (void)
Summary
?
Fundamentals Level @ SoftUni
http://softuni.bg/courses/advanced-csharp
License
 This course (slides, examples, demos, videos, homework, etc.)
is licensed under the "Creative Commons Attribution-
NonCommercial-ShareAlike 4.0 International" license
 Attribution: this work may contain portions from
 "C# Fundamentals – Part 1" course by Telerik Academy under CC-BY-NC-SA license
 "C# Fundamentals – Part 2" course by Telerik Academy under CC-BY-NC-SA license
26
Free Trainings @ Software University
 Software University Foundation – softuni.org
 Software University – High-Quality Education,
Profession and Job for Software Developers
 softuni.bg
 Software University @ Facebook
 facebook.com/SoftwareUniversity
 Software University @ YouTube
 youtube.com/SoftwareUniversity
 Software University Forums – forum.softuni.bg

More Related Content

What's hot

02. Primitive Data Types and Variables
02. Primitive Data Types and Variables02. Primitive Data Types and Variables
02. Primitive Data Types and VariablesIntro C# Book
 
03. Operators Expressions and statements
03. Operators Expressions and statements03. Operators Expressions and statements
03. Operators Expressions and statementsIntro C# Book
 
02. Data Types and variables
02. Data Types and variables02. Data Types and variables
02. Data Types and variablesIntro C# Book
 
13. Java text processing
13.  Java text processing13.  Java text processing
13. Java text processingIntro C# Book
 
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
 
19. Data Structures and Algorithm Complexity
19. Data Structures and Algorithm Complexity19. Data Structures and Algorithm Complexity
19. Data Structures and Algorithm ComplexityIntro C# Book
 
Java Tutorial: Part 1. Getting Started
Java Tutorial: Part 1. Getting StartedJava Tutorial: Part 1. Getting Started
Java Tutorial: Part 1. Getting StartedSvetlin Nakov
 
05. Java Loops Methods and Classes
05. Java Loops Methods and Classes05. Java Loops Methods and Classes
05. Java Loops Methods and ClassesIntro C# Book
 
20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction20.4 Java interfaces and abstraction
20.4 Java interfaces and abstractionIntro C# Book
 
Java Foundations: Basic Syntax, Conditions, Loops
Java Foundations: Basic Syntax, Conditions, LoopsJava Foundations: Basic Syntax, Conditions, Loops
Java Foundations: Basic Syntax, Conditions, LoopsSvetlin Nakov
 
Python programming workshop session 2
Python programming workshop session 2Python programming workshop session 2
Python programming workshop session 2Abdul Haseeb
 
15. Streams Files and Directories
15. Streams Files and Directories 15. Streams Files and Directories
15. Streams Files and Directories Intro C# Book
 
conditional statements
conditional statementsconditional statements
conditional statementsJames Brotsos
 
Ch02 primitive-data-definite-loops
Ch02 primitive-data-definite-loopsCh02 primitive-data-definite-loops
Ch02 primitive-data-definite-loopsJames Brotsos
 
Java basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini indiaJava basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini indiaSanjeev Tripathi
 
Java Foundations: Strings and Text Processing
Java Foundations: Strings and Text ProcessingJava Foundations: Strings and Text Processing
Java Foundations: Strings and Text ProcessingSvetlin Nakov
 

What's hot (20)

02. Primitive Data Types and Variables
02. Primitive Data Types and Variables02. Primitive Data Types and Variables
02. Primitive Data Types and Variables
 
03. Operators Expressions and statements
03. Operators Expressions and statements03. Operators Expressions and statements
03. Operators Expressions and statements
 
06.Loops
06.Loops06.Loops
06.Loops
 
02. Data Types and variables
02. Data Types and variables02. Data Types and variables
02. Data Types and variables
 
13. Java text processing
13.  Java text processing13.  Java text processing
13. Java text processing
 
20.1 Java working with abstraction
20.1 Java working with abstraction20.1 Java working with abstraction
20.1 Java working with abstraction
 
19. Data Structures and Algorithm Complexity
19. Data Structures and Algorithm Complexity19. Data Structures and Algorithm Complexity
19. Data Structures and Algorithm Complexity
 
Java Tutorial: Part 1. Getting Started
Java Tutorial: Part 1. Getting StartedJava Tutorial: Part 1. Getting Started
Java Tutorial: Part 1. Getting Started
 
05. Java Loops Methods and Classes
05. Java Loops Methods and Classes05. Java Loops Methods and Classes
05. Java Loops Methods and Classes
 
07. Arrays
07. Arrays07. Arrays
07. Arrays
 
20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction
 
Java Foundations: Basic Syntax, Conditions, Loops
Java Foundations: Basic Syntax, Conditions, LoopsJava Foundations: Basic Syntax, Conditions, Loops
Java Foundations: Basic Syntax, Conditions, Loops
 
Python programming workshop session 2
Python programming workshop session 2Python programming workshop session 2
Python programming workshop session 2
 
15. Streams Files and Directories
15. Streams Files and Directories 15. Streams Files and Directories
15. Streams Files and Directories
 
conditional statements
conditional statementsconditional statements
conditional statements
 
Ch02 primitive-data-definite-loops
Ch02 primitive-data-definite-loopsCh02 primitive-data-definite-loops
Ch02 primitive-data-definite-loops
 
Java basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini indiaJava basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini india
 
Java Foundations: Strings and Text Processing
Java Foundations: Strings and Text ProcessingJava Foundations: Strings and Text Processing
Java Foundations: Strings and Text Processing
 
C++ Language
C++ LanguageC++ Language
C++ Language
 
Parameters
ParametersParameters
Parameters
 

Similar to 09. Methods

Similar to 09. Methods (20)

Java Foundations: Methods
Java Foundations: MethodsJava Foundations: Methods
Java Foundations: Methods
 
Methods intro-1.0
Methods intro-1.0Methods intro-1.0
Methods intro-1.0
 
09 Methods
09 Methods09 Methods
09 Methods
 
Csphtp1 06
Csphtp1 06Csphtp1 06
Csphtp1 06
 
Java method present by showrov ahamed
Java method present by showrov ahamedJava method present by showrov ahamed
Java method present by showrov ahamed
 
14method in c#
14method in c#14method in c#
14method in c#
 
Lecture 5
Lecture 5Lecture 5
Lecture 5
 
Methods in Java
Methods in JavaMethods in Java
Methods in Java
 
Class 10
Class 10Class 10
Class 10
 
Xamarin: C# Methods
Xamarin: C# MethodsXamarin: C# Methods
Xamarin: C# Methods
 
Module 4 : methods & parameters
Module 4 : methods & parametersModule 4 : methods & parameters
Module 4 : methods & parameters
 
static methods
static methodsstatic methods
static methods
 
06 procedures
06 procedures06 procedures
06 procedures
 
CIS110 Computer Programming Design Chapter (9)
CIS110 Computer Programming Design Chapter  (9)CIS110 Computer Programming Design Chapter  (9)
CIS110 Computer Programming Design Chapter (9)
 
Intro to Programming: Modularity
Intro to Programming: ModularityIntro to Programming: Modularity
Intro to Programming: Modularity
 
import java.util.Scanner;Henry Cutler ID 1234 7202.docx
import java.util.Scanner;Henry Cutler ID 1234  7202.docximport java.util.Scanner;Henry Cutler ID 1234  7202.docx
import java.util.Scanner;Henry Cutler ID 1234 7202.docx
 
Methods.ppt
Methods.pptMethods.ppt
Methods.ppt
 
Visual Basic 6.0
Visual Basic 6.0Visual Basic 6.0
Visual Basic 6.0
 
06slide.ppt
06slide.ppt06slide.ppt
06slide.ppt
 
Methods In C-Sharp (C#)
Methods In C-Sharp (C#)Methods In C-Sharp (C#)
Methods In C-Sharp (C#)
 

More from Intro C# Book

17. Java data structures trees representation and traversal
17. Java data structures trees representation and traversal17. Java data structures trees representation and traversal
17. Java data structures trees representation and traversalIntro C# Book
 
Java Problem solving
Java Problem solving Java Problem solving
Java Problem solving Intro C# Book
 
21. Java High Quality Programming Code
21. Java High Quality Programming Code21. Java High Quality Programming Code
21. Java High Quality Programming CodeIntro C# Book
 
20.5 Java polymorphism
20.5 Java polymorphism 20.5 Java polymorphism
20.5 Java polymorphism Intro C# Book
 
20.3 Java encapsulation
20.3 Java encapsulation20.3 Java encapsulation
20.3 Java encapsulationIntro C# Book
 
20.2 Java inheritance
20.2 Java inheritance20.2 Java inheritance
20.2 Java inheritanceIntro C# Book
 
19. Java data structures algorithms and complexity
19. Java data structures algorithms and complexity19. Java data structures algorithms and complexity
19. Java data structures algorithms and complexityIntro C# Book
 
18. Java associative arrays
18. Java associative arrays18. Java associative arrays
18. Java associative arraysIntro C# Book
 
16. Java stacks and queues
16. Java stacks and queues16. Java stacks and queues
16. Java stacks and queuesIntro C# Book
 
14. Java defining classes
14. Java defining classes14. Java defining classes
14. Java defining classesIntro C# Book
 
12. Java Exceptions and error handling
12. Java Exceptions and error handling12. Java Exceptions and error handling
12. Java Exceptions and error handlingIntro C# Book
 
11. Java Objects and classes
11. Java  Objects and classes11. Java  Objects and classes
11. Java Objects and classesIntro C# Book
 
07. Java Array, Set and Maps
07.  Java Array, Set and Maps07.  Java Array, Set and Maps
07. Java Array, Set and MapsIntro C# Book
 
01. Introduction to programming with java
01. Introduction to programming with java01. Introduction to programming with java
01. Introduction to programming with javaIntro C# Book
 
23. Methodology of Problem Solving
23. Methodology of Problem Solving23. Methodology of Problem Solving
23. Methodology of Problem SolvingIntro C# Book
 
21. High-Quality Programming Code
21. High-Quality Programming Code21. High-Quality Programming Code
21. High-Quality Programming CodeIntro C# Book
 
18. Dictionaries, Hash-Tables and Set
18. Dictionaries, Hash-Tables and Set18. Dictionaries, Hash-Tables and Set
18. Dictionaries, Hash-Tables and SetIntro C# Book
 
16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks Queues16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks QueuesIntro C# Book
 
17. Trees and Tree Like Structures
17. Trees and Tree Like Structures17. Trees and Tree Like Structures
17. Trees and Tree Like StructuresIntro C# Book
 

More from Intro C# Book (20)

17. Java data structures trees representation and traversal
17. Java data structures trees representation and traversal17. Java data structures trees representation and traversal
17. Java data structures trees representation and traversal
 
Java Problem solving
Java Problem solving Java Problem solving
Java Problem solving
 
21. Java High Quality Programming Code
21. Java High Quality Programming Code21. Java High Quality Programming Code
21. Java High Quality Programming Code
 
20.5 Java polymorphism
20.5 Java polymorphism 20.5 Java polymorphism
20.5 Java polymorphism
 
20.3 Java encapsulation
20.3 Java encapsulation20.3 Java encapsulation
20.3 Java encapsulation
 
20.2 Java inheritance
20.2 Java inheritance20.2 Java inheritance
20.2 Java inheritance
 
19. Java data structures algorithms and complexity
19. Java data structures algorithms and complexity19. Java data structures algorithms and complexity
19. Java data structures algorithms and complexity
 
18. Java associative arrays
18. Java associative arrays18. Java associative arrays
18. Java associative arrays
 
16. Java stacks and queues
16. Java stacks and queues16. Java stacks and queues
16. Java stacks and queues
 
14. Java defining classes
14. Java defining classes14. Java defining classes
14. Java defining classes
 
12. Java Exceptions and error handling
12. Java Exceptions and error handling12. Java Exceptions and error handling
12. Java Exceptions and error handling
 
11. Java Objects and classes
11. Java  Objects and classes11. Java  Objects and classes
11. Java Objects and classes
 
07. Java Array, Set and Maps
07.  Java Array, Set and Maps07.  Java Array, Set and Maps
07. Java Array, Set and Maps
 
01. Introduction to programming with java
01. Introduction to programming with java01. Introduction to programming with java
01. Introduction to programming with java
 
23. Methodology of Problem Solving
23. Methodology of Problem Solving23. Methodology of Problem Solving
23. Methodology of Problem Solving
 
21. High-Quality Programming Code
21. High-Quality Programming Code21. High-Quality Programming Code
21. High-Quality Programming Code
 
18. Dictionaries, Hash-Tables and Set
18. Dictionaries, Hash-Tables and Set18. Dictionaries, Hash-Tables and Set
18. Dictionaries, Hash-Tables and Set
 
16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks Queues16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks Queues
 
17. Trees and Tree Like Structures
17. Trees and Tree Like Structures17. Trees and Tree Like Structures
17. Trees and Tree Like Structures
 
14 Defining Classes
14 Defining Classes14 Defining Classes
14 Defining Classes
 

Recently uploaded

Best VIP Call Girls Noida Sector 75 Call Me: 8448380779
Best VIP Call Girls Noida Sector 75 Call Me: 8448380779Best VIP Call Girls Noida Sector 75 Call Me: 8448380779
Best VIP Call Girls Noida Sector 75 Call Me: 8448380779Delhi Call girls
 
Call Girls in Mayur Vihar ✔️ 9711199171 ✔️ Delhi ✔️ Enjoy Call Girls With Our...
Call Girls in Mayur Vihar ✔️ 9711199171 ✔️ Delhi ✔️ Enjoy Call Girls With Our...Call Girls in Mayur Vihar ✔️ 9711199171 ✔️ Delhi ✔️ Enjoy Call Girls With Our...
Call Girls in Mayur Vihar ✔️ 9711199171 ✔️ Delhi ✔️ Enjoy Call Girls With Our...sonatiwari757
 
Challengers I Told Ya ShirtChallengers I Told Ya Shirt
Challengers I Told Ya ShirtChallengers I Told Ya ShirtChallengers I Told Ya ShirtChallengers I Told Ya Shirt
Challengers I Told Ya ShirtChallengers I Told Ya Shirtrahman018755
 
Radiant Call girls in Dubai O56338O268 Dubai Call girls
Radiant Call girls in Dubai O56338O268 Dubai Call girlsRadiant Call girls in Dubai O56338O268 Dubai Call girls
Radiant Call girls in Dubai O56338O268 Dubai Call girlsstephieert
 
Call Girls In Model Towh Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Model Towh Delhi 💯Call Us 🔝8264348440🔝Call Girls In Model Towh Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Model Towh Delhi 💯Call Us 🔝8264348440🔝soniya singh
 
Hot Call Girls |Delhi |Hauz Khas ☎ 9711199171 Book Your One night Stand
Hot Call Girls |Delhi |Hauz Khas ☎ 9711199171 Book Your One night StandHot Call Girls |Delhi |Hauz Khas ☎ 9711199171 Book Your One night Stand
Hot Call Girls |Delhi |Hauz Khas ☎ 9711199171 Book Your One night Standkumarajju5765
 
FULL ENJOY Call Girls In Mayur Vihar Delhi Contact Us 8377087607
FULL ENJOY Call Girls In Mayur Vihar Delhi Contact Us 8377087607FULL ENJOY Call Girls In Mayur Vihar Delhi Contact Us 8377087607
FULL ENJOY Call Girls In Mayur Vihar Delhi Contact Us 8377087607dollysharma2066
 
Chennai Call Girls Porur Phone 🍆 8250192130 👅 celebrity escorts service
Chennai Call Girls Porur Phone 🍆 8250192130 👅 celebrity escorts serviceChennai Call Girls Porur Phone 🍆 8250192130 👅 celebrity escorts service
Chennai Call Girls Porur Phone 🍆 8250192130 👅 celebrity escorts servicesonalikaur4
 
VIP 7001035870 Find & Meet Hyderabad Call Girls LB Nagar high-profile Call Girl
VIP 7001035870 Find & Meet Hyderabad Call Girls LB Nagar high-profile Call GirlVIP 7001035870 Find & Meet Hyderabad Call Girls LB Nagar high-profile Call Girl
VIP 7001035870 Find & Meet Hyderabad Call Girls LB Nagar high-profile Call Girladitipandeya
 
GDG Cloud Southlake 32: Kyle Hettinger: Demystifying the Dark Web
GDG Cloud Southlake 32: Kyle Hettinger: Demystifying the Dark WebGDG Cloud Southlake 32: Kyle Hettinger: Demystifying the Dark Web
GDG Cloud Southlake 32: Kyle Hettinger: Demystifying the Dark WebJames Anderson
 
'Future Evolution of the Internet' delivered by Geoff Huston at Everything Op...
'Future Evolution of the Internet' delivered by Geoff Huston at Everything Op...'Future Evolution of the Internet' delivered by Geoff Huston at Everything Op...
'Future Evolution of the Internet' delivered by Geoff Huston at Everything Op...APNIC
 
✂️ 👅 Independent Andheri Escorts With Room Vashi Call Girls 💃 9004004663
✂️ 👅 Independent Andheri Escorts With Room Vashi Call Girls 💃 9004004663✂️ 👅 Independent Andheri Escorts With Room Vashi Call Girls 💃 9004004663
✂️ 👅 Independent Andheri Escorts With Room Vashi Call Girls 💃 9004004663Call Girls Mumbai
 
VIP 7001035870 Find & Meet Hyderabad Call Girls Dilsukhnagar high-profile Cal...
VIP 7001035870 Find & Meet Hyderabad Call Girls Dilsukhnagar high-profile Cal...VIP 7001035870 Find & Meet Hyderabad Call Girls Dilsukhnagar high-profile Cal...
VIP 7001035870 Find & Meet Hyderabad Call Girls Dilsukhnagar high-profile Cal...aditipandeya
 
10.pdfMature Call girls in Dubai +971563133746 Dubai Call girls
10.pdfMature Call girls in Dubai +971563133746 Dubai Call girls10.pdfMature Call girls in Dubai +971563133746 Dubai Call girls
10.pdfMature Call girls in Dubai +971563133746 Dubai Call girlsstephieert
 
AlbaniaDreamin24 - How to easily use an API with Flows
AlbaniaDreamin24 - How to easily use an API with FlowsAlbaniaDreamin24 - How to easily use an API with Flows
AlbaniaDreamin24 - How to easily use an API with FlowsThierry TROUIN ☁
 

Recently uploaded (20)

Best VIP Call Girls Noida Sector 75 Call Me: 8448380779
Best VIP Call Girls Noida Sector 75 Call Me: 8448380779Best VIP Call Girls Noida Sector 75 Call Me: 8448380779
Best VIP Call Girls Noida Sector 75 Call Me: 8448380779
 
Call Girls in Mayur Vihar ✔️ 9711199171 ✔️ Delhi ✔️ Enjoy Call Girls With Our...
Call Girls in Mayur Vihar ✔️ 9711199171 ✔️ Delhi ✔️ Enjoy Call Girls With Our...Call Girls in Mayur Vihar ✔️ 9711199171 ✔️ Delhi ✔️ Enjoy Call Girls With Our...
Call Girls in Mayur Vihar ✔️ 9711199171 ✔️ Delhi ✔️ Enjoy Call Girls With Our...
 
Challengers I Told Ya ShirtChallengers I Told Ya Shirt
Challengers I Told Ya ShirtChallengers I Told Ya ShirtChallengers I Told Ya ShirtChallengers I Told Ya Shirt
Challengers I Told Ya ShirtChallengers I Told Ya Shirt
 
Radiant Call girls in Dubai O56338O268 Dubai Call girls
Radiant Call girls in Dubai O56338O268 Dubai Call girlsRadiant Call girls in Dubai O56338O268 Dubai Call girls
Radiant Call girls in Dubai O56338O268 Dubai Call girls
 
Call Girls In Model Towh Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Model Towh Delhi 💯Call Us 🔝8264348440🔝Call Girls In Model Towh Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Model Towh Delhi 💯Call Us 🔝8264348440🔝
 
Rohini Sector 22 Call Girls Delhi 9999965857 @Sabina Saikh No Advance
Rohini Sector 22 Call Girls Delhi 9999965857 @Sabina Saikh No AdvanceRohini Sector 22 Call Girls Delhi 9999965857 @Sabina Saikh No Advance
Rohini Sector 22 Call Girls Delhi 9999965857 @Sabina Saikh No Advance
 
Dwarka Sector 26 Call Girls | Delhi | 9999965857 🫦 Vanshika Verma More Our Se...
Dwarka Sector 26 Call Girls | Delhi | 9999965857 🫦 Vanshika Verma More Our Se...Dwarka Sector 26 Call Girls | Delhi | 9999965857 🫦 Vanshika Verma More Our Se...
Dwarka Sector 26 Call Girls | Delhi | 9999965857 🫦 Vanshika Verma More Our Se...
 
Hot Call Girls |Delhi |Hauz Khas ☎ 9711199171 Book Your One night Stand
Hot Call Girls |Delhi |Hauz Khas ☎ 9711199171 Book Your One night StandHot Call Girls |Delhi |Hauz Khas ☎ 9711199171 Book Your One night Stand
Hot Call Girls |Delhi |Hauz Khas ☎ 9711199171 Book Your One night Stand
 
FULL ENJOY Call Girls In Mayur Vihar Delhi Contact Us 8377087607
FULL ENJOY Call Girls In Mayur Vihar Delhi Contact Us 8377087607FULL ENJOY Call Girls In Mayur Vihar Delhi Contact Us 8377087607
FULL ENJOY Call Girls In Mayur Vihar Delhi Contact Us 8377087607
 
Rohini Sector 6 Call Girls Delhi 9999965857 @Sabina Saikh No Advance
Rohini Sector 6 Call Girls Delhi 9999965857 @Sabina Saikh No AdvanceRohini Sector 6 Call Girls Delhi 9999965857 @Sabina Saikh No Advance
Rohini Sector 6 Call Girls Delhi 9999965857 @Sabina Saikh No Advance
 
Chennai Call Girls Porur Phone 🍆 8250192130 👅 celebrity escorts service
Chennai Call Girls Porur Phone 🍆 8250192130 👅 celebrity escorts serviceChennai Call Girls Porur Phone 🍆 8250192130 👅 celebrity escorts service
Chennai Call Girls Porur Phone 🍆 8250192130 👅 celebrity escorts service
 
Call Girls In South Ex 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SERVICE
Call Girls In South Ex 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SERVICECall Girls In South Ex 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SERVICE
Call Girls In South Ex 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SERVICE
 
VIP 7001035870 Find & Meet Hyderabad Call Girls LB Nagar high-profile Call Girl
VIP 7001035870 Find & Meet Hyderabad Call Girls LB Nagar high-profile Call GirlVIP 7001035870 Find & Meet Hyderabad Call Girls LB Nagar high-profile Call Girl
VIP 7001035870 Find & Meet Hyderabad Call Girls LB Nagar high-profile Call Girl
 
GDG Cloud Southlake 32: Kyle Hettinger: Demystifying the Dark Web
GDG Cloud Southlake 32: Kyle Hettinger: Demystifying the Dark WebGDG Cloud Southlake 32: Kyle Hettinger: Demystifying the Dark Web
GDG Cloud Southlake 32: Kyle Hettinger: Demystifying the Dark Web
 
Rohini Sector 26 Call Girls Delhi 9999965857 @Sabina Saikh No Advance
Rohini Sector 26 Call Girls Delhi 9999965857 @Sabina Saikh No AdvanceRohini Sector 26 Call Girls Delhi 9999965857 @Sabina Saikh No Advance
Rohini Sector 26 Call Girls Delhi 9999965857 @Sabina Saikh No Advance
 
'Future Evolution of the Internet' delivered by Geoff Huston at Everything Op...
'Future Evolution of the Internet' delivered by Geoff Huston at Everything Op...'Future Evolution of the Internet' delivered by Geoff Huston at Everything Op...
'Future Evolution of the Internet' delivered by Geoff Huston at Everything Op...
 
✂️ 👅 Independent Andheri Escorts With Room Vashi Call Girls 💃 9004004663
✂️ 👅 Independent Andheri Escorts With Room Vashi Call Girls 💃 9004004663✂️ 👅 Independent Andheri Escorts With Room Vashi Call Girls 💃 9004004663
✂️ 👅 Independent Andheri Escorts With Room Vashi Call Girls 💃 9004004663
 
VIP 7001035870 Find & Meet Hyderabad Call Girls Dilsukhnagar high-profile Cal...
VIP 7001035870 Find & Meet Hyderabad Call Girls Dilsukhnagar high-profile Cal...VIP 7001035870 Find & Meet Hyderabad Call Girls Dilsukhnagar high-profile Cal...
VIP 7001035870 Find & Meet Hyderabad Call Girls Dilsukhnagar high-profile Cal...
 
10.pdfMature Call girls in Dubai +971563133746 Dubai Call girls
10.pdfMature Call girls in Dubai +971563133746 Dubai Call girls10.pdfMature Call girls in Dubai +971563133746 Dubai Call girls
10.pdfMature Call girls in Dubai +971563133746 Dubai Call girls
 
AlbaniaDreamin24 - How to easily use an API with Flows
AlbaniaDreamin24 - How to easily use an API with FlowsAlbaniaDreamin24 - How to easily use an API with Flows
AlbaniaDreamin24 - How to easily use an API with Flows
 

09. Methods

  • 1. Methods Writing and using methods, overloads, ref, out SoftUni Team Technical Trainers Software University http://softuni.bg
  • 2. Table of Contents 1. Using Methods  What is a Method? Why Use Methods?  Declaring and Creating Methods  Calling Methods 2. Methods with Parameters  Passing Parameters  Returning Values 3. Best Practices 2
  • 4.  A method is a named piece of code  Each method has: Declaring Methods static void PrintHyphens(int count) { Console.WriteLine( new string('-', count)); } NameReturn type Parameters Body
  • 5. 5  Methods can be invoked (called) by their name Invoking Methods static void PrintHyphens(int count) { Console.WriteLine(new string('-', count)); } static void Main() { for (int i = 1; i <= 10; i++) { PrintHyphens(i); } } Method body always surrounded by { } Method called by name
  • 7. 7  Method parameters can be of any type  Separated by comma Method Parameters static void PrintNumbers(int start, int end) { for (int i = start; i <= end; i++) { Console.Write("{0} ", i); } } static void Main() { PrintNumbers(5, 10); } Declares the use of int start and int end Passed concrete values when called
  • 8. Method Parameters – Example 8 static void PrintSign(int number) { if (number > 0) Console.WriteLine("The number {0} is positive.", number); else if (number < 0) Console.WriteLine("The number {0} is negative.", number); else Console.WriteLine("The number {0} is zero.", number); } static void Main() { PrintSign(5); PrintSign(-3); PrintSign(0); }
  • 9.  C# 4.0 supports optional parameters with default values:  The above method can be called in several ways: Optional Parameters static void PrintNumbers(int start = 0, int end = 100) { for (int i = start; i <= end; i++) { Console.Write("{0} ", i); } } PrintNumbers(5, 10); PrintNumbers(15); PrintNumbers(); PrintNumbers(end: 40, start: 35);
  • 12. Printing Triangle  Create a method for printing triangles as shown below: 12 1 1 1 2 1 2 1 2 3 1 2 3 1 2 3 4 1 2 3 4 1 2 3 4 5 n=5  1 2 3 4 5 n=6  1 2 3 4 5 6 1 2 3 4 1 2 3 4 5 1 2 3 1 2 3 4 1 2 1 2 3 1 1 2 1
  • 13.
  • 15. 15  Type void - does not return a value (only executes code)  Other types - return values, based on the return type of the method Method Return Types static void AddOne(int n) { n += 1; Console.WriteLine(n); } static int PlusOne(int n) { return n + 1; }
  • 16. 16 Methods with Parameters and Return Value static double CalcTriangleArea(double width, double height) { return width * height / 2; } static void Main() { Console.Write("Enter triangle width: "); double width = double.Parse(Console.ReadLine()); Console.Write("Enter triangle height: "); double height = double.Parse(Console.ReadLine()); Console.WriteLine(CalcTriangleArea(width, height)); }
  • 17. 17 Power Method static double Power(double number, int power) { double result = 1; for (int i = 0; i < power; i++) { result *= number; } return result; } static void Main() { double powerTwo = Power(5, 2); Console.WriteLine(powerTwo); double powerThree = Power(7.45, 3); Console.WriteLine(powerThree); }
  • 18. 18  Convert temperature from Fahrenheit to Celsius: Temperature Conversion – Example static double FahrenheitToCelsius(double degrees) { double celsius = (degrees - 32) * 5 / 9; return celsius; } static void Main() { Console.Write("Temperature in Fahrenheit: "); double t = Double.Parse(Console.ReadLine()); t = FahrenheitToCelsius(t); Console.Write("Temperature in Celsius: {0}", t); }
  • 21. 21  Method Overloading  Use the same method name for multiple methods with different signature (return type and parameters) Overloading Methods static void Print(string text) { Console.WriteLine(text); } static void Print(int number) { Console.WriteLine(number); } static void Print(string text, int number) { Console.WriteLine(text + ' ' + number); }
  • 22. Why Use Methods?  More manageable programming  Splits large problems into small pieces  Better organization of the program  Improves code readability  Improves code understandability  Avoiding repeating code  Improves code maintainability  Code reusability  Using existing methods several times 22
  • 23. 23  Each method should perform a single, well-defined task  Method's name should describe that task in a clear and non- ambiguous way  Good examples: CalculatePrice, ReadName  Bad examples: f, g1, Process  In C# methods should start with a capital letter (PascalCase)  Avoid methods longer than one screen  Split them to several shorter methods Methods – Best Practices
  • 24. 24  Break large programs into simple methods that solve small sub-problems  Methods consist of declaration and body  Methods are invoked by their name  Methods can accept parameters  Parameters take actual values when calling a method  Methods can return a value or nothing (void) Summary
  • 25. ? Fundamentals Level @ SoftUni http://softuni.bg/courses/advanced-csharp
  • 26. License  This course (slides, examples, demos, videos, homework, etc.) is licensed under the "Creative Commons Attribution- NonCommercial-ShareAlike 4.0 International" license  Attribution: this work may contain portions from  "C# Fundamentals – Part 1" course by Telerik Academy under CC-BY-NC-SA license  "C# Fundamentals – Part 2" course by Telerik Academy under CC-BY-NC-SA license 26
  • 27. Free Trainings @ Software University  Software University Foundation – softuni.org  Software University – High-Quality Education, Profession and Job for Software Developers  softuni.bg  Software University @ Facebook  facebook.com/SoftwareUniversity  Software University @ YouTube  youtube.com/SoftwareUniversity  Software University Forums – forum.softuni.bg

Editor's Notes

  1. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  2. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  3. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  4. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  5. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*