SlideShare ist ein Scribd-Unternehmen logo
1 von 11
C#
LECTURE
Abid Kohistani
GC Madyan Swat
Methods
A method is a block of code which only runs when it is called.
You can pass data, known as parameters, into a method.
Methods are used to perform certain actions, and they are also known as functions.
Why use methods? To reuse code: define the code once, and use it many times.
Create a Method
A method is defined with the name of the method, followed by parentheses ().
C# provides some pre-defined methods, which you already are familiar with, such as Main(), but you can
also create your own methods to perform certain actions:
class Program
{
static void MyMethod()
{
// code to be executed
}
}
Syntax
MyMethod() is the name of the method
static means that the method belongs to the Program class and not
an object of the Program class. You will learn more about objects
and how to access methods through objects later in this tutorial.
void means that this method does not have a return value. You will
learn more about return values later in this chapter
Note: In C#, it is good practice to start with an uppercase letter when
naming methods, as it makes the code easier to read.
Call a Method
To call (execute) a method, write the method's name followed by two parentheses () and a semicolon;
In the following example, MyMethod( ) is used to print a text (the action), when it is called:
static void MyMethod()
{
Console.WriteLine("I just got executed!");
}
static void Main(string[] args)
{
MyMethod();
} // Outputs "I just got executed!"
Example 1
static void MyMethod()
{
Console.WriteLine("I just got executed!");
}
static void Main(string[] args)
{
MyMethod();
MyMethod();
MyMethod();
} // I just got executed!
// I just got executed!
// I just got executed!
Example 2
A method can be called multiple times:
Parameters and Arguments
Information can be passed to methods as parameter. Parameters act as variables inside the method.
They are specified after the method name, inside the parentheses. You can add as many parameters as you
want, just separate them with a comma.
The following example has a method that takes a string called fname as parameter. When the method is
called, we pass along a first name, which is used inside the method to print the full name:
When a parameter is passed to the
method, it is called an argument.
So, from the example above:
fname is a parameter, while Liam,
Jenny and Anja are arguments.
static void MyMethod(string fname)
{
Console.WriteLine(fname + " Refsnes");
}
static void Main(string[] args)
{
MyMethod("Liam");
MyMethod("Jenny");
MyMethod("Anja");
}
// Liam Refsnes
// Jenny Refsnes // Anja Refsnes
Default Parameter Value
You can also use a default parameter value, by using the equals sign (=). If we call the method without an
argument, it uses the default value ("Norway"):
static void MyMethod(string country = "Norway")
{
Console.WriteLine(country);
}
static void Main(string[] args)
{
MyMethod("Sweden");
MyMethod("India");
MyMethod();
MyMethod("USA"); } // Sweden // pakistan// Norway // USA
Example
A parameter with a default value, is often
known as an "optional parameter". From the
example above, country is an optional
parameter and "Norway" is the default value.
Multiple Parameters
You can have as many parameters as you like:
Note that when you are working with
multiple parameters, the method call
must have the same number of
arguments as there are parameters,
and the arguments must be passed
in the same order.
static void MyMethod(string fname, int age)
{
Console.WriteLine(fname + " is " + age);
}
static void Main(string[] args)
{
MyMethod("Liam", 5);
MyMethod("Jenny", 8);
MyMethod("Anja", 31);
} // Liam is 5 // Jenny is 8 // Anja is 31
Example
Return Values
The void keyword, used in the examples above, indicates that the method should not return a value. If you
want the method to return a value, you can use a primitive data type (such as int or double) instead of void,
and use the return keyword inside the method:
This example returns the sum of a
method's two parameters:
static int MyMethod(int x)
{
return 5 + x;
}
static void Main(string[] args)
{
Console.WriteLine(MyMethod(3));
} // Outputs 8 (5 + 3)
Example
static int MyMethod(int x, int y)
{
return x + y;
}
static void Main(string[] args)
{
Console.WriteLine(MyMethod(5, 3));
} // Outputs 8 (5 + 3)
static int MyMethod(int x, int y)
{
return x + y;
}
static void Main(string[] args)
{
int z = MyMethod(5, 3);
Console.WriteLine(z);
} // Outputs 8 (5 + 3)
You can also store the result in a
variable (recommended, as it is easier
to read and maintain):
Named Arguments
It is also possible to send arguments with the key: value syntax.
That way, the order of the arguments does not matter:
static void MyMethod(string child1, string child2, string child3)
{
Console.WriteLine("The youngest child is: " + child3);
}
static void Main(string[] args)
{
MyMethod(child3: "John", child1: "Liam", child2: "Liam");
} // The youngest child is: John
Example
Method Overloading
With method overloading, multiple methods can have the same name with different parameters:
static int PlusMethod(int x, int y)
{
return x + y;
}
static double PlusMethod(double x, double y)
{
return x + y;
}
static void Main(string[] args)
{
int myNum1 = PlusMethod(8, 5);
double myNum2 = PlusMethod(4.3, 6.26);
Console.WriteLine("Int: " + myNum1);
Console.WriteLine("Double: " + myNum2);
}
Example
END

Weitere ähnliche Inhalte

Was ist angesagt?

Was ist angesagt? (20)

Namespaces
NamespacesNamespaces
Namespaces
 
Input output streams
Input output streamsInput output streams
Input output streams
 
Unit 4 python -list methods
Unit 4   python -list methodsUnit 4   python -list methods
Unit 4 python -list methods
 
Method overriding
Method overridingMethod overriding
Method overriding
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
 
Datatype in c++ unit 3 -topic 2
Datatype in c++ unit 3 -topic 2Datatype in c++ unit 3 -topic 2
Datatype in c++ unit 3 -topic 2
 
java interface and packages
java interface and packagesjava interface and packages
java interface and packages
 
Java Input Output and File Handling
Java Input Output and File HandlingJava Input Output and File Handling
Java Input Output and File Handling
 
interface in c#
interface in c#interface in c#
interface in c#
 
Java arrays
Java arraysJava arrays
Java arrays
 
Static Data Members and Member Functions
Static Data Members and Member FunctionsStatic Data Members and Member Functions
Static Data Members and Member Functions
 
Problem solving and design
Problem solving and designProblem solving and design
Problem solving and design
 
Variables in python
Variables in pythonVariables in python
Variables in python
 
Constructors in C++
Constructors in C++Constructors in C++
Constructors in C++
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
Python data type
Python data typePython data type
Python data type
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
 
Arrays in java
Arrays in javaArrays in java
Arrays in java
 
Python programming : Classes objects
Python programming : Classes objectsPython programming : Classes objects
Python programming : Classes objects
 
Array lecture
Array lectureArray lecture
Array lecture
 

Ähnlich wie Methods In C-Sharp (C#)

Working with Methods in Java.pptx
Working with Methods in Java.pptxWorking with Methods in Java.pptx
Working with Methods in Java.pptxmaryansagsgao
 
Chapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part IIChapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part IIEduardo Bergavera
 
Java căn bản - Chapter7
Java căn bản - Chapter7Java căn bản - Chapter7
Java căn bản - Chapter7Vince Vo
 
CIS 1403 lab 3 functions and methods in Java
CIS 1403 lab 3 functions and methods in JavaCIS 1403 lab 3 functions and methods in Java
CIS 1403 lab 3 functions and methods in JavaHamad Odhabi
 
Java method present by showrov ahamed
Java method present by showrov ahamedJava method present by showrov ahamed
Java method present by showrov ahamedMd Showrov Ahmed
 
Bad Smell in Codes - Part 1
Bad Smell in Codes - Part 1Bad Smell in Codes - Part 1
Bad Smell in Codes - Part 1Shaer Hassan
 
EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...
EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...
EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...vekariyakashyap
 
Module 4 : methods & parameters
Module 4 : methods & parametersModule 4 : methods & parameters
Module 4 : methods & parametersPrem Kumar Badri
 
Java căn bản - Chapter4
Java căn bản - Chapter4Java căn bản - Chapter4
Java căn bản - Chapter4Vince Vo
 
Chapter 4 - Defining Your Own Classes - Part I
Chapter 4 - Defining Your Own Classes - Part IChapter 4 - Defining Your Own Classes - Part I
Chapter 4 - Defining Your Own Classes - Part IEduardo Bergavera
 
Lecture_7 Method Overloading.pptx
Lecture_7 Method Overloading.pptxLecture_7 Method Overloading.pptx
Lecture_7 Method Overloading.pptxMaheenVohra
 

Ähnlich wie Methods In C-Sharp (C#) (20)

Working with Methods in Java.pptx
Working with Methods in Java.pptxWorking with Methods in Java.pptx
Working with Methods in Java.pptx
 
static methods
static methodsstatic methods
static methods
 
Methods in Java
Methods in JavaMethods in Java
Methods in Java
 
Computer programming 2 Lesson 15
Computer programming 2  Lesson 15Computer programming 2  Lesson 15
Computer programming 2 Lesson 15
 
Chapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part IIChapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part II
 
Java căn bản - Chapter7
Java căn bản - Chapter7Java căn bản - Chapter7
Java căn bản - Chapter7
 
CIS 1403 lab 3 functions and methods in Java
CIS 1403 lab 3 functions and methods in JavaCIS 1403 lab 3 functions and methods in Java
CIS 1403 lab 3 functions and methods in Java
 
Methods.ppt
Methods.pptMethods.ppt
Methods.ppt
 
Java method present by showrov ahamed
Java method present by showrov ahamedJava method present by showrov ahamed
Java method present by showrov ahamed
 
Bad Smell in Codes - Part 1
Bad Smell in Codes - Part 1Bad Smell in Codes - Part 1
Bad Smell in Codes - Part 1
 
Class 10
Class 10Class 10
Class 10
 
EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...
EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...
EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...
 
Module 4 : methods & parameters
Module 4 : methods & parametersModule 4 : methods & parameters
Module 4 : methods & parameters
 
Methods intro-1.0
Methods intro-1.0Methods intro-1.0
Methods intro-1.0
 
Java căn bản - Chapter4
Java căn bản - Chapter4Java căn bản - Chapter4
Java căn bản - Chapter4
 
Chapter 4 - Defining Your Own Classes - Part I
Chapter 4 - Defining Your Own Classes - Part IChapter 4 - Defining Your Own Classes - Part I
Chapter 4 - Defining Your Own Classes - Part I
 
Lecture_7 Method Overloading.pptx
Lecture_7 Method Overloading.pptxLecture_7 Method Overloading.pptx
Lecture_7 Method Overloading.pptx
 
09. Methods
09. Methods09. Methods
09. Methods
 
Methods in C#
Methods in C#Methods in C#
Methods in C#
 
7494605
74946057494605
7494605
 

Mehr von Abid Kohistani

Algorithm in Computer, Sorting and Notations
Algorithm in Computer, Sorting  and NotationsAlgorithm in Computer, Sorting  and Notations
Algorithm in Computer, Sorting and NotationsAbid Kohistani
 
Polymorphism in C# Function overloading in C#
Polymorphism in C# Function overloading in C#Polymorphism in C# Function overloading in C#
Polymorphism in C# Function overloading in C#Abid Kohistani
 
Exception Handling in C#
Exception Handling in C#Exception Handling in C#
Exception Handling in C#Abid Kohistani
 
Access Modifiers in C# ,Inheritance and Encapsulation
Access Modifiers in C# ,Inheritance and EncapsulationAccess Modifiers in C# ,Inheritance and Encapsulation
Access Modifiers in C# ,Inheritance and EncapsulationAbid Kohistani
 
OOP in C# Classes and Objects.
OOP in C# Classes and Objects.OOP in C# Classes and Objects.
OOP in C# Classes and Objects.Abid Kohistani
 
Loops in C# for loops while and do while loop.
Loops in C# for loops while and do while loop.Loops in C# for loops while and do while loop.
Loops in C# for loops while and do while loop.Abid Kohistani
 
Conditions In C# C-Sharp
Conditions In C# C-SharpConditions In C# C-Sharp
Conditions In C# C-SharpAbid Kohistani
 
C# Operators. (C-Sharp Operators)
C# Operators. (C-Sharp Operators)C# Operators. (C-Sharp Operators)
C# Operators. (C-Sharp Operators)Abid Kohistani
 
data types in C-Sharp (C#)
data types in C-Sharp (C#)data types in C-Sharp (C#)
data types in C-Sharp (C#)Abid Kohistani
 

Mehr von Abid Kohistani (9)

Algorithm in Computer, Sorting and Notations
Algorithm in Computer, Sorting  and NotationsAlgorithm in Computer, Sorting  and Notations
Algorithm in Computer, Sorting and Notations
 
Polymorphism in C# Function overloading in C#
Polymorphism in C# Function overloading in C#Polymorphism in C# Function overloading in C#
Polymorphism in C# Function overloading in C#
 
Exception Handling in C#
Exception Handling in C#Exception Handling in C#
Exception Handling in C#
 
Access Modifiers in C# ,Inheritance and Encapsulation
Access Modifiers in C# ,Inheritance and EncapsulationAccess Modifiers in C# ,Inheritance and Encapsulation
Access Modifiers in C# ,Inheritance and Encapsulation
 
OOP in C# Classes and Objects.
OOP in C# Classes and Objects.OOP in C# Classes and Objects.
OOP in C# Classes and Objects.
 
Loops in C# for loops while and do while loop.
Loops in C# for loops while and do while loop.Loops in C# for loops while and do while loop.
Loops in C# for loops while and do while loop.
 
Conditions In C# C-Sharp
Conditions In C# C-SharpConditions In C# C-Sharp
Conditions In C# C-Sharp
 
C# Operators. (C-Sharp Operators)
C# Operators. (C-Sharp Operators)C# Operators. (C-Sharp Operators)
C# Operators. (C-Sharp Operators)
 
data types in C-Sharp (C#)
data types in C-Sharp (C#)data types in C-Sharp (C#)
data types in C-Sharp (C#)
 

Kürzlich hochgeladen

Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - InfographicHr365.us smith
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 

Kürzlich hochgeladen (20)

Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
Exploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the ProcessExploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the Process
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - Infographic
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 

Methods In C-Sharp (C#)

  • 2. Methods A method is a block of code which only runs when it is called. You can pass data, known as parameters, into a method. Methods are used to perform certain actions, and they are also known as functions. Why use methods? To reuse code: define the code once, and use it many times.
  • 3. Create a Method A method is defined with the name of the method, followed by parentheses (). C# provides some pre-defined methods, which you already are familiar with, such as Main(), but you can also create your own methods to perform certain actions: class Program { static void MyMethod() { // code to be executed } } Syntax MyMethod() is the name of the method static means that the method belongs to the Program class and not an object of the Program class. You will learn more about objects and how to access methods through objects later in this tutorial. void means that this method does not have a return value. You will learn more about return values later in this chapter Note: In C#, it is good practice to start with an uppercase letter when naming methods, as it makes the code easier to read.
  • 4. Call a Method To call (execute) a method, write the method's name followed by two parentheses () and a semicolon; In the following example, MyMethod( ) is used to print a text (the action), when it is called: static void MyMethod() { Console.WriteLine("I just got executed!"); } static void Main(string[] args) { MyMethod(); } // Outputs "I just got executed!" Example 1 static void MyMethod() { Console.WriteLine("I just got executed!"); } static void Main(string[] args) { MyMethod(); MyMethod(); MyMethod(); } // I just got executed! // I just got executed! // I just got executed! Example 2 A method can be called multiple times:
  • 5. Parameters and Arguments Information can be passed to methods as parameter. Parameters act as variables inside the method. They are specified after the method name, inside the parentheses. You can add as many parameters as you want, just separate them with a comma. The following example has a method that takes a string called fname as parameter. When the method is called, we pass along a first name, which is used inside the method to print the full name: When a parameter is passed to the method, it is called an argument. So, from the example above: fname is a parameter, while Liam, Jenny and Anja are arguments. static void MyMethod(string fname) { Console.WriteLine(fname + " Refsnes"); } static void Main(string[] args) { MyMethod("Liam"); MyMethod("Jenny"); MyMethod("Anja"); } // Liam Refsnes // Jenny Refsnes // Anja Refsnes
  • 6. Default Parameter Value You can also use a default parameter value, by using the equals sign (=). If we call the method without an argument, it uses the default value ("Norway"): static void MyMethod(string country = "Norway") { Console.WriteLine(country); } static void Main(string[] args) { MyMethod("Sweden"); MyMethod("India"); MyMethod(); MyMethod("USA"); } // Sweden // pakistan// Norway // USA Example A parameter with a default value, is often known as an "optional parameter". From the example above, country is an optional parameter and "Norway" is the default value.
  • 7. Multiple Parameters You can have as many parameters as you like: Note that when you are working with multiple parameters, the method call must have the same number of arguments as there are parameters, and the arguments must be passed in the same order. static void MyMethod(string fname, int age) { Console.WriteLine(fname + " is " + age); } static void Main(string[] args) { MyMethod("Liam", 5); MyMethod("Jenny", 8); MyMethod("Anja", 31); } // Liam is 5 // Jenny is 8 // Anja is 31 Example
  • 8. Return Values The void keyword, used in the examples above, indicates that the method should not return a value. If you want the method to return a value, you can use a primitive data type (such as int or double) instead of void, and use the return keyword inside the method: This example returns the sum of a method's two parameters: static int MyMethod(int x) { return 5 + x; } static void Main(string[] args) { Console.WriteLine(MyMethod(3)); } // Outputs 8 (5 + 3) Example static int MyMethod(int x, int y) { return x + y; } static void Main(string[] args) { Console.WriteLine(MyMethod(5, 3)); } // Outputs 8 (5 + 3) static int MyMethod(int x, int y) { return x + y; } static void Main(string[] args) { int z = MyMethod(5, 3); Console.WriteLine(z); } // Outputs 8 (5 + 3) You can also store the result in a variable (recommended, as it is easier to read and maintain):
  • 9. Named Arguments It is also possible to send arguments with the key: value syntax. That way, the order of the arguments does not matter: static void MyMethod(string child1, string child2, string child3) { Console.WriteLine("The youngest child is: " + child3); } static void Main(string[] args) { MyMethod(child3: "John", child1: "Liam", child2: "Liam"); } // The youngest child is: John Example
  • 10. Method Overloading With method overloading, multiple methods can have the same name with different parameters: static int PlusMethod(int x, int y) { return x + y; } static double PlusMethod(double x, double y) { return x + y; } static void Main(string[] args) { int myNum1 = PlusMethod(8, 5); double myNum2 = PlusMethod(4.3, 6.26); Console.WriteLine("Int: " + myNum1); Console.WriteLine("Double: " + myNum2); } Example
  • 11. END