Enviar pesquisa
Carregar
C sharp chap5
•
0 gostou
•
1,584 visualizações
M
Mukesh Tekwani
Seguir
C#
Leia menos
Leia mais
Educação
Denunciar
Compartilhar
Denunciar
Compartilhar
1 de 13
Baixar agora
Baixar para ler offline
Recomendados
C sharp chap6
C sharp chap6
Mukesh Tekwani
C sharp chap4
C sharp chap4
Mukesh Tekwani
Intake 38 3
Intake 38 3
Mahmoud Ouf
Intake 38 5
Intake 38 5
Mahmoud Ouf
Basic c#
Basic c#
kishore4268
Bc0037
Bc0037
hayerpa
Intake 38 5 1
Intake 38 5 1
Mahmoud Ouf
Intake 38 2
Intake 38 2
Mahmoud Ouf
Recomendados
C sharp chap6
C sharp chap6
Mukesh Tekwani
C sharp chap4
C sharp chap4
Mukesh Tekwani
Intake 38 3
Intake 38 3
Mahmoud Ouf
Intake 38 5
Intake 38 5
Mahmoud Ouf
Basic c#
Basic c#
kishore4268
Bc0037
Bc0037
hayerpa
Intake 38 5 1
Intake 38 5 1
Mahmoud Ouf
Intake 38 2
Intake 38 2
Mahmoud Ouf
Visula C# Programming Lecture 6
Visula C# Programming Lecture 6
Abou Bakr Ashraf
C# Summer course - Lecture 3
C# Summer course - Lecture 3
mohamedsamyali
Intake 38 data access 5
Intake 38 data access 5
Mahmoud Ouf
Intake 38 6
Intake 38 6
Mahmoud Ouf
C# Summer course - Lecture 4
C# Summer course - Lecture 4
mohamedsamyali
Introduction to objective c
Introduction to objective c
Mayank Jalotra
C++ tutorials
C++ tutorials
Divyanshu Dubey
Java execise
Java execise
Keneth miles
Intake 38 data access 3
Intake 38 data access 3
Mahmoud Ouf
C basic questions&ansrs by shiva kumar kella
C basic questions&ansrs by shiva kumar kella
Manoj Kumar kothagulla
The Ring programming language version 1.9 book - Part 98 of 210
The Ring programming language version 1.9 book - Part 98 of 210
Mahmoud Samir Fayed
Templates
Templates
Pranali Chaudhari
Resource wrappers in C++
Resource wrappers in C++
Ilio Catallo
java tutorial 2
java tutorial 2
Tushar Desarda
SPF Getting Started - Console Program
SPF Getting Started - Console Program
Hock Leng PUAH
Intake 37 6
Intake 37 6
Mahmoud Ouf
Intake 37 5
Intake 37 5
Mahmoud Ouf
java tutorial 3
java tutorial 3
Tushar Desarda
The Ring programming language version 1.5.1 book - Part 174 of 180
The Ring programming language version 1.5.1 book - Part 174 of 180
Mahmoud Samir Fayed
Introduction to c ++ part -2
Introduction to c ++ part -2
baabtra.com - No. 1 supplier of quality freshers
Debugging in .Net
Debugging in .Net
Muhammad Amir
Exception handling in asp.net
Exception handling in asp.net
Neelesh Shukla
Mais conteúdo relacionado
Mais procurados
Visula C# Programming Lecture 6
Visula C# Programming Lecture 6
Abou Bakr Ashraf
C# Summer course - Lecture 3
C# Summer course - Lecture 3
mohamedsamyali
Intake 38 data access 5
Intake 38 data access 5
Mahmoud Ouf
Intake 38 6
Intake 38 6
Mahmoud Ouf
C# Summer course - Lecture 4
C# Summer course - Lecture 4
mohamedsamyali
Introduction to objective c
Introduction to objective c
Mayank Jalotra
C++ tutorials
C++ tutorials
Divyanshu Dubey
Java execise
Java execise
Keneth miles
Intake 38 data access 3
Intake 38 data access 3
Mahmoud Ouf
C basic questions&ansrs by shiva kumar kella
C basic questions&ansrs by shiva kumar kella
Manoj Kumar kothagulla
The Ring programming language version 1.9 book - Part 98 of 210
The Ring programming language version 1.9 book - Part 98 of 210
Mahmoud Samir Fayed
Templates
Templates
Pranali Chaudhari
Resource wrappers in C++
Resource wrappers in C++
Ilio Catallo
java tutorial 2
java tutorial 2
Tushar Desarda
SPF Getting Started - Console Program
SPF Getting Started - Console Program
Hock Leng PUAH
Intake 37 6
Intake 37 6
Mahmoud Ouf
Intake 37 5
Intake 37 5
Mahmoud Ouf
java tutorial 3
java tutorial 3
Tushar Desarda
The Ring programming language version 1.5.1 book - Part 174 of 180
The Ring programming language version 1.5.1 book - Part 174 of 180
Mahmoud Samir Fayed
Introduction to c ++ part -2
Introduction to c ++ part -2
baabtra.com - No. 1 supplier of quality freshers
Mais procurados
(20)
Visula C# Programming Lecture 6
Visula C# Programming Lecture 6
C# Summer course - Lecture 3
C# Summer course - Lecture 3
Intake 38 data access 5
Intake 38 data access 5
Intake 38 6
Intake 38 6
C# Summer course - Lecture 4
C# Summer course - Lecture 4
Introduction to objective c
Introduction to objective c
C++ tutorials
C++ tutorials
Java execise
Java execise
Intake 38 data access 3
Intake 38 data access 3
C basic questions&ansrs by shiva kumar kella
C basic questions&ansrs by shiva kumar kella
The Ring programming language version 1.9 book - Part 98 of 210
The Ring programming language version 1.9 book - Part 98 of 210
Templates
Templates
Resource wrappers in C++
Resource wrappers in C++
java tutorial 2
java tutorial 2
SPF Getting Started - Console Program
SPF Getting Started - Console Program
Intake 37 6
Intake 37 6
Intake 37 5
Intake 37 5
java tutorial 3
java tutorial 3
The Ring programming language version 1.5.1 book - Part 174 of 180
The Ring programming language version 1.5.1 book - Part 174 of 180
Introduction to c ++ part -2
Introduction to c ++ part -2
Destaque
Debugging in .Net
Debugging in .Net
Muhammad Amir
Exception handling in asp.net
Exception handling in asp.net
Neelesh Shukla
Exception Handling Mechanism in .NET CLR
Exception Handling Mechanism in .NET CLR
Kiran Munir
Debugging
Debugging
nicky_walters
CSharp Presentation
CSharp Presentation
Vishwa Mohan
EVALUATION OF PROCESSES PARAMETER AND MECHANICAL PROPERTIES IN FRICTION STIR ...
EVALUATION OF PROCESSES PARAMETER AND MECHANICAL PROPERTIES IN FRICTION STIR ...
IAEME Publication
Error handling and debugging in vb
Error handling and debugging in vb
Salim M
Programming in c#
Programming in c#
Shehrevar Davierwala
Data Structure In C#
Data Structure In C#
Shahzad
Presentation on visual basic 6 (vb6)
Presentation on visual basic 6 (vb6)
pbarasia
Introduction to visual basic programming
Introduction to visual basic programming
Roger Argarin
Basic controls of Visual Basic 6.0
Basic controls of Visual Basic 6.0
Salim M
Destaque
(12)
Debugging in .Net
Debugging in .Net
Exception handling in asp.net
Exception handling in asp.net
Exception Handling Mechanism in .NET CLR
Exception Handling Mechanism in .NET CLR
Debugging
Debugging
CSharp Presentation
CSharp Presentation
EVALUATION OF PROCESSES PARAMETER AND MECHANICAL PROPERTIES IN FRICTION STIR ...
EVALUATION OF PROCESSES PARAMETER AND MECHANICAL PROPERTIES IN FRICTION STIR ...
Error handling and debugging in vb
Error handling and debugging in vb
Programming in c#
Programming in c#
Data Structure In C#
Data Structure In C#
Presentation on visual basic 6 (vb6)
Presentation on visual basic 6 (vb6)
Introduction to visual basic programming
Introduction to visual basic programming
Basic controls of Visual Basic 6.0
Basic controls of Visual Basic 6.0
Semelhante a C sharp chap5
Java căn bản - Chapter7
Java căn bản - Chapter7
Vince Vo
Chapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part II
Eduardo Bergavera
Introduction to C++
Introduction to C++
Pranali Chaudhari
Ap Power Point Chpt4
Ap Power Point Chpt4
dplunkett
OBJECT ORIENTED PROGRAMING IN C++
OBJECT ORIENTED PROGRAMING IN C++
Dev Chauhan
OOC MODULE1.pptx
OOC MODULE1.pptx
1HK19CS090MOHAMMEDSA
Presentation 3rd
Presentation 3rd
Connex
Class and object
Class and object
Prof. Dr. K. Adisesha
9781439035665 ppt ch08
9781439035665 ppt ch08
Terry Yoast
My c++
My c++
snathick
I assignmnt(oops)
I assignmnt(oops)
Jay Patel
C++ largest no between three nos
C++ largest no between three nos
krismishra
CS3391 -OOP -UNIT – II NOTES FINAL.pdf
CS3391 -OOP -UNIT – II NOTES FINAL.pdf
AALIM MUHAMMED SALEGH COLLEGE OF ENGINEERING
The smartpath information systems c plus plus
The smartpath information systems c plus plus
The Smartpath Information Systems,Bhilai,Durg,Chhattisgarh.
Unit3
Unit3
Abha Damani
Microsoft dynamics ax 2012 development introduction part 2/3
Microsoft dynamics ax 2012 development introduction part 2/3
Ali Raza Zaidi
CLASSES AND OBJECTS IN C++ +2 COMPUTER SCIENCE
CLASSES AND OBJECTS IN C++ +2 COMPUTER SCIENCE
Venugopalavarma Raja
C++ beginner's guide ch08
C++ beginner's guide ch08
Jotham Gadot
CIS 1403 lab 3 functions and methods in Java
CIS 1403 lab 3 functions and methods in Java
Hamad Odhabi
Java class
Java class
Arati Gadgil
Semelhante a C sharp chap5
(20)
Java căn bản - Chapter7
Java căn bản - Chapter7
Chapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part II
Introduction to C++
Introduction to C++
Ap Power Point Chpt4
Ap Power Point Chpt4
OBJECT ORIENTED PROGRAMING IN C++
OBJECT ORIENTED PROGRAMING IN C++
OOC MODULE1.pptx
OOC MODULE1.pptx
Presentation 3rd
Presentation 3rd
Class and object
Class and object
9781439035665 ppt ch08
9781439035665 ppt ch08
My c++
My c++
I assignmnt(oops)
I assignmnt(oops)
C++ largest no between three nos
C++ largest no between three nos
CS3391 -OOP -UNIT – II NOTES FINAL.pdf
CS3391 -OOP -UNIT – II NOTES FINAL.pdf
The smartpath information systems c plus plus
The smartpath information systems c plus plus
Unit3
Unit3
Microsoft dynamics ax 2012 development introduction part 2/3
Microsoft dynamics ax 2012 development introduction part 2/3
CLASSES AND OBJECTS IN C++ +2 COMPUTER SCIENCE
CLASSES AND OBJECTS IN C++ +2 COMPUTER SCIENCE
C++ beginner's guide ch08
C++ beginner's guide ch08
CIS 1403 lab 3 functions and methods in Java
CIS 1403 lab 3 functions and methods in Java
Java class
Java class
Mais de Mukesh Tekwani
Computer Science Made Easy - Youtube Channel
Computer Science Made Easy - Youtube Channel
Mukesh Tekwani
The Elphinstonian 1988-College Building Centenary Number (2).pdf
The Elphinstonian 1988-College Building Centenary Number (2).pdf
Mukesh Tekwani
Circular motion
Circular motion
Mukesh Tekwani
Gravitation
Gravitation
Mukesh Tekwani
ISCE-Class 12-Question Bank - Electrostatics - Physics
ISCE-Class 12-Question Bank - Electrostatics - Physics
Mukesh Tekwani
Hexadecimal to binary conversion
Hexadecimal to binary conversion
Mukesh Tekwani
Hexadecimal to decimal conversion
Hexadecimal to decimal conversion
Mukesh Tekwani
Hexadecimal to octal conversion
Hexadecimal to octal conversion
Mukesh Tekwani
Gray code to binary conversion
Gray code to binary conversion
Mukesh Tekwani
What is Gray Code?
What is Gray Code?
Mukesh Tekwani
Decimal to Binary conversion
Decimal to Binary conversion
Mukesh Tekwani
Video Lectures for IGCSE Physics 2020-21
Video Lectures for IGCSE Physics 2020-21
Mukesh Tekwani
Refraction and dispersion of light through a prism
Refraction and dispersion of light through a prism
Mukesh Tekwani
Refraction of light at a plane surface
Refraction of light at a plane surface
Mukesh Tekwani
Spherical mirrors
Spherical mirrors
Mukesh Tekwani
Atom, origin of spectra Bohr's theory of hydrogen atom
Atom, origin of spectra Bohr's theory of hydrogen atom
Mukesh Tekwani
Refraction of light at spherical surfaces of lenses
Refraction of light at spherical surfaces of lenses
Mukesh Tekwani
ISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGE
ISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGE
Mukesh Tekwani
Cyber Laws
Cyber Laws
Mukesh Tekwani
XML
XML
Mukesh Tekwani
Mais de Mukesh Tekwani
(20)
Computer Science Made Easy - Youtube Channel
Computer Science Made Easy - Youtube Channel
The Elphinstonian 1988-College Building Centenary Number (2).pdf
The Elphinstonian 1988-College Building Centenary Number (2).pdf
Circular motion
Circular motion
Gravitation
Gravitation
ISCE-Class 12-Question Bank - Electrostatics - Physics
ISCE-Class 12-Question Bank - Electrostatics - Physics
Hexadecimal to binary conversion
Hexadecimal to binary conversion
Hexadecimal to decimal conversion
Hexadecimal to decimal conversion
Hexadecimal to octal conversion
Hexadecimal to octal conversion
Gray code to binary conversion
Gray code to binary conversion
What is Gray Code?
What is Gray Code?
Decimal to Binary conversion
Decimal to Binary conversion
Video Lectures for IGCSE Physics 2020-21
Video Lectures for IGCSE Physics 2020-21
Refraction and dispersion of light through a prism
Refraction and dispersion of light through a prism
Refraction of light at a plane surface
Refraction of light at a plane surface
Spherical mirrors
Spherical mirrors
Atom, origin of spectra Bohr's theory of hydrogen atom
Atom, origin of spectra Bohr's theory of hydrogen atom
Refraction of light at spherical surfaces of lenses
Refraction of light at spherical surfaces of lenses
ISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGE
ISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGE
Cyber Laws
Cyber Laws
XML
XML
Último
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
christianmathematics
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
Poonam Aher Patil
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
AnaAcapella
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Celine George
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
pradhanghanshyam7136
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
Celine George
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
jbellavia9
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
VishalSingh1417
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
Celine George
Single or Multiple melodic lines structure
Single or Multiple melodic lines structure
dhanjurrannsibayan2
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
Celine George
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
Admir Softic
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
christianmathematics
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
neillewis46
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University of Engineering & Technology, Jamshoro
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
Sherif Taha
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
TechSoup
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
Jisc
Dyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptx
callscotland1987
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
Pooky Knightsmith
Último
(20)
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
Single or Multiple melodic lines structure
Single or Multiple melodic lines structure
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
Dyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptx
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
C sharp chap5
1.
Generated by Foxit
PDF Creator © Foxit Software http://www.foxitsoftware.com For evaluation only. 5. Classes and Methods – Part 1 Defining a class : The keyword class is used to define a class. The basic structure of a class is as follows: class identifier { Class-body } Where identifier is the name given to the class and class-body is the code that makes up the class. Class declarations: After a class is defined, we use it to create objects. A class is just a definition used to create objects. A class by itself cannot hold information. A class cannot perform any operations. A class is used to declare objects. The object can then be used to hold data and perform operations. The declaration of an object is called instantiation. We say that an object is an instance of a class. The format of declaring an object from a class is as follows: class_name object_identifier = new class_name(); Here, class_name is the name of the class, object_identifier is the name of the object being declared. Example 1: We create an object called c1 of class Circle as follows: Circle c1 = new Circle(); On the right side, the class name with parenthesis i.e., Circle(), is a signal to construct – create – an object of class type Circle. Here: Name of the class is Circle. Name of the object declared is c1. The keyword new is used to create new items. This keyword indicates that a new instance is to be created. In this case, the new instance is the object called c1. Members of a Class: A class can hold two types of items: data members, and function members (methods). Page 1 of 13
2.
Generated by Foxit
PDF Creator © Foxit Software http://www.foxitsoftware.com For evaluation only. Prof. Mukesh N. Tekwani Email: mukeshtekwani@hotmail.com Data Members or fields: Data members include variables and constants. Data members can themselves be classes. Data members are also called as fields. Data members within a class are simply variables that are members of a class. Example 1: Consider a class called Circle defined as follows: class Circle { public int x, y; // co-ordinates of the centre of the circle public int radius; } The keyword public is called the access modifier. Example 2: Create a class called FullName that contains three strings that store the first, middle and last name of a person. class FullName { string firstname; string middlename; string lastname; } Example 3: Create a class called Customer that contains account holder’s bank account no (long), balance amount (float), and a Boolean value called status (active/inactive account); class Customer { long acno; flaot balance; boolean status; } How to access Data Members? Consider a class called Circle. We declare two objects c1 and c2 of this class. Now both the objects can be represented as follows: c1 c2 x x y y Page 2 of 13 Classes and Methods
3.
Generated by Foxit
PDF Creator © Foxit Software http://www.foxitsoftware.com For evaluation only. 4. Programming in C# If we want to refer to the fields x and y then we must specify which object we are referring to. So we use the name of the object and the data member (field name) separated by the dot operator. The dot operator is also called the member of operator. To refer to data x and y of object c1, we write: c1.x and c1.y Similarly, to refer to data x and y of object c2, we write: c2.x and c2.y Methods: 1. A method is a code designed to work with data. Think of a method like a function. 2. Methods are declared inside a class. 3. Methods are declared after declaring all the data members (fields). Declaring Methods: Methods are declared inside the body of a class. The general declaration of a method is : modifier type methodname (formal parameter list) { method body } There are 5 parts in every method declaration: 1. Name of the method (methodname) 2. Type of value the method returns 3. List of parameters (formal parameters) (think of these as inputs for the method) 4. Method modifier, and 5. Body of the method. Examples: void display(); // no parameters int cube (int x); // one int type parameter float area (float len, int bre); // one float, one int parameter, return type float How is a method invoked (or called)? A method can be invoked or called only after it has been defined. The process of activating a method is known as invoking or calling. A method can be invoked like this: Objectname.methodname(actual parameter list); Classes and Methods Page 3 of 13
4.
Generated by Foxit
PDF Creator © Foxit Software http://www.foxitsoftware.com For evaluation only. Prof. Mukesh N. Tekwani Email: mukeshtekwani@hotmail.com Nesting of Methods: A method of a class can be invoked only by an object of that class if it is invoked outside the class. But a method can be called using only its name by another method belonging to the same class.This is known as nesting of methods. In the following program, the class Nesting defines two methods, Largest() and Max(). The method Largest() calls the method Max(). Program 1: To compute the largest of two integers. using System; namespace Method2 { class Nesting { public void Largest(int m, int n) { int large = Max(m, n); // nesting Console.WriteLine(large); } int Max(int a, int b) { int x = (a > b) ? a : b; return (x); } } class NestTesting { public static void Main() { Nesting next = new Nesting(); next.Largest(190, 1077); Console.ReadLine(); } } } Method Parameters: When a method is called, it creates a copy of the formal parameters and local variables of that method. The argument list is used to assign values to the formal parameters. These formal parameters can then be used just like ordinary variables inside the body of the method. When a method is called, we are interested in not only passing values to the method but also in getting back results from that method. It is just like a function which takes input via formal parameters and returns some calculated result. To manage the process of passing values and getting back results from a method, C# supports four types of parameters: Page 4 of 13 Classes and Methods
5.
Generated by Foxit
PDF Creator © Foxit Software http://www.foxitsoftware.com For evaluation only. 4. Programming in C# 1. Value parameters - to pass parameters into methods by value. 2. Reference parameters - to pass parameters into methods by reference. 3. Output parameters - to pass results back from a method. 4. Parameter arrays - used to receive variable number of arguments when called. PASS BY VALUE: i) The default way of passing method parameters is “pass by value”. ii) A parameter declared with no modifier is passed by value and is called a value parameter. iii) When a method is called (or invoked), the values of the actual parameters are assigned to the corresponding formal parameters. iv) The method can then change the values of the value parameters. v) But the value of the actual parameter that is passed to the method is not changed. vi) Thus formal parameter values can change, but actual parameter values are not changed. vii) This is because the method refers only to the copy of the parameter passed to it. viii) Thus, pass by value means pass a copy of the parameter to the method. The following example illustrates the concept of pass-by-value: using System; namespace PassbyValue { class Program { static void multiply(int x) { x = x * 3; Console.WriteLine("Inside the method, x = {0}", x); } public static void Main() { int x = 100; multiply(x); Console.WriteLine("Outside the method, x = {0}", x); Console.ReadLine(); } } } In the above program, we have declared a variable x in method Main. This is assigned a value of 100. When the method multiply is invoked from Main(), the formal parameter is x in the method, while x in the calling part is called the actual parameter. Classes and Methods Page 5 of 13
6.
Generated by Foxit
PDF Creator © Foxit Software http://www.foxitsoftware.com For evaluation only. Prof. Mukesh N. Tekwani Email: mukeshtekwani@hotmail.com PASS BY REFERENCE: i) The default way of passing values to a method is by “pass by value”. ii) We can force the value parameters to be passed by reference. This is done by using the ref keyword. iii) A parameter declared with the ref keyword is a reference parameter. E.g., void Change (ref int x). In this case, x is declared as a reference parameter. iv) A reference parameter does not create a new storage location. It represents or refers to the same storage location as the actual parameter. v) Reference parameters are used when we want to change the values of the variables in the calling method. vi) If the called method changes the value of the reference parameter, this change will be visible in the calling method also. vii) A variable must be assigned a value before it can be passed as a reference variable. viii) They can be used to implement transient parameters, i.e. parameters that are passed to a method, changed there and returned from the method to its caller again. Without ref parameters one would need both a value parameter and a function return value. ix) They can be used to implement methods with multiple transient parameters in which values can be returned to the caller, whereas functions can only return a single value. x) Actual ref parameters are not copied to their formal parameters but are passed by reference (i.e. only their address is passed). For large parameters this is more efficient than copying. xi) ref parameters can lead to side effects, because a formal ref parameter is an alias of the corresponding actual parameter. If the method modifies a formal ref parameter the corresponding actual parameter changes as well. This is a disadvantage of ref parameters. The following example illustrates the use of reference parameters to exchange values of two variables. using System; namespace PassByRef { class Program { static void Swap(ref int x, ref int y) { int temp; temp = x; x = y; y = temp; } static void Main(string[] args) { int m = 100, n = 200; Console.WriteLine("Before swapping:"); Console.WriteLine("m = {0}, n = {1}", m, n); Swap(ref m, ref n); Console.WriteLine("After swapping:"); Console.WriteLine("m = {0}, n = {1}", m, n); } } } Page 6 of 13 Classes and Methods
7.
Generated by Foxit
PDF Creator © Foxit Software http://www.foxitsoftware.com For evaluation only. 4. Programming in C# OUTPUT PARAMETERS: i) Output parameters are used to pass values back to the calling method. ii) Such parameters are declared with the out keyword. iii) An output parameter does not create a new storage location. iv) When a formal parameter is declared with the out keyword, the corresponding actual parameter must also be declared with the out keyword. v) The actual output parameter is not assigned any value in the function call. vi) But every formal parameter declared as an output parameter must be assigned a value before it is returned to the calling method. vii) They can be used to write methods with multiple return values, whereas a function can have only a single return value. viii) Like ref parameters, out parameters are passed by value, i.e. only their address is passed and not their value. For large parameters this is more efficient than copying. The following program illustrates the use of out parameter: using System; namespace OutParameters { class Program { static void square (int x, out int n) { n = x * x; } public static void Main() { int n; // no need to initialize this variable int m = 5; square(m, out n); Console.WriteLine("n = {0}", n); Console.ReadLine(); } } } VARIABLE ARGUMENT LISTS / PARAMETER ARRAY: This is used for passing a number of variables. A parameter array is declared using the params keyword. A method can take only one single dimensional array as a parameter. We can use parameter arrays with value parameters but we cannot use parameter arrays with ref and out modifiers. The following program illustrates the use of variable argument lists. Classes and Methods Page 7 of 13
8.
Generated by Foxit
PDF Creator © Foxit Software http://www.foxitsoftware.com For evaluation only. Prof. Mukesh N. Tekwani Email: mukeshtekwani@hotmail.com using System; namespace ParameterArray { class Program { public static void myfunc(params int[] x) { Console.WriteLine("No. of elements in the array is {0}", x.Length); //the following statements print the array elements foreach (int i in x) Console.WriteLine(" " + i); } static void Main(string[] args) { myfunc(); myfunc(10); myfunc(10, 20); myfunc(10, 20, 30); myfunc(10, 20, 30, 40); Console.ReadLine(); } } } SOLVED EXAMPLES: 1. Write a PrintLine method that will display a line of 20 character length using the * character. using System; namespace StarPrg { class CStar { public void PrintLine(int n) { for(int i = 1; i <= n; i++) { Console.Write("*"); } Console.WriteLine(); } } class MStar { static void Main() { CStar p = new CStar(); p.PrintLine(20); Console.ReadLine(); } } } Page 8 of 13 Classes and Methods
9.
Generated by Foxit
PDF Creator © Foxit Software http://www.foxitsoftware.com For evaluation only. 4. Programming in C# 2. Modify the PrintLine method such that it can take the “character” to be used and the “length” of the line as the input parameters. Write a program using the PrintLine method. using System; namespace StarPrg { class CStar { public void Star(int n, char ch) { for (int i = 1; i <= n; i++) { Console.Write(ch); } Console.WriteLine(); } } class MStar { static void Main() { CStar p = new CStar(); Console.WriteLine("How many characters ?"); int num = int.Parse(Console.ReadLine()); Console.WriteLine("Which character ? "); char ch = char.Parse(Console.ReadLine()); p.Star(num, ch); Console.ReadLine(); } } } 3. Write a void type method that takes two int type value parameters and one int type out parameter and returns the product of the two value parameters through the output parameter. Write a program to test its working. using System; namespace OutParams2 { class Program { static void multiply(int a, int b, out int p) { p = a * b; } static void Main() { int a, b; Classes and Methods Page 9 of 13
10.
Generated by Foxit
PDF Creator © Foxit Software http://www.foxitsoftware.com For evaluation only. Prof. Mukesh N. Tekwani Email: mukeshtekwani@hotmail.com int p; // no ned to initialize this Console.WriteLine("Pls enter value of a "); a = int.Parse(Console.ReadLine()); Console.WriteLine("Pls enter value of b "); b = int.Parse(Console.ReadLine()); multiply(a, b, out p); Console.WriteLine("Product is {0}", p); } } } 4. Write a method that takes three values as input parameters and returns the largest of the three values. Write a program to test its working. using System; namespace Largest3 { class Program { static void largest(int a, int b, int c, out int max) { max = a > b ? a : b; max = max > c ? max : c; } static void Main() { int x, y, z, max; Console.WriteLine("Enter the value of x"); x = int.Parse(Console.ReadLine()); Console.WriteLine("Enter the value of y"); y = int.Parse(Console.ReadLine()); Console.WriteLine("Enter the value of z"); z = int.Parse(Console.ReadLine()); largest(x, y, z, out max); Console.WriteLine("Largest number is {0}", max); Console.ReadLine(); } } } Page 10 of 13 Classes and Methods
11.
Generated by Foxit
PDF Creator © Foxit Software http://www.foxitsoftware.com For evaluation only. 4. Programming in C# 5. Write a method Prime that returns true if its argument is a prime number and returns false otherwise. Write a program to test its working. using System; namespace PrimeMethod { class Program { static bool Prime(int x) { int i; for (i = 2; i <= x - 1; i++) { if (x % i == 0) return false; } return true; } static void Main(string[] args) { int a; Console.WriteLine("Please enter a number"); a = int.Parse(Console.ReadLine()); if (Prime(a)) Console.WriteLine("Number is Prime"); else Console.WriteLine("Number is not prime"); Console.ReadLine(); } } } 6. Write a method Space (int n) that can be used to provide a space of n positions between output of two numbers. Test your method. using System; namespace SpacebetweenNos { class Program { static void Space(int n) { for (int i = 1; i <= n; i++) Console.Write(" "); // note there is only one space quotes marks } Classes and Methods Page 11 of 13
12.
Generated by Foxit
PDF Creator © Foxit Software http://www.foxitsoftware.com For evaluation only. Prof. Mukesh N. Tekwani Email: mukeshtekwani@hotmail.com static void Main() { int x, y; x = 23; // these values are chosen arbitrarily y = 87; int n; // to store the number of spaces required Console.Write("How many spaces do you want "); n = int.Parse(Console.ReadLine()); Console.Write(x); Space(n); Console.Write(y); Console.ReadLine(); } } } METHOD OVERLOADING: Method overloading is the process of using two or more methods with the same name for two or more methods. Each redefinition of the method must use different types of parameters, or different sequence of parameters or different number of parameters. The number, type and sequence of parameters for a function is called the function signature. Method overloading is used when methods have to perform similar tasks but with different input parameters. Method overloading is one form of polymorphism. How does the compiler decide which method to use? The compiler decides this based on the number and type of arguments. The return type of a method is not used to decide which method to call. The following examples illustrate the use of overloaded methods: Ex 1. Write overloaded method add() that takes two or three int type input parameters and returns the sum of the input parameters. using System; namespace Overloading1 { class Program { public static int add(int x, int y) // method with two parameters { int sum; sum = x + y; return (sum); } public static int add(int x, int y, int z) //method with three parameters { int sum; Page 12 of 13 Classes and Methods
13.
Generated by Foxit
PDF Creator © Foxit Software http://www.foxitsoftware.com For evaluation only. 4. Programming in C# sum = x + y + z; return (sum); } static void Main() { int ans; ans = add(10, 20); // call the method with only two arguments Console.WriteLine("Ans = {0}", ans); ans = add(10, 20, 50); // call the method with three arguments Console.WriteLine("Ans = {0}", ans); Console.ReadLine(); } } } Ex 2. Write overloaded methods volume() that compute the volume of a cube, a box, and a cylinder. Write the program to test your function. using System; namespace Overloading2 { class Program { static int volume(int x) // volume of a cube, all sides equal { return (x * x * x); } static double volume(float r, float h) // volume of a cylinder { return(3.142 * r * r * h); } static long volume(long l, long b) // volume of a box { return (l * b); } public static void Main() { Console.WriteLine("Vol of cube is {0}", volume(5)); Console.WriteLine("Vol of cylinder is {0}", volume(3.0f, 10.0f)); Console.WriteLine("Vol of box is {0}", volume(50L, 20L)); Console.ReadLine(); } } } Classes and Methods Page 13 of 13
Baixar agora