SlideShare ist ein Scribd-Unternehmen logo
1 von 13
Downloaden Sie, um offline zu lesen
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
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
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
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
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
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
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
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
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
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
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
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
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

Weitere ähnliche Inhalte

Was ist angesagt?

Visula C# Programming Lecture 6
Visula C# Programming Lecture 6Visula C# Programming Lecture 6
Visula C# Programming Lecture 6Abou Bakr Ashraf
 
C# Summer course - Lecture 3
C# Summer course - Lecture 3C# Summer course - Lecture 3
C# Summer course - Lecture 3mohamedsamyali
 
Intake 38 data access 5
Intake 38 data access 5Intake 38 data access 5
Intake 38 data access 5Mahmoud Ouf
 
C# Summer course - Lecture 4
C# Summer course - Lecture 4C# Summer course - Lecture 4
C# Summer course - Lecture 4mohamedsamyali
 
Introduction to objective c
Introduction to objective cIntroduction to objective c
Introduction to objective cMayank Jalotra
 
Intake 38 data access 3
Intake 38 data access 3Intake 38 data access 3
Intake 38 data access 3Mahmoud Ouf
 
C basic questions&amp;ansrs by shiva kumar kella
C basic questions&amp;ansrs by shiva kumar kellaC basic questions&amp;ansrs by shiva kumar kella
C basic questions&amp;ansrs by shiva kumar kellaManoj 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 210The Ring programming language version 1.9 book - Part 98 of 210
The Ring programming language version 1.9 book - Part 98 of 210Mahmoud Samir Fayed
 
Resource wrappers in C++
Resource wrappers in C++Resource wrappers in C++
Resource wrappers in C++Ilio Catallo
 
SPF Getting Started - Console Program
SPF Getting Started - Console ProgramSPF Getting Started - Console Program
SPF Getting Started - Console ProgramHock Leng PUAH
 
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 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
 

Was ist angesagt? (20)

Visula C# Programming Lecture 6
Visula C# Programming Lecture 6Visula C# Programming Lecture 6
Visula C# Programming Lecture 6
 
C# Summer course - Lecture 3
C# Summer course - Lecture 3C# Summer course - Lecture 3
C# Summer course - Lecture 3
 
Intake 38 data access 5
Intake 38 data access 5Intake 38 data access 5
Intake 38 data access 5
 
Intake 38 6
Intake 38 6Intake 38 6
Intake 38 6
 
C# Summer course - Lecture 4
C# Summer course - Lecture 4C# Summer course - Lecture 4
C# Summer course - Lecture 4
 
Introduction to objective c
Introduction to objective cIntroduction to objective c
Introduction to objective c
 
C++ tutorials
C++ tutorialsC++ tutorials
C++ tutorials
 
Java execise
Java execiseJava execise
Java execise
 
Intake 38 data access 3
Intake 38 data access 3Intake 38 data access 3
Intake 38 data access 3
 
C basic questions&amp;ansrs by shiva kumar kella
C basic questions&amp;ansrs by shiva kumar kellaC basic questions&amp;ansrs by shiva kumar kella
C basic questions&amp;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 210The Ring programming language version 1.9 book - Part 98 of 210
The Ring programming language version 1.9 book - Part 98 of 210
 
Templates
TemplatesTemplates
Templates
 
Resource wrappers in C++
Resource wrappers in C++Resource wrappers in C++
Resource wrappers in C++
 
java tutorial 2
 java tutorial 2 java tutorial 2
java tutorial 2
 
SPF Getting Started - Console Program
SPF Getting Started - Console ProgramSPF Getting Started - Console Program
SPF Getting Started - Console Program
 
Intake 37 6
Intake 37 6Intake 37 6
Intake 37 6
 
Intake 37 5
Intake 37 5Intake 37 5
Intake 37 5
 
java tutorial 3
 java tutorial 3 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 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 -2Introduction to c ++   part -2
Introduction to c ++ part -2
 

Andere mochten auch

Exception handling in asp.net
Exception handling in asp.netException handling in asp.net
Exception handling in asp.netNeelesh Shukla
 
Exception Handling Mechanism in .NET CLR
Exception Handling Mechanism in .NET CLRException Handling Mechanism in .NET CLR
Exception Handling Mechanism in .NET CLRKiran Munir
 
CSharp Presentation
CSharp PresentationCSharp Presentation
CSharp PresentationVishwa Mohan
 
EVALUATION OF PROCESSES PARAMETER AND MECHANICAL PROPERTIES IN FRICTION STIR ...
EVALUATION OF PROCESSES PARAMETER AND MECHANICAL PROPERTIES IN FRICTION STIR ...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 vbError handling and debugging in vb
Error handling and debugging in vbSalim M
 
Data Structure In C#
Data Structure In C#Data Structure In C#
Data Structure In C#Shahzad
 
Presentation on visual basic 6 (vb6)
Presentation on visual basic 6 (vb6)Presentation on visual basic 6 (vb6)
Presentation on visual basic 6 (vb6)pbarasia
 
Introduction to visual basic programming
Introduction to visual basic programmingIntroduction to visual basic programming
Introduction to visual basic programmingRoger Argarin
 
Basic controls of Visual Basic 6.0
Basic controls of Visual Basic 6.0Basic controls of Visual Basic 6.0
Basic controls of Visual Basic 6.0Salim M
 

Andere mochten auch (12)

Debugging in .Net
Debugging in .NetDebugging in .Net
Debugging in .Net
 
Exception handling in asp.net
Exception handling in asp.netException handling in asp.net
Exception handling in asp.net
 
Exception Handling Mechanism in .NET CLR
Exception Handling Mechanism in .NET CLRException Handling Mechanism in .NET CLR
Exception Handling Mechanism in .NET CLR
 
Debugging
DebuggingDebugging
Debugging
 
CSharp Presentation
CSharp PresentationCSharp Presentation
CSharp Presentation
 
EVALUATION OF PROCESSES PARAMETER AND MECHANICAL PROPERTIES IN FRICTION STIR ...
EVALUATION OF PROCESSES PARAMETER AND MECHANICAL PROPERTIES IN FRICTION STIR ...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 vbError handling and debugging in vb
Error handling and debugging in vb
 
Programming in c#
Programming in c#Programming in c#
Programming in c#
 
Data Structure In C#
Data Structure In C#Data Structure In C#
Data Structure In C#
 
Presentation on visual basic 6 (vb6)
Presentation on visual basic 6 (vb6)Presentation on visual basic 6 (vb6)
Presentation on visual basic 6 (vb6)
 
Introduction to visual basic programming
Introduction to visual basic programmingIntroduction to visual basic programming
Introduction to visual basic programming
 
Basic controls of Visual Basic 6.0
Basic controls of Visual Basic 6.0Basic controls of Visual Basic 6.0
Basic controls of Visual Basic 6.0
 

Ähnlich wie C sharp chap5

Java căn bản - Chapter7
Java căn bản - Chapter7Java căn bản - Chapter7
Java căn bản - Chapter7Vince Vo
 
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
 
Ap Power Point Chpt4
Ap Power Point Chpt4Ap Power Point Chpt4
Ap Power Point Chpt4dplunkett
 
OBJECT ORIENTED PROGRAMING IN C++
OBJECT ORIENTED PROGRAMING IN C++ OBJECT ORIENTED PROGRAMING IN C++
OBJECT ORIENTED PROGRAMING IN C++ Dev Chauhan
 
Presentation 3rd
Presentation 3rdPresentation 3rd
Presentation 3rdConnex
 
9781439035665 ppt ch08
9781439035665 ppt ch089781439035665 ppt ch08
9781439035665 ppt ch08Terry Yoast
 
I assignmnt(oops)
I assignmnt(oops)I assignmnt(oops)
I assignmnt(oops)Jay Patel
 
C++ largest no between three nos
C++ largest no between three nosC++ largest no between three nos
C++ largest no between three noskrismishra
 
Microsoft dynamics ax 2012 development introduction part 2/3
Microsoft dynamics ax 2012 development introduction part 2/3Microsoft dynamics ax 2012 development introduction part 2/3
Microsoft dynamics ax 2012 development introduction part 2/3Ali Raza Zaidi
 
CLASSES AND OBJECTS IN C++ +2 COMPUTER SCIENCE
CLASSES AND OBJECTS IN C++ +2 COMPUTER SCIENCECLASSES AND OBJECTS IN C++ +2 COMPUTER SCIENCE
CLASSES AND OBJECTS IN C++ +2 COMPUTER SCIENCEVenugopalavarma Raja
 
C++ beginner's guide ch08
C++ beginner's guide ch08C++ beginner's guide ch08
C++ beginner's guide ch08Jotham Gadot
 
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
 

Ähnlich wie C sharp chap5 (20)

Java căn bản - Chapter7
Java căn bản - Chapter7Java 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 IIChapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part II
 
Introduction to C++
Introduction to C++Introduction to C++
Introduction to C++
 
Ap Power Point Chpt4
Ap Power Point Chpt4Ap Power Point Chpt4
Ap Power Point Chpt4
 
OBJECT ORIENTED PROGRAMING IN C++
OBJECT ORIENTED PROGRAMING IN C++ OBJECT ORIENTED PROGRAMING IN C++
OBJECT ORIENTED PROGRAMING IN C++
 
OOC MODULE1.pptx
OOC MODULE1.pptxOOC MODULE1.pptx
OOC MODULE1.pptx
 
Presentation 3rd
Presentation 3rdPresentation 3rd
Presentation 3rd
 
Class and object
Class and objectClass and object
Class and object
 
9781439035665 ppt ch08
9781439035665 ppt ch089781439035665 ppt ch08
9781439035665 ppt ch08
 
My c++
My c++My c++
My c++
 
I assignmnt(oops)
I assignmnt(oops)I assignmnt(oops)
I assignmnt(oops)
 
C++ largest no between three nos
C++ largest no between three nosC++ largest no between three nos
C++ largest no between three nos
 
CS3391 -OOP -UNIT – II NOTES FINAL.pdf
CS3391 -OOP -UNIT – II  NOTES FINAL.pdfCS3391 -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 plusThe smartpath information systems  c plus plus
The smartpath information systems c plus plus
 
Unit3
Unit3Unit3
Unit3
 
Microsoft dynamics ax 2012 development introduction part 2/3
Microsoft dynamics ax 2012 development introduction part 2/3Microsoft 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 SCIENCECLASSES AND OBJECTS IN C++ +2 COMPUTER SCIENCE
CLASSES AND OBJECTS IN C++ +2 COMPUTER SCIENCE
 
C++ beginner's guide ch08
C++ beginner's guide ch08C++ 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 JavaCIS 1403 lab 3 functions and methods in Java
CIS 1403 lab 3 functions and methods in Java
 
Java class
Java classJava class
Java class
 

Mehr von Mukesh Tekwani

Computer Science Made Easy - Youtube Channel
Computer Science Made Easy - Youtube ChannelComputer Science Made Easy - Youtube Channel
Computer Science Made Easy - Youtube ChannelMukesh Tekwani
 
The Elphinstonian 1988-College Building Centenary Number (2).pdf
The Elphinstonian 1988-College Building Centenary Number (2).pdfThe Elphinstonian 1988-College Building Centenary Number (2).pdf
The Elphinstonian 1988-College Building Centenary Number (2).pdfMukesh Tekwani
 
ISCE-Class 12-Question Bank - Electrostatics - Physics
ISCE-Class 12-Question Bank - Electrostatics  -  PhysicsISCE-Class 12-Question Bank - Electrostatics  -  Physics
ISCE-Class 12-Question Bank - Electrostatics - PhysicsMukesh Tekwani
 
Hexadecimal to binary conversion
Hexadecimal to binary conversion Hexadecimal to binary conversion
Hexadecimal to binary conversion Mukesh Tekwani
 
Hexadecimal to decimal conversion
Hexadecimal to decimal conversion Hexadecimal to decimal conversion
Hexadecimal to decimal conversion Mukesh Tekwani
 
Hexadecimal to octal conversion
Hexadecimal to octal conversionHexadecimal to octal conversion
Hexadecimal to octal conversionMukesh Tekwani
 
Gray code to binary conversion
Gray code to binary conversion Gray code to binary conversion
Gray code to binary conversion Mukesh Tekwani
 
Decimal to Binary conversion
Decimal to Binary conversionDecimal to Binary conversion
Decimal to Binary conversionMukesh Tekwani
 
Video Lectures for IGCSE Physics 2020-21
Video Lectures for IGCSE Physics 2020-21Video Lectures for IGCSE Physics 2020-21
Video Lectures for IGCSE Physics 2020-21Mukesh Tekwani
 
Refraction and dispersion of light through a prism
Refraction and dispersion of light through a prismRefraction and dispersion of light through a prism
Refraction and dispersion of light through a prismMukesh Tekwani
 
Refraction of light at a plane surface
Refraction of light at a plane surfaceRefraction of light at a plane surface
Refraction of light at a plane surfaceMukesh Tekwani
 
Atom, origin of spectra Bohr's theory of hydrogen atom
Atom, origin of spectra Bohr's theory of hydrogen atomAtom, origin of spectra Bohr's theory of hydrogen atom
Atom, origin of spectra Bohr's theory of hydrogen atomMukesh Tekwani
 
Refraction of light at spherical surfaces of lenses
Refraction of light at spherical surfaces of lensesRefraction of light at spherical surfaces of lenses
Refraction of light at spherical surfaces of lensesMukesh Tekwani
 
ISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGE
ISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGEISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGE
ISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGEMukesh Tekwani
 

Mehr von Mukesh Tekwani (20)

Computer Science Made Easy - Youtube Channel
Computer Science Made Easy - Youtube ChannelComputer 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).pdfThe Elphinstonian 1988-College Building Centenary Number (2).pdf
The Elphinstonian 1988-College Building Centenary Number (2).pdf
 
Circular motion
Circular motionCircular motion
Circular motion
 
Gravitation
GravitationGravitation
Gravitation
 
ISCE-Class 12-Question Bank - Electrostatics - Physics
ISCE-Class 12-Question Bank - Electrostatics  -  PhysicsISCE-Class 12-Question Bank - Electrostatics  -  Physics
ISCE-Class 12-Question Bank - Electrostatics - Physics
 
Hexadecimal to binary conversion
Hexadecimal to binary conversion Hexadecimal to binary conversion
Hexadecimal to binary conversion
 
Hexadecimal to decimal conversion
Hexadecimal to decimal conversion Hexadecimal to decimal conversion
Hexadecimal to decimal conversion
 
Hexadecimal to octal conversion
Hexadecimal to octal conversionHexadecimal to octal conversion
Hexadecimal to octal conversion
 
Gray code to binary conversion
Gray code to binary conversion Gray code to binary conversion
Gray code to binary conversion
 
What is Gray Code?
What is Gray Code? What is Gray Code?
What is Gray Code?
 
Decimal to Binary conversion
Decimal to Binary conversionDecimal to Binary conversion
Decimal to Binary conversion
 
Video Lectures for IGCSE Physics 2020-21
Video Lectures for IGCSE Physics 2020-21Video 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 prismRefraction 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 surfaceRefraction of light at a plane surface
Refraction of light at a plane surface
 
Spherical mirrors
Spherical mirrorsSpherical mirrors
Spherical mirrors
 
Atom, origin of spectra Bohr's theory of hydrogen atom
Atom, origin of spectra Bohr's theory of hydrogen atomAtom, 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 lensesRefraction 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 - WEIGHTAGEISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGE
ISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGE
 
Cyber Laws
Cyber LawsCyber Laws
Cyber Laws
 
XML
XMLXML
XML
 

Kürzlich hochgeladen

mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...Pooja Nehwal
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 

Kürzlich hochgeladen (20)

mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 

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