We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 68
Properties in C#.Net (smart accessors/mutator (getter and setter): a new member)
Properties are named members of classes, structures, and interfaces. Member variables
or methods in a class or structures are called Fields. Properties are an extension of fields and are
accessed using the same syntax. They use accessors through which the values of the private
fields can be read, written or manipulated.
Properties do not name the storage locations. Instead, they have accessors that read,
write, or compute their values.
For example, let us have a class named Student, with private fields for age, name, and code. We
cannot directly access these fields from outside the class scope, but we can have properties for
accessing these private fields.
Note: These are a smart solution to replace accessor and mutator methods of a class in
OOP language.
Accessors:
The accessor of a property contains the executable statements that helps in getting (reading or
computing) or setting (writing) the property. The accessor declarations can contain a get
accessor, a set accessor, or both. For example:
W Declare a Code property of type string:
public string Code
{
c
retum code;
set
{
code = value;
}
}
1 Declare a Name property of type string:
public string Name
{
Bet
{
retum name;
i
set
name = value;
}
}
M Declare a Age property of type int:
public int Age
{
get
{
return age;
43‘Property name and deta member names must not be same. In above example Cade and code ae two diferent variables.
2) get, set and value ae keywords.
Example:
using System;
System.Collections.Generic;
using System.Ling;
using System. Text;
namespace ConsoleApplication2
{
class Student
{
private double m;
public double Marks
{
get {
return m;
}
set {
m= value;
}
)
}
class Program
{
static void Main()
{
Student t = new Student();
t.Marks = 459;
System.Console.WriteLine("Student marks are: " + t.Marks);
System.Console.ReadLine();
}
}
}‘Same program without using properties (i.e. using accessor and mutator methods)/ Traditional
without Properties:
using System;
namespace ConsoleApplication2
Sas Sudent
‘ private double m;
public void InputMarks(int x)
; m=x;
}
public double OutputMarks()
{
return m;
i
class Program
{
static void Main()
{
‘Student t = new Student();
tInputMarks(459);
System.Console. WriteLine("Student marks are: " + t,OutputMarks());
System.Console.ReadLine();
}
}
}
‘Types or categories of properties in C#.net:
1) Read-write property.
2) Read-only property.
3) Write-only property
4) Auto-implemented property.
1)Read-write property means properties having both get and set blocks.
2)Read-only property means properties having only get block.
eg.
class Student
{
private double m=99;
public double Marks
1 m= value;
ny
}
}
class Program
{
static void Main(){
Student t= new Student();
I-Marks = 459;
System.Console, WriteLine("Student marks are:
System.Console.ReadLine();
}
}
3)Write-only property; properties having only set block.
clas Student
{ Private double m;
mete double Marks.
Mget
mK
return m;
n
set
{
m= value;
}
}
}
class Program
static void Main()
‘Student t = new Student();
t-Marks = 459;
System.Console. WriteLine("Student marks are: * + Marks);
System.Console.ReadLine();
}
}
4) Auto implemented property
The patterns you see here, where a property encapsulates a property
withget and set accessors, without any other logic is common. It is more code than we should
have to write for such a common scenario. That’s why C# 3.0 introduced a new syntax for a
property, called anauto-implemented property, which allows you to create properties
without ger and ser accessor implementations. These may be further classified as read-write auto
implemented, read-only auto implemented, write-only auto implemented properties. Below
example shows how to add auto-implemented properties to a class.
using System; ;
using System Collections. Generic;
using System.Ling;
using System. Text;
namespace ConsoleApplication?
class Student
{
public double Marks
Bet;
set;
46}
}
class Program
{
static void Main()
‘Student t= new Student();
t-Marks = 459;
‘System.Console. WriteLine("Student marks are: "+ ‘t.Marks);
‘System.Console.ReadLine();
}
}
}
Notice how the get and set accessors in above example do not have implementations. In
an auto-implemented property, the C# compiler creates the backing store field behind the scenes,
giving the same logic that exists with traditional properties, but saving you from having to use all
of the syntax of the traditional Property. As you can see in the Main method, the usage of an
auto-implemented property is exactly the same as traditional properties, which you learned about
in previous sections.Arrays in C#.Net
An array stores a fixed-size sequential collection of elements of the same type. An array is used
to store a collection of data, but it is often more useful to think of an array as a collection of
variables of the same type stored at contiguous memory locations.
Declaring Arrays
To declare an array in C#, you can use the following syntax:
datatype[] arrayName;
where,
* datatype is used to specify the type of elements in the array.
* [J specifies the rank of the array. The rank specifies the size of the array.
* arrayName specifies the name of the array.
For example,
double[] balance;
Initializing an Array
Declaring an array does not initialize the array in the memory. When the array variable is
initialized, you can assign values to the array.
Array is a reference type, so you need to use the new keyword to create an instance of the array.
For example,
double{] balance =new double[10];
Assigning Values to an Array
‘You can assign values to individual array elements, by using the index number, like:
double{] balance =newdouble[10];
balance{0}=4500.
‘You can assign values to the array at the time of declaration, as shown:
double[] balance ={2340.0,4523.69,3421.0};
‘You can also create and initialize an array, as shown:
int{] marks =newint[5]{99,98,92,97,95};
You may also omit the size of the array, as shown:
int{] marks =newint{] {99,98,92,97,95};
You can copy an array variable into another target array variable. In such case, both the target
and source point to the same memory location:
int{} marks =newint{] {99,98,92,97,95};
int{] score = marks;
When you create an array, C# compiler implicitly initializes each array element to a default
value depending on the array type. For example, for an int array all elements are initialized to 0.
Accessing Array Elements
48An element is accessed by indexing the array name. This is done by placing the index of the
element within square brackets after the name of the array. For example,
double salary = balance[9];
The following example, demonstrates the above-mentioned concepts declaration, assignment,
and accessing arrays:
usingSystem;
namespaceArrayApplication
{
classMyArray
{
staticvoidMain(string[] args)
int{]_n =new int{10];/* n is an array of 10 integers */
int ij;
/* initialize elements of array n */
for i =0; i <10; i++)
{
}
/* output each array element's value */
for(j =0; j <10; j++)
Console. WriteLine("Element[{0}] = {1}",j, nfj]);
}
Console.ReadKey();
}
}
}
When the above code is compiled and executed, it produces the following result:
Element{0] = 100
Element{1] = 101
Element{2] = 102
Element{3] = 103
Element{4] = 104
Element{5] = 105
Element{6] = 106
Element{7] = 107
Element(8] = 108
Element{9] = 109
Using the foreach LoopIn the previous example, we used a for loop for accessing cach array element. You can also use
a foreach statement to iterate through an array.
usingSystem; ae
namespaceArrayA pplication
Sean
| siovoidMain( string] args)
ie n=new int[10]; /* n is an array of 10 integers */
/* initialize elements of array n */
for(int i =0; i <10; i++)
{
}
/* output each array element's value */
foreach(int j inn )
{
int i =j-100;
Console. WriteLine("Element[ {0}] = {1}", i,j);
nfiJ= i +100;
}
Console.ReadKey();
}
}
J
When the above code is compiled and executed, it produces the following result:
Element[0] = 100
Element{1] = 101
Element{2] = 102
Element[3] = 103
Element[4] = 104
Element{5] = 105
Element{6] = 106
Element{7] = 107
Element{8] = 108
Element{9] = 109
Note:
1)In C#, dimension is before variable name (array name) eg.
double{] ar=new double{ 10];
50Note: double arf] ={10,20,30}; // Error in C# but it was possible(both side) in Java
2)In Cit, 2D arrays are comma separated e.g.
doublef,] ar=newdouble[ 10,5];
3) In Cit, Jagged arrays are multiple brackets eg.
double[][Jar=newdouble[ 10] [];
4) Jegged array can serve rectangular array but vice-versa not possible.
5) In Jagged array, at time of declaration of an array second dimension(column size) must not be specified.
ie. double[] []ar=newdouble[10] [6]; // is an ERROR
6) One more difference between Non-jagged and Jagged array is use of foreach loop to traverse. See program
code below:
int[,] ar = new int[2, 3];
0, 0] = 1;
ar[0, 1] = 2;
ar[0, a= 3;
foreach (inti i in ar)// bez non jagged is a collection of items
System.Console. WriteLine(i);
// foreach also replaces two for loops here
System.Console.ReadKey();
MMagged array
int{][] ar2 = new int[2][];// column size must be empty here and then must be initialized
/fin next lines
ar2[0][0] = 1;
ar2[0][1] = 2;
ar2[0][2] = 3;
ar2[1][0] = 4;
ar2[1][1] = 5;
ar2[1][2] = 6;
1/ foreach (int i in ar2) // foreach loop is an error bez column size may vary
//’bcz non jagged is not a collection of items but a collection of arrays
System.Console. WriteLine(i);
System.Console.ReadKey();Ci Arrays
There are following few important concepts related to array which should be clear to a C#
Concept Description
Multi-dimensional arrays C# supports multidimensional arrays. The simplest
form of the multidimensional array is the two-
dimensional array.
Jagged arrays C# supports multidimensional arrays, which are arrays
of arrays.
Passing arrays to functions You can pass to the function a pointer to an array by
specifying the array's name without an index.
Param arrays This is used for passing unknown number of
parameters to a function.
LINO Sub-namespace Defined in System namespace i.e. using System.Linq;,
it provides various methods for working with arrays
like Min(), Max(), Average() etc.
The Array Class Defined in System namespace, it is the base class to
all arrays, and provides various properties and
methods for working with arrays.
C# allows multidimensional arrays. Multi-dimensional arrays are also called rectangular array.
You can declare a 2-dimensional array of strings as:
string [,] names;
or, a 3-dimensional array of int variables as:
int [,,] m;
Two-Dimensional Arrays
The simplest form of the multidimensional array is the 2-dimensional array. A 2-dimensional
array is a list of one-dimensional arrays.
A 2-dimensional array can be thought of as a table, which has x number of rows and y number
of columns. Following is a 2-dimensional array, which contains 3 rows and 4 columns:Thus, every element in the array a is identifi
ied by an element name of the form al i, j ], where a
is the name of the array,
and i and j are the subscripts that uniquely identify each element in
array a.
Initializing Two-Dimensional Amays
Multidimensional arrays may be initialized by specifying bracketed values for each row. The
Following array is with 3 rows and each row has 4 columns.
int [,] a = new int [3,4] {
{0, 1, 2,3}, /* initializers for row indexed by 0 */
{4,5,6,7}, /* initializers for row indexed by 1 */
{8,9, 10,11} /* initializers for row indexed by 2 */
‘
Accessing Two-Dimensional Array Elements
An element in 2-dimensional array is accessed by using the subscripts. That is, row index and
column index of the array. For example,
int val = a[2,3];
The above statement takes 4th element from the 3rd row of the array. You can verify it in the
above diagram. Let us check the program to handle a two dimensional array:
using System;
namespace ArrayApplication
class MyArray
static void Main(string[] args)
{
/* an array with 5 rows and 2 columns*/
int[,] a = new int[5, 2] {{0,0}, {1,2}, {2,4}, {3,6}, {4.8} };
int i, j;
/* output each array element's value */
for (i= 0; i <5; i++)
; for G = 0; 5 <2; j++)
Console. WriteLine("a[{0},{1}] = {2}", i,j, alid)s
Console.ReadKey();
53}
}
}
When the above code is compiled and executed, it produces the following result:
[0,0]: 0
af0,
(1,0): 1
aft,1]:2
(2,0): 2
af2,1]: 4
[3,0]: 3
[3,1]: 6
af4,0]: 4
af4,1]: 8
Jagged Arrays
A Jagged array is an array of arrays. You can declare a jagged array namedscores of type int as:
int [][] scores;
Declaring an array, does not create the array in memory. To create the above array:
int[}{] scores = new int[5][];
for (int i = 0; i < scores.Length; i++)
scores[i] = new int{4];
You can initialize a jagged array as:
int[][] scores = new int[2][] {new int[]{92,93,94},new int[]{85,66,87,88} };
Where, scores is an array of two arrays of integers - scores[0] is an array of 3 integers and
scores[1] is an array of 4 integers.
Example
The following example illustrates using a jagged array:
using System;
namespace ArrayApplication
class MyArray
{
static void Main(string[] args)
i
/* a jagged array of 5 array of integers*/ianaay i new int{][] {new int{]}{0,0},new int{]{1,2},new int[]{2,4).new int[]{ 3, 6 }, new
int i, j;
/* output each array element's value */
for (i= 0; i <5; i++)
{
for (j = 0; j <2; j++)
{
; Console. WriteLine("al {0} ][{1}] = {2}", i, j, alii);
}
Console.ReadKey();
}
}
}
Jagged array Vs Non-jagged arrays
Means arrays having variable number of columns in each rows example array to record
contact numbers of 500 employees who are having variable number of contact numbers. These
are storage efficient and also called non-rectangular arrays. Whereas, arrays of fixed size
columns are called rectangular arrays.
Simple example of Jagged-array:
class ArrayJA
{
public static void Main(string{] args)
{
int r, ¢ i, j5
System.Console. WriteLine("enter number of rows of an array");
1 = System.Convert. ToInt32(System.Console.ReadLine());
// Partial array declaration with row number info only
int] a = new int(r]0];
110 enter variable columns for each rows
for (i= 0; i <1; i++)
System.Console.WriteLine("enter number of columns for a" + i +] th row:");
c= System.Convert.Toint32(System.Console.ReadLine());
afi] = new int{c];
‘System.Console. WriteLine(“enter elements of array");
for (i= 0; 1 (T[] array, int index)
{
if (index < @)
{
// Tf the index is negative, it represents the bitwise
// complement of the next larger element in the array.
Wy
index = ~index;
Console.Write("Not found. Sorts between: ");
if (index ®) .
Console.Write("beginning of array and ");
else :
Console.wWrite("{@} and ", array[index - 1]);
if (index == array.Length) :
Console.WriteLine("end of array.");
else : i
Console.WriteLine("{@}.", array[index]);
else
{ : Seed
Console.WriteLine("Found at index {0}.", index);
}
Mu
Output:(ieee
Deinonychus
irre
Brest
eaters)
ietitretioes
BinarySearch for ’Coelophysis’
Not found. Sorts between: Amargasaurus and Deinonychus.
UR e) lee eS Ty ty
Geter Mtoe ht ahh
using System;
using System.Collections.Generic;
using System.Ling;
using System.Text;
namespace ConsoleApplication14
{
class Employee
{
public string Name;
public int Age;
class Program
{
static void Main(string[] args)
{ _
inti;
Employee[] emp = new Employee(3);
for (i= 0; 1<3; i++)
{
emp[i] = new Employee);
for (i= 0; 1<3; i++)
{
System.Console.WriteLine("'enter name and age");
empli].Name = System.Console.ReadLine();
empfi].Age = Convert. Tolnt32(System.Console.ReadLine());
}
/I sort array by name using Array class
65Array.Sort(emp, delegate(Employee emp1, Employee emp2)
{
return emp1.Name.CompareTo(emp2.Name);
Ds
i/Same sorting can be done by defining explicit logic of Bubble sort
// write array (output: Bunny23 Susan20 Tina25)
foreach (Employee e in emp) Console. Write(e.Name + e.Age + wry;
Console.ReadLine();
}
}
}C# Array Operations using System.Ling
In C#, we have the System.Ling namespace that provides different methods to perform various
operations in an array (by default 1D array). For example,
PeeeSe CT
ides us various methods to use in an array
Renee A
Pee eta
ree aeorti
static void Main(stringf] args) {
int{] numbers = (51, 1, 3, 4, 98};
Mes enters
Console. WriteLine("Smallest Element: " + numbers.Min());
Max() returns the largest number in array
COOMA Mt @ etrceraoaurreaesnitnivor an ey O)H
Ceo BL 0
Meese sense
Seen ed
In the above example,
numbers.Min() - returns the smallest number in an array, 1
numbers.Max() - returns the largest number in an array, 98
Example: Find the Average of an Array
Tena Cn
REA een cknamespace ArrayFunction {
class Program {
PROC ROOM ENE
int|] numbers = {30, 31, 94, 86, 55};
RR eva ets
Rete ssrestic tgs
RRR amano uterus nee aes
Peete sett 3
MeN Seeet ny ec(e
eR aS Bn Warts NT 5
Perens to
eRe BW reo lee Wier Wace een ee Werte)
Console.ReadLineQ;
Pees
In the above example, we have used
numbers.Sum() to get the sum of all the elements of the array
numbers.Count() to get the total number of element present inside the array
Note: It is compulsory to.-—use__the System.Linq namespace while
using MinQ, Max(), Sum(), Count(), and Average() methods.Param Arrays (params keyword)
At times, while declaring a method, you are not sure of the number of arguments passed as a
parameter. C# params arrays (or parameter arrays) come into help at such times. params is used
to pass variable number of parameters(even array) while calling same function( even variable
types if Object is used).The following example demonstrates this:
class c1
{
public int f1(params int[] arr)
{
int sum = @;
foreach (int i in arr)
{ sum += i; }
return sum;
}
static void Main(string[] args)
it
int r;
1 ob1 = new c1();
r = ob1.#1(10, 20);
Console.WriteLine("The sum is: {@}", 7);
Pr = ob1.f1(10, 20, 30);
Console.WriteLine("The sum is: {@}", r)5
/Iwill also be working with zero number of arguments
r= ob1.f1()5
Console.WriteLine("The sum is: {@}", 7);
//can pass array as well
int[] a = new int[] { 10, 20, 30, 40 }3
P= ob1.f1(a);
Console.WriteLine("The sum is: {8}", r)3
Console.Readkey() 5
Output:
i) CAUsers\DELL\source\tepeArray of objects (user-defined types)
class Student
string name;
internal void input()
Console.Write("Enter Name:");
name = Console.ReadLine();
}
internal void display()
Console.WriteLine("Name is:{0}",name) ;
}
}
class cmain
{
public static void Main()
{
int i,n;
Console.wWrite(“Enter number of students:");
n = Convert .ToInt32(Console.ReadLine());
Student[] ob = new Student[n];
for (i = 0; i < nj i++)
{ ob[i] = new Student(); }
for (i = @; i Microsoft Corporation. All rights reserved.Nested class example(Containment example):
class c2,
{
public class c3
{
public int x=10;
public void £234()
{
x=200;
}
}
(factory method
public ¢3 f123()
{
3 ob3=new c3();
return 0b3;
}
}
class cl {
public static void Main(string [Jargs)
{
2 ob=new c2();
ob.f123().f234();
System.Console. WriteLine(ob.f123().x);
Microsoft ras Visual C# 2418 Compiler version 4.6.30319.1
Copyright (C) Microsoft Corporation. All rights reserved.
1 EROT-5
18
ER
Note: A class containing an object of other class is also containment.Abstract class
Abstract classes, marked by the keyword abstract in the class definition, are typically
used to define a base class in the hierarchy,
An Abstract class is an incomplete class or special class we can't instantiate, We can use an
Abstract class as a Base Class. An Abstract method must be implemented in the non-Abstract
class using the override keyword. After overriding the abstract method is in the non-Abstract
class. We can derive this class in another class and again we can override the same abstract
method
with it.
Features:
1
2.
SPA NAHwAY
An abstract class can inherit from a class and one or more interfaces.
An abstract class can implement code with non-Abstract methods (means 0-100%
abstraction).
. An Abstract class can have modifiers for methods, properties etc.
. An Abstract class can have constants and fields.
. An abstract class can implement a property.
. An abstract class can have constructors or destructors.
. An abstract class cannot be inherited from by structures.
. An abstract class cannot support multiple inheritance.
Example 1:
#region
//An abstract calss can inherit from a class and one or more interfaces.
interface [VendorTransDetails
{
}
void getVendorID();
interface IClaimsTracker
{
void getSeqID();
}
class ClaimsMaster
{
string getDCNNO()
{
return "PC20100308A 00005";
Example 2:
96abstract class Abstract : ClaimsMaster, IClaimsTracker, IVendorTransDetails
{
(Mere we should implement modifiers oterwise it throws complie-time error
public void getVendorl10()
{
int s = new int();
s= 001;
Console. Write(s);
}
public void getSeqID()
{
int SeqID = new int():
SeqID = 001;
Console. Write(SeqID):
}
}
#endregion
Example 3:
#region
//An abstract class can implement code with non-Abstract methods.
abstract class NonAbstractMethod
/Mt is a Non-abstract method we should implement code into the non-abstract method on the
class.
public string getDen()
{
return "PS20100301A0012";
}
public abstract void getSeqID();
}
class Utilize : NonAbstractMethod
{
public override void getSeqID()
{
}
}
#endregion
Example 4:
#region
//Abstract class can have modifiers for methods,properties and An abstract class can
implement a property ;
public abstract class abstractModifier
rrivate int id;
, 7public int ID
{
get { return id; }
set {id= value; }
internal abstract void Add();
:
#endregion
Example 5:
#region
Abstract class can have constant and fields
public abstract class ConstantFields
{
public int no;
private const int id = 10;
}
#endregion
Example 6:
#region
//An abstract class can have constructors or destructors
abstract class ConsDes
{
ConsDes()
{
,
~ConsDes()
‘
2
}
#endregion
Example 7:
#region
//An abstract class cannot be inherited from by structures
public struct test
{
//Ne can't inheritance the struct class on the abstract class
abstract class NotInheritanceStruct
{
}
#endregion
Example 8:
#region a
//An abstract class cannot support multiple inheritance
class A
{
98}
class B: A
{
abstract class Container : B //But we can't iherit like this : A,B
{
egal
Abstract class vs. Interface
An abstract class can have abstract members as well as non abstract members (i.e. 0 to
100% abstraction). But in an interface all the members are implicitly abstract (i.e. always 100%
abstraction) and all the members of the interface must override to its derived class.
An example of interface:
interface iSampleInterface
MAlI methods are automaticall abstract
int AddNumbers(int Num 1, int Num2);
int MultiplyNumbers(int Num1, int Num2);
}
Defining an abstract class with abstract members has the same effect to defining an
interface.
The members of the interface are public with no implementation. Abstract classes can
have protected parts, static methods, etc.A class can inherit one or more interfaces, but only one
abstract class.
Abstract classes can add more functionality without destroying the child classes that were
using the old version. In an interface, creation of additional functions will have an effect on its
child classes, due to the necessary implementation of interface methods to classes.
The selection of interface or abstract class depends on the need and design of your
Project. You can make an abstract class, interface or combination of both depending on your
needs.Polymorphism
Polymorphism means to exists in more than one form and is derived from term
“Polymorphic” where Poly (means many)+ morphic (means form). i.e same task perform more
than one actions is known as polymorphism. For example: to condense the customer differently,
to draw something ¢.g. shape or rectangle etc.
Other example of abs() function i.e. if a language supports overloading then this provides
a common abs() function to find absolute value for integer, float, double etc else different-
different functions. Same is a case of user-defined functions means you can serve clients with
common function name over different parameters/signatures,
We use method overloading and method overriding to achieve polymorphism.
Another example can be to speak something e.g. cat speaks meaw, dog barks woof etc.
Technical examples (benefits of polymorphism):
sqrt) function can perform square root of integer, float, double etc if language supports
overloadi € user has to remember only one name of function.
ob.f123(); statement can call different f123 functions of different sub classes (depends on object
‘ob’ contained address of which sub class) if language supports overriding.
Types: Polymorphism is of two types
1)Compile time/Early-time/Static e.g. Overloading-Method overloading, Constructor
overloading, Operator overloading(not supported by Java even few operators are provided in-
built overloaded and others are not provided due to JVM complexities but supported by C#.net).
2) Run-time/Late-time/ Dynamic e.g. Method overriding (overriding is possible because of
inheritance i.e. same signature of function even returning type in super and sub class).
Method overloading examples:
egl
class cl
{
public void £1230)
{ System,Console. WriteLine("'without arguments"); }
public void f123(int x)
{ System.Console.WriteLine(x); }
public void £123(int x, int y)
{ ’ i
System.Console. WriteLine("Values are: " +x +); // check if only x+y is printed}
}
class abe
public static void Main(string{] args)
el ob=new cl(); ,
ob.f123(); / invokes first 123 function
ob.f123(5); // invokes second £123 function
ob.f123(5, 6); // invokes third £123 function
‘System.Console.ReadLine();
}
}
}
Operator overloading examples:
egl
class cl
100{
int x;
int y5
public c1(){}
public cl(int p, int q)
{
=P
ia
public void disp()
ft
System.Console. WriteLine(x+" and "+y);
}
public static ¢1 operator+(cl obl,cl ob2)
{
ol obt=new cl();
obt.x=0b1.x+0b2.x;
obty=ob1.ytob2.y;
retum obt;
}
}
class abe
{
Public static void Main(String{} args)
{
1 obj =new c1(10,20);
1 obj2=new c1(100,200);
obj | disp();
obj2.disp0;
el obj3-new c1();
(0bj3=0bj +0bj2;
0bj3.disp0;
System.Console.ReadLine();
.
}
Method Overriding (virtual and override keyword)
In C#, for overriding the base class method in derived class, you have to declare base class
method as virtual and derived class method as override as shown below:(new Keyword Vs
virtual and override keywords(method hiding Vs overriding))
As you know Polymorphism is the concepts of OOPS which includes method overriding
and method overloading. virtual and override keywords are used for method overriding and
new keyword is used for method hiding.
using System;
namespace Polymorphism
{
class A
{
101public virtual void Test() { Console. Writel ine("A::Test()"), }
i B:A
ee override void Test() { Console, Writel ine("B::Test()"); }
cas C:8
a override void Test() { Console. WriteLine("C::Test()"); }
Law Program
{
static void Main(string[] args)
Ce=newC();
a.Test(); // output --> "A::Test()"
b.Test(); // output --> "B::Test()"
c.Test(); // output --> "C::Test()"
a=new Bi);
a.Test(); // output --> "B::Test()"
// bez overriding means compiler must ignore the type object but must consider only the point
/fhat object contains the reference of which class. So, Test() of B is invoked. Reverse result is
Healled method hiding not overriding.
b=new C();
b.Test(); // output --> "C::Test()"
Console.ReadKey();
}
}
}
Note: : :
i) Advantage of method overriding by using downcasting is that we can do different tasks
by single statement like
ob.1123();
Where, ob is an object of super class down-casted to several different stb-classes.
cl obfJ=new cl [10];
ob[0]=new ¢2();
ob{1]=new ¢3();
ob[2}=new c4();
ob{3]-new c5();
102Hlete
for(int i=0;i "A::Test()"
b.Test(); // output --> "B::Test()"
c.Test(); // output -> "C::Test()"
a=new BO);
103a.Test(); // output —> "A::Test()"
b=new CQ;
b.TestQ); // output --> "B::Test()"
Console.ReadKey();
}
}
}
When you will run the above program (method hiding) without use of new keyword, it will run
successfully and gives the O/P (by default C# compiler thinks of hiding). But this program will
show the two warnings as shown below:
1. ‘Polymorphism.B.Test()' hides inherited member 'Polymorphism.A.Test()'. Use the new
keyword if hiding was intended.
2. 'Polymorphism.C.Test()' hides inherited member 'Polymorphism.B.Test()'. Use the new
keyword if hiding was intended.
Note:In Java method hiding was achieved by static methods but here in C# we cannot mark
static methods as virtual or override because static members cannot be accessed with object i.e
only with class name (but in Java it is possible to access static elements with class and with
object as well). So, to achieve the same (hiding concept) an extra keyword “new” is introduced.
Mixing Method Overriding and Method Hiding
You can also mix the method hiding and method overriding by using virtual and new
keyword since the method of a derived class can be virtual and new at the same time. This is
required when you want to further override the derived class method into next level as | am
overriding Class B, Test() method in Class C as shown below:
using System;
namespace Polymorphism
{
class A
{
public void Test() { Console. WriteLine("A::Test()"); }
}
class B: A
{
public new virtual void Test() { Console. WriteLine("B::Test()"); }
}
class C:B
104{
nai override void Test() { Console. WriteLine("C::Test()"); J
class Program
{
static void Main(string[] args)
{
Aa=new AQ;
Bb=new BQ;
Cc=new C();
a.Test(); // output --> "A::Test()"
b.Test(); // output --> "B::Test()"
¢.Test(); // output -> "C::Test()"
a=new BQ);
a.Test(); // output --> "A::Test()"
b=new CO;
b.Test(); // output -->
Console.ReadKey();
est()"
1. The virtual keyword is used to modify a method, property, indexer, or event declared in
the base class and allows it to be overridden in the derived class.
2. The override keyword is used to extend or modify a virtual/abstract method, property,
indexer, or event of base class into derived class,
The new keyword is used to hide a method, property, indexer, or event of base class into
derived class.
3.sealed Keyword
In C#, the sealed modifier is used to define a class as sealed. In Visual Basic .NET the
NotInheritable keyword serves the purpose of sealed. In Java final keyword is used for same
purpose. Sealed classes are used to restrict the inheritance feature of object oriented
programming. Once a class is defined as a sealed class, the class cannot be inherited.If a class is
derived from a sealed class then the compiler throws an error. If you have ever noticed, structs
are sealed. You cannot derive a class from a struct. The following class definition defines a
sealed class in C#:
// Sealed class
sealed class SealedClass
{
}
In the following code, I create a sealed class SealedClass and use it from Class]. If you
run this code then it will work fine. But if you try to derive a class from the SealedClass, you will
get an error.
using System;
class Class1
{
static void Main(string[] args)
{
SealedClass sealedCls = new SealedClass();
int total = sealedCls.Add(4, 5);
Console. WriteLine("Total = " + total.ToString());
}
}
/! Sealed class
sealed class SealedClass
' public int Add(int x, int y)
{
return x + y;
}
}
Sealed Methods and Properties
You can also use the sealed modifier on a method or a property that overrides a virtual
method or property in a base class. This enables you to allow classes to derive from your class
and prevent other developers that are using your derived classes from overriding specific virtual
methods and properties.
class X{
protected virtual void F() { Console. WriteLine("X.F"); }
protected virtual void F2() { Console, WriteLine("X.F2"); }
class Y : X
{
sealed protected override void F() { Console. WriteLine("Y.F"); }
protected override void F2() { Console. WriteLine("X.F3"); }
}
class Z: Y
{
// Attempting to override F causes compiler error CS0239.
// protected override void F() { Console. WriteLine("C.F"); }
// Overriding F2 is allowed.
protected override void F2() { Console. WriteLine("Z.F2"); }
}
Note: We can use sealed keyword with methods that are overridden in derived class because in
base class method without virtual keyword is non-overridable (i.e. sealed) by default. So, no any
need of sealed keyword (even cannot use sealed keyword with methods not having override
keyword) with methods of base classes. sealed is used only with methods that are
overridden in derived classes and you want to exclude it from further override in next level
inheritance ( methods with override keyword in derived are also inheritable in next level class).
Why Sealed Classes?
The vast majority of .NET programmers let their classes “unsealed” without even
considering making them sealed. If a class was not designedly made inheritable, it is very
probably even impossible to inherit from it and override members reasonably. On the other hand,
overriding members of the class which were not designed to be overridden might cause
unpredictable results. For example a class that implements security features, so that the original
object cannot be "impersonated".readonly and const Keyword
The readonly keyword is a modifier that you can be used on fields. When a field
declaration includes a readonly modifier, assignments to the fields introduced by the declaration
can only occur as part of the declaration or in a constructor in the same class.
The readonly keyword is different from the const keyword. A const field can only be
initialized at the declaration of the field. A readonly field can be initialized either at the
declaration or in a constructor. Therefore, readonly fields can have different values depending on
the constructor used. Also, while a const field is a compile-time constant, the readonly field can
be used for runtime constants as in the following example:
Example:
In this example, the value of the field year cannot be changed in the method ChangeYear,
even though it is assigned a value in the class constructor:
class Age
{
readonly int _ year;
Age(int year)
{
_year = year;
}
void ChangeYear()
//_year = 1967; // Compile error if uncommented.
}
}
You can assign a value to a readonly field only in the following contexts:
+ When the variable is initialized in the declaration, for example:
* public readonly int y = 5;
Other Example:
public class ReadOnlyTest
class SampleClass
public int x;
// Initialize a readonly field
public readonly int y = 25;
public readonly int z;
public SampleClass()
// Initialize a readonly instance field
z= 24;
}
public SampleClass(int p!, int p2, int p3)
{
x=pl;
108static void Main()
SampleClass p1 = new SampleClass(11, 21, 32); // OK
Console.WriteLine("p1: x={0}, y={1}, 2=(2}", pl.x, pl ;
. . » PLX, ply, pl.2);
SampleClass p2 = new SampleClass();
p2.x=55; // OK
Console. WriteLine("p2: x={0}, y={1}, 2={2)", p2.x, p2,y, p22);
In the preceding example, if you use a statement like tl
p2.y = 66; // Error
You will get the compiler error message.
In the preceding example, if you use a statement like this:
public const int n;
/finstead of below
public const int n=99;
“will give an error
Error 1. A .const field requires a value to be provided
More examples:
Example 1:
using System;
using System.Collections.Generic;
using System.Ling;
using System.Text ;
namespace ConsoleApplication10
classProgram
it
publicconstint x=10;
publicreadonlyint y;
public Program()
Console.WriteLine("Enter y:\n");
y=Convert .ToInt32(Console .ReadLine ());
}
staticvoid main(string[] args)
{ :
Program ob=newProgram ()3
Console.wWriteLine(x); fe//cannot write like Console.WriteLine(ob.x)5
Console.wWriteLine(ob.y);
//cannot write like Console.wWriteLine(y);
Console.ReadLine();
}
}
Example 2:
using System;
using System.Collections.Generic;
using System.Ling;
using System.Text;
namespace ConsoleApplication1e
classProgram
{
staticvoid Main(string[] args)
t
constint x=10;
readonlyint y=20;
7/ ERROR bcz readonly can be applied with data
Console.WriteLine("Enter y:\n");
y=Convert .ToInt32(Console .ReadLine ())5
Console.WriteLine(x) ;
Console.WriteLine(y);
Console.ReadLine();
}
members of a class