Part 2
Part 2
METHODS IN C#
Encapsulation means binding of data fields and methods defined to work on that data of particular objects of
a class.
Example :
Class emp
{ empno = x ;
bsal = y;
Every method must be contained within a class. They are used not only to access and process data contained in
the object but also responses to any message received from other objects.
DECLARING METHODS IN C#
Methods are declared inside the body of a class, normally after the declaration of data fields.
General Form :
Method body ;
3. Methodname – It is a valid c# identifier. All rules of naming identifier is also applicable for method
name.
4. List of formal parameters – The formal parameter list is always enclosed in parentheses.
Parameter list contains variable names and types of all the values we want to give to the method as input
and separated by comma. When no input data required then include an empty set parenthesis () after the
method name.
5. Method Body- The body must be enclosed in curly braces actually describes the operations to be
performed on the data.
Nesting of Methods
A method can be called using only its name by another method of the same class is called as
nesting of methods .
Example :
using System;
class Nested
{ void Smallest ( int m, int n)
{ int small = Min(m , n) ; // Nesting
Console.Writeline(small) ;
}
int Min ( int a , int b)
{ int z = ( a< b) ? a: b ;
return (z) ;
}
}
class Testing
{ public static void Main( )
{ Nested S = new Nested( ) ;
S.Smallest (50,20) ; // Method call or invoke
Console.ReadKey();
}
}
Analysis : The class Nesting defines two methods, Smallest ( ) and Min( ). The method smallest calls the
method Min() to determine the smallest of the two numbers and then displays the result.
Note that , A method can call any no. of methods. It is also possible for a called method to call another
method.
For managing and process of passing values and getting back the results, C# employs four kinds of
parameters:
1. Value parameters 3. Output Parameters
2. Reference parameters 4. Parameter arrays
Value Parameters
By default, method parameters are passed by value . A parameter declared with no modifier is passed by
value and is called a value parameters. When a method is invoked, the values of actual parameters are
assigned to the corresponding formal parameters . The values of the parameters can changed within the method.
The value of the actual parameter that is passed by value to the method is called pass by value and not
changed by any changes made to the corresponding formal parameter within the body of the method. This is
because the methods refer to only copies of those variables when they are passed by value.
Example :
using System ;
class valueparameter
{
static void mmodify ( int m)
{ m= m+ 10; }
Public static void Main()
{ int x= 200 ;
mmodify(x);
Console.WriteLine( “ x= “ +x);
Console.ReadKey();
}
}
Reference Parameters
User can force the value parameters to be passed by reference by using keyword ref. A parameter declared
with the ref modifier is passed, is called a reference parameters. When a method is invoked, the references
of actual parameters are assigned to the corresponding formal parameters.
Reference parameter does not create a new storage location. When a formal parameter is declared as ref, the
corresponding argument in the method invocation must also be declared as ref.
Example :
void change ( ref int m) // declaration of method with reference parameter
{m= m+10 ; }
Dr. Vilas Hajare
int x= 10;
change (ref x) ; // call method with reference parameter
Note that : Reference parameters are used in a situations where we would like to change values of the variable in
the calling method. Here, the formal arguments in the called method becomes aliases to the actual arguments in
the calling method. This means that when the method is working with its own arguments, it is actually working
with the original data.
Output Parameters
Output parameters are used to pass result back to the calling method. This is achieved by declaring the
parameters with an out keyword. An Output parameters does not create a new storage location. Instead it
becomes alias to the parameter in the calling method. . When a formal parameter is declared as out, the
corresponding actual parameters in the calling method must also be declared as out.
Example :
using System ;
class ouputparameter
{ static void square ( int x, out int y)
{ y= x*x; }
Public static void Main()
{ int m; // need not to initialize output parameter
int n=2;
square(n, out m);
Console.WriteLine( “square of {0} is {1}”, n, m);
Console.ReadKey();
}
}
Output : square of 2 is 4
Parameter Arrays
We can define methods that can handle variable number of arguments using what are known as parameter arrays.
Parameter arrays are declared using the keyword params.
Example :
using System ;
class paramsparameter
{ static void Parray ( params int []x)
{ Console.Write(“ Array elements are : “);
foreach( int i in x)
Console.Write(“ “ + i);
Console.WriteLine();
}
public static void Main()
{ int [ ] a= { 20, 30, 40} ;
Parray(x) ;
Parray( ) ;
Parray(100,200) ;
}
}
using System ;
class methodoverload
{
public static void Main( )
{ Console.WriteLine( volume(10) );
Console.WriteLine( volume(2.5 F, 8) );
Console.WriteLine( volume(100L, 75, 15) );
Console.ReadKey();
}
static int volume ( int x)
{ return ( x * x * x ) ; }
static double volume ( float r, int h)
{ return (3.14 * r *r * h ) ; }
static Long volume ( long l, int b, int h)
{ return (l * b * h ) ; }
}
/* pr-11 C#.net console application to withdraw, deposit and transfer of money using
method overloading */
using System;
class bankaccounts
{
public static void Main()
{
Console.WriteLine("After Withdraw Balance amount:" + money(11111L,1000,1000));
Console.WriteLine("After Deposit Balance amount:" + money(22222L,2000,5000.0F));
Console.WriteLine("After Transfer Balance amount " +
money(33333L,22222L,1000,3000.0F));
Console.ReadKey();
}
static int money( long acno, int amt, int bamt)
{ bamt = bamt - amt;
return bamt; }
static float money(long acno, int amt, float bamt)
{ bamt = bamt + amt;
Dr. Vilas Hajare
return bamt; }
static float money(long yacno, long oacno , int amt, float bamt)
{ bamt = bamt - amt;
return bamt;
}
}
Virtual keyword is used to declare a base class method while performing overriding
HANDLING ARRAYS IN C#
An array is a group of contiguous or related data items that share a common name.
Example marks[10] represents the marks obtained by the 10 students.
The complete set of values is referred as an array, the individual values are called as elements of that
array. Index value for the first element is 0. So that Index for the last element is ( size – 1) .
All the elements of an array store in contiguous memory locations.
An arrays of following types:
One Dimensional Arrays
Two Dimensional Arrays
Variable Size Arrays ( Jagged Arrays )
CREATING AN ARRAY
Arrays must be declared and created in the computer memory before they are used.
Note that , Do not enter the size of the array in the declaration.
rno = new int[5]; // create a 5 element int array to store roll numbers
Example: int [ ] rno = new int [5]; // declare and create an array simultaneously.
The process of putting values into the array created is known as initialization. This is done using the array
subscripts. Note that Subscripts for first element is 0 and last element is (size-1) .
Or
int [ ] rno = new int [ 5] {111, 222, 333, 444, 555 }; // declaration, creation and initialization at a time.
int [ ] b;
b= a; // After assigning, both the arrays will have the same values.
ARRAY LENGTH
In c#, all arrays are class based and store the allocated size in a variable named Length.
We can access the length of an array rno using rno.Length.
It is useful in the manipulation of an array when their sizes are not known.
Example : int assize = rno.Length ;
1. Declaration of 2D-Array
Note that , Do not enter the size of the array in the declaration.
rno = new int[5,4]; // create an array of row size 5 and columnsize 4 of int type to store roll numbers
Example: int [ , ] rno = new int [5,4]; // declare and create an array simultaneously.
Example : to store roll numbers of students where there are 5 sections and in each section there are 4 students.
SYSTEM.ARRAY CLASS
Program : W.A. P. in c#.net Console application to sort a jagged array in ascending order
using System;
Console.ReadKey();
}
}
/* To find largest and smallest number from jagged array */
using System;
Console.WriteLine(" To find largest and smallest number from jagged array :");
}
Console.Write("large :" + lar);
Console.Write("\t small : "+sm );
Console.WriteLine();
}
Console.ReadKey();
}
}
Output :
// Jagged Sorted Array in reverse order is as follows :
Dr. Vilas Hajare
large :65 small : 5
large :60 small : 7
large :50 small : 10
Encapsulation is the procedure of covering up of data and functions into a single unit (called class). An
encapsulated object is often called an abstract data type. In this article let us see about it in a detailed manner.
The need of encapsulation is to protect or prevent the code (data) from accidental corruption due to the silly
little errors that we are all prone to make. In Object oriented programming data is treated as a critical element
in the program development and data is packed closely to the functions that operate on it and protects it from
accidental modification from outside functions.
Encapsulation provides a way to protect data from accidental corruption. Rather than defining the data in the
form of public, we can declare those fields as private. The Private data are manipulated indirectly by two ways.
String
Example
StringBuilder is mutable, means if create string builder object then you can perform any operation like insert, replace
or append without creating new instance for every time. It will update string at one place in memory doesn’t create new
space in memory.
Example
Handling of Strings
We can create immutable strings using string or String objects in a number of ways.
There are some techniques to handling the immutable strings:
Assigning String
string s1;
s1 = "welcome"; or string s1 =”welcome”;
Copying String
string s2 = s1; or string s2 = string.copy(s1);
Concatenating Strings
string s3 =s1 + s2; or string s3 = string.Concat(sl,s2);
Reading from Console
string sl = console.ReadLine(); .
Converting Number to String
int num = 100 ; string s1= num.Tostring();
Inserting String
string s1 = "wel";
This statement will perform case-sensitive comparison and returns integer values for different
conditions. Such as:
• If sl is equal to s2 it will return zero.
• If sl is greater than s2 it will return positive integer (1).
• If sl is less than s2 it will return negative integer(-l).
Or you can use following statement:
bool a = s2.Equals(sl);
bool b = string.Equal(sl,s2);
Above statements will return a Boolean value true (if equal) or false (if not equal).
Or you can also use the "==" operator for comparing the strings. Like as:
if (s1 == s2)
console.write (" both are equal");
In this statement, it will return a Boolean value true (if equal) or false (if not equal
Mutable String
Mutable strings are those strings, which can be modifying dynamically. This type of strings are created
using StringBuilder class. For Example:
StringBuilder sl = new StringBuilder ("welcome");
StringBuilder s2 = new StringBuilder ( );
The string sl is created with an initial size of seven characters and s2 is created as an empty string. They
can grow dynamically as more character added to them. Mutual string are also referred as a dynamic
strings. Mutable string can be modify dynamically.
The StringBuilder class supports many methods that are useful for manipulating dynamic strings. Some
of the most common methods are listed below:
Here is an example program for mutable string. To use string builder class we have to use System.Text
in the program.
Mutable string
using System.Text; // For using StringBuilder
using System;
class strMethod
{ public static void Main( )
{ StringBuilder s = new stringBui1der("C"};
console.writeLine(" stored string is :"+ s);
console.writeLine("Length of string is :"+s.Length);
s.Append("Sharp "); II appending the string s
Console.writeLine("After Append String is :"+ s);
console.writeLine("Length of string is :"+s.Length);
//space will be count in "sharp" string.
s.Insert(7,"Language"); II inserting the string at last in s
console.writeLine("After Insertion String is:"+ s);
Dr. Vilas Hajare
console.writeLine("Length of string is :"+s.Length);
int n = s.Length;
s [n] = "!";
console.writeLine (" At Last String is:"+ s);
}
}
OUTPUT:
Stored string is : C
Length of string is 1
After Append string is : CSharp
Length of string is : 7
After Insertion string is : CSharp Language
Length of string is: 15
Polymorphism:
The word polymorphism means one name many forms. In object-oriented programming
paradigm, polymorphism is often expressed as 'one interface, multiple functions'.
Static Polymorphism
The mechanism of linking a function with an object during compile time is called early binding.
It is also called static binding. C# provides two techniques to implement static polymorphism.
They are −
Function overloading
Operator overloading
Dynamic Polymorphism
C# allows you to create abstract classes that are used to provide partial class implementation
of an interface. Implementation is completed when a derived class inherits from
it. Abstract classes contain abstract methods, which are implemented by the derived class.
The derived classes have more specialized functionality.
Here are the rules about abstract classes −
You cannot create an instance of an abstract class
You cannot declare an abstract method outside an abstract class