C Sharp U-II Notes

Download as pdf or txt
Download as pdf or txt
You are on page 1of 16

UNIT-II

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

{ int empno; // data field

float bsal; // data field

public void getdata( int x , float y) // method

{ empno = x ;

bsal = y;

What is method in c# ? ( Imp)


C# is a pure Object oriented programming Language. Objects Encapsulates data , and code to manipulate that
data. The code designed to work on the data fields is known as methods in C#.

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# (Imp)


Methods are declared inside the body of a class, normally after the declaration of data fields.

General Form :

Modifiers type methodname ( formal parameter-list )

Method body ;

Method declaration consist offive parts :


1. Modifiers- Decides the nature of accessibility and the mode of application of the method. A
Method can take one or more of the modifiers such as public , private, static etc.
 Public – The method can be accessed from anywhere, including outside the class.
 Private – The method can be accessed from inside the class to which it belongs.

Dr. Vilas Hajare


 Static –The method does not operate on a specific instance of a the class
 Protected- The method can be accessed from within the class to which it belongs, or a type
derived from that class.
2. Type - type specifies the type of value the method will return. This can be a simple data type like
int, float ,doubIeetc . as well as any class type. The method does not return anything, specify the
return type is void.

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.

Nesting of Methods (Imp)

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.

Dr. Vilas Hajare


Method Parameters
The actual argument list of the invocation assigns values or variable reference to the created formal
parameters. Within the body of the method, formal parameters can be used like any other variables.

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) ;
}
}

Dr. Vilas Hajare


Output :
Array elements are : 20 30 40
Array elements are :
Array elements are : 100 200

Method Overloading ( V. V. Imp)


Definition :Creation of more than one method with the same name, but with different parameters
lists and different definitions such mechanism is called method overloading.
 Method overloading is used when methods are required to perform similar tasks but using different input
parameters.
 Overloded methods must be differ in number and/or type of parameters they take. This enables to decode
which one of the definitions to execute depending on the type and number of arguments in the method
call.
 Return type does not play any role in the overloading.
Example : find the volume of cube, cylinder, box using method overloading

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;
}
}

Sealed modifier is used to prevent Method overriding.

Virtual keyword is used to declare a base class method while performing overriding

HANDLING ARRAYS IN JAVA


What is an array ?
 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 )

One Dimensional Arrays (IMP)


A list of items can be given one variable name using only one subscript and such a variable is called
a single subscripted variable or a one dimensional array.

CREATING AN ARRAY

Arrays must be declared and created in the computer memory before they are used.

Creation of an array involves three steps :


1. Declaring the array
2. Creating memory locations
3. Putting values into the memory location
1. Declaration of 1D-Array

Syntax : type [ ] arrayname ;

Example : int [ ] counter ; float [ ] per ; int [ ] x, y ;

Note that ,Do not enter the size of the array in the declaration.

2. Creation of 1D-Arrays (Creation of Memory Locations)


C# allows us to create array usingnew operator only.
Dr. Vilas Hajare
Syntax :Arrrayname = new type[size] ;

Example: int [ ]rno; // first declaration an array

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.

3. Initialization of 1D-Arrays (Putting values into the memory location)

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) .

Syntax 1 :arrayname[ Subscript] = value ;

Example :rno[0] = 111 ;

Rno[1] = 222; etc.

Syntax 2 : type [ ] arrayname = { list of values };

Example : int [ ] rno= { 111, 222, 333, 444, 555 };

Or

int [ ]rno = new int [ 5] {111, 222, 333, 444, 555 }; // declaration, creation and initialization at a time.

Note that , it is possible to assign an array object to another .

int [ ] a= {1,2 3, 4, 5};

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 ;

Two Dimensional Arrays


 An array of one dimensional array is called as Two dimensional array. It is in the form of a Table.
 It has two subscripts, first one represents rows and another subscript represents column of a table.
 All the elements of two dimensional arrays also stores in contiguous memory locations.

1. Declaration of 2D-Array

Syntax : type [ , ] arrayname ;

Example : int [ , ] counter ; float [ , ] per ; int [ , ] x, y ;


Dr. Vilas Hajare
Note that , Do not enter the size of the array in the declaration.

2. Creation of 2D-Arrays (Creation of Memory Locations)


C# allows us to create array usingnew operator only.

Syntax :Arrrayname = new type[Rsize, Csize] ; //

Example: int [ , ] rno; // first declaration an 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.

3. Initialization of 2D-Arrays (Putting values into the memory location)

Example : to store roll numbers of students where there are 5 sections and in each section there are 4 students.

Syntax 1 :arrayname[ RSubscript , CSubscripts] = {value };


Example :rno[0,0] = 111 ;rno[0,1] = 112 ; ; rno[0,2] = 113 ; ; rno[0,3] = 114;
rno[1,0] = 211 ; rno[1,1] = 212 ; ; rno[1,2] = 213 ; ; rno[1,3] = 214;

Syntax 2 : type [ , ] arrayname = { list of values };


Example : int [ , ] rno = { {111, 112,113,114} , {201,201,203,204 } } ;
Variable –Size Array/Jagged Arrays
1. It is also called array of array.
2. A jagged array is an array whose elements are also arrays.
3. The elements of a jagged array can be of different dimensions and sizes.
4. Before you can use jagged array, its elements must be initialized.
5. The element array can be of any length.

 C# treats multidimensional array as ‘ array of arrays’.


 A two dimensional array having different lengths for each row is known as Variable –size
array or jagged array.
Example : declare a two dimensional array as:

int [ ] [ ] x = new int [3] [ ]; // three rows array


x[0] = new int[2] ; //First row has two elements
x[1] = new int [4] ; //Second row has Four elements
x[2] = new int[3] ; //Third row has three elements
 For jagged arrays each elements is within its own square brackets.

Dr. Vilas Hajare


SYSTEM.ARRAY CLASS
 Every array created by the user is automatically derived from the System.Array class.
 This class defines a number of methods and properties that can be used to manipulate arrays more
efficiently.
Methods of System.Array class and its purpose:
Method/Property Purpose
Clear( ) Sets a range of elements to empty values.
CopyTo( ) Copies elements from the source array into the destination array
GetLength( ) Gives the number of elements in a given dimension of the array.
GetValue( ) Gets the value for a given index in the array
Length ( ) Gives the length of an array
SetValue( ) Sets the value for a given index in the array
Reverse( ) Reverses the content of a one dimensional array
Sort( ) Sorts the elements in a one dimensional array

Examples :Array.sort( ) , Array.Reverse( ) ;

ARRAYLIST CLASS ( Imp)


 ArrayList class used to store a dynamically sized array of objects.
 ArrayList class methods are predefined in System.Collections namespace.
 An array List is similar to an array , except that it has the ability to grow dynamically. We can create an
array list as follows:
ArrayList cities = new ArrayList(30) ; // It creates cities with a capacity to store thirty objects.
ArrayList cities = new ArrayList() ; // Defaults, creates cities with a capacity to store Sixteen objects.
cities.Capacity = 20 ; //
int n = cities.count ; // count actual numbers of array objects

Methods and Properties supported by the ArrayList class are as follows:


Method/Property Purpose
Add( ) Adds an object to a list
Clear ( ) Removes all the elements from the list
Contains( ) Determines if an element is in the list
CopyTo( ) Copies a list to another
Insert ( ) Inserts an element into the list
Remove ( ) Remove the first occurrence of an element
RemoveAT( ) Remove the elements at the specified place
RemoveRange( ) Removes a range of elements in the list
Sort() Sorts the Elements
Capacity Gets or sets the number of elements in the list
Count Gets the number of elements currently in the list.

Dr. Vilas Hajare


Program : W.A. P. in c#.net Console application to sort a jagged array in ascending order

using System;

public class sortrevjagarray


{
public static void Main()
{
Int32 k = 0;
const Int32 row = 3;
Int32[][] jagarr = new Int32[row][];
jagarr[0] = new Int32[5] { 10, 57, 34, 65, 5 };
jagarr[1] = new Int32[3] { 7, 50, 15 };
jagarr[2] = new Int32[4] { 50, 20, 40, 10 };

Console.WriteLine(" // Jagged Sorted Array in reverse order is as follows :");

for (k = 0; k < 3; k++)


{ Array.Sort(jagarr[k]);
Array.Reverse(jagarr[k]);
Console.Write("{");
foreach (int x in jagarr[k])
{ Console.Write(" " + x);
}
Console.Write(" } \n");
}

Console.ReadKey();

}
}
/* To find largest and smallest numberfrom jagged array */
using System;

public class larsmalljagarray


{
public static void Main()
{
Int32 k = 0, lar ,sm;
const Int32 row = 3;
Int32[][] jagarr = new Int32[row][];
jagarr[0] = new Int32[5] { 10, 57, 34, 65, 5 };
jagarr[1] = new Int32[3] { 7, 60, 15 };
jagarr[2] = new Int32[4] { 50, 20, 40, 10 };

Console.WriteLine(" To find largest and smallest numberfrom jagged array :");

for (k = 0; k < 3; k++)


{
lar = jagarr[k][0]; sm = jagarr[k][0] ;
foreach (int x in jagarr[k])
{
lar = Math.Max(lar, x);
sm = Math.Min(sm, x);

}
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

What is Encapsulation ? ( V.V. Imp)

 The wrapping up of data under a single unit is called as Encapsulation

 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.

There are two types of string in C#:


1. Immutable strings
2. Mutable strings
 The immutable strings are can't be modify while mutable strings are modifiable.C# also supports a feature
of regular expression that can be used for complex strings manipulations and pattern matching.

Dr. Vilas Hajare


String is immutable, Immutable means if you create string object then you cannot modify it and It always
create new object of string type in memory.

Example

string strMyValue = "Hello Visitor";


// create a new string instance instead of changing the old one
strMyValue += "How Are";
strMyValue += "You ??";

What is mutable string ? ( V. Imp)

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

StringBuilder sbMyValue = new StringBuilder("");


sbMyValue.Append("Hello Visitor");
sbMyValue.Append("How Are You ??");
string strMyValue = sbMyValue.ToString();

Handling of immutable 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"; orstring s1 =”welcome”;
Copying String
string s2 = s1;or string s2 = string.copy(s1);
Dr. Vilas Hajare
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";
string s2 = s1.Insert(3,"come");// s2 = welcome
string s3 = s1.Insert(3,"don");/ / s3 = we1don;
Comparing Strings
int n = string.Compare(sl,s2);

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.

Dr. Vilas Hajare


s.Insert(7,"Language"); // inserting the string at last in s
Console.WriteLine("After Insertion String is:"+ s);
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

/* W A P in C# to search a number from array using liner search method of array */


CODING:-
using System;
classlinerSearch
{
publicstaticvoidMain()
{
Int[] a = newint[100];
Console.WriteLine("Enter the number of elements you want to add in the array ?");
string s = Console.ReadLine();
int x = Convert.ToInt32(s);

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();
}
}

Console.WriteLine("Entered element not found.SearchUnseccessful");


Console.ReadLine();
}
}

Polymorphism: ( V.V. Imp)


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
 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.

Dr. Vilas Hajare

You might also like