C Sharp U-II Notes
C Sharp U-II Notes
C Sharp U-II Notes
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.
General Form :
Method body ;
3. Methodname –It is a valid c# identifier. All rules of naming identifier is also applicable for
methodname.
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.
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( inti 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;
classbankaccounts
{
publicstaticvoidMain()
{
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();
}
staticintmoney( longacno, int amt, intbamt)
{ bamt = bamt - amt;
returnbamt; }
staticfloatmoney(longacno, int amt, floatbamt)
{ bamt = bamt + amt;
returnbamt; }
Dr. Vilas Hajare
staticfloatmoney(longyacno, longoacno , int amt, floatbamt)
{ bamt = bamt - amt;
returnbamt;
}
}
Virtual keyword is used to declare a base class method while performing overriding
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
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.
using System;
Console.ReadKey();
}
}
/* To find largest and smallest numberfrom jagged array */
using System;
}
Dr. Vilas Hajare
Console.Write("large :" + lar);
Console.Write("\t small : "+sm );
Console.WriteLine();
}
Console.ReadKey();
}
}
Output :
// Jagged Sorted Array in reverse order is as follows :
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.
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
What is string ?
A string is an empty space, a character, a word, or a group of words.
A string is an empty space, a character, a word, or a group of words that you want the compiler to
consider "as is", that is, not to pay too much attention to what the string is made of, unless you explicitly
ask it to. This means that, in the strict sense, you can put in a string anything you want.
Primarily, the value of a string starts with a double quote and ends with a double-quote.
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
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. Mutable strings are also referred as a dynamic
strings. Mutable string can be modify dynamically.
Dr. Vilas Hajare
The StringBuilder class supports many methods that are useful for manipulating dynamic strings. Some
of the most common methods are listed below:
StringBuilder also provides some attributes to access some properties of strings, such as:
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 strbuilderMethod
{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"); // 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.
Console.WriteLine("-------------------");
Console.WriteLine("\n Enter the array element \n");
for(inti=0;i<x;i++)
{
string s1 = Console.ReadLine();
a[i] = Convert.ToInt32(s1);
}
Console.WriteLine("------------------");
Console.WriteLine("Enter the Search element");
string s3 = Console.ReadLine();
int x2 = Convert.ToInt32(s3);
foreach(intk in a )
{
if(a[k]==x2)
Dr. Vilas Hajare
{
Console.WriteLine("------------------");
Console.WriteLine("Search Successful");
Console.WriteLine("Element {0} found at index {1}\n", x2, k );
Console.ReadLine();
}
}
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
When a class is declared sealed, it cannot be inherited, abstract classes cannot
be declared sealed.
Overloaded operators are functions with special names the keyword operator followed by the
symbol for the operator being defined.