Weitere ähnliche Inhalte
Ähnlich wie C sharp chap5 (20)
Mehr von Mukesh Tekwani (20)
Kürzlich hochgeladen (20)
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