Module-2 With Content
Module-2 With Content
Prepared by
Mrs. Suma M G
Assistant Professor
Department of MCA
RNSIT
Bengaluru – 98.
Programming using C# .NET Module – 2 Chapter – 1: Classes, Objects & OOP
Chapter - 1
Syntax:
<ClassName> <ObjectName> = new <ClassName>();
Partial method are only allowed in partial types, such as classes and structs. A partial method consists of 2
parts that listed below:
✓ Deals with defining the partial method Rules:
✓ Deals with implementing the partial method Must have a void return type
No access modifier are allowed for declaring a partial
declaration
method except for static
Partial methods are private by default.
Example 1.3:
using System;
namespace Class_Demos{
partial class MyTest {
private int a;
private int b;
public void getAnswer(int a1, int b1){
a = a1;
b = b1;
}
static partial void Message();
}
partial class MyTest{
partial void Message(){
Console.WriteLine("Successfully accessed. . . . . . ");
}
public void DisplayAns(){
Console.WriteLine("Integer values: {0}, {1}", a, b);
Console.WriteLine("Addition:{0}", a + b);
Console.WriteLine("Multiply:{0}", a * b);
Message();
}
}
class PartialEx{
public static void Main(){
MyTest ts = new MyTest();
ts.getAnswer(2, 3);
ts.DisplayAns();
Console.Read();
}}}
using System;
namespace Class_Demos{
class MyArea {
double l, b, area;
public double RectArea() {
Console.WriteLine("Enter the Length");
l = double.Parse(Console.ReadLine());
Console.WriteLine("Enter the Breadth");
b = double.Parse(Console.ReadLine());
area = l * b;
Console.WriteLine("The area of Rectangle:" + area);
return (area);
}
}
class ReturnValue{
static void Main(){
MyArea obj = new MyArea();
obj.RectArea();
Console.WriteLine("Press Enter to quit....");
Console.ReadLine();
} } }
Modifiers Meaning
public Allows public access to members both inside and outside a class without any restrictions.
internal Allows internal access to members. Only the current assembly can access these members.
Allows protected access to members. You can access protected members from either the class in
protected
which they are declared or a class derived from the class in which they are declared.
Allows private access to members. Private members have the least access permission level; you
private
can either access then within the body of the class or in the structure in which they are declared.
protected Allows access to the members of the current assembly, the containing class, and the class derived
internal from the containing class.
Static methods
A C# class can contain both static and non-static methods. When we declare a method with the help of the
keyword static, it becomes a static method.
For using static methods,
Creation of instance is not necessary.
A static method only access other static data and methods
Static methods cannot access data members and members’ method directly – they must use an object
reference.
Example 1.5:
using System;
namespace Examples {
class Stmethod{
static int record=0;
int i;
Stmethod(){
record++;
i++;
}
static void printrecord(){
Console.WriteLine ("No of stud record: {0}", record);
Console.WriteLine ("i: {0}", i);
}
static void Main(){
Stmethod stm1 = new Stmethod();
Stmethod stm2 = new Stmethod();
printrecord();
Console.ReadLine();
}
}
}
When you create Stdata objects( std1, std2), memory for the non-static data field is allocated for each instance.
On the other hand, Static data is allocated once and shared among all object instances of the same type. So the
output of the record is 2 in both the instance of the class.
Static class:
When a class has been defined as static, no need to create an object. A static class must contain only static
members, except for constants (if this is not the case, you receive compiler errors).
Main benefit: We do not need to make any instance of this class; all members can be accessible with its own
name.
using System;
namespace Examples {
static class StClass {
static int record = 0;
static void printrecord(){
Console.WriteLine("No of stud record: {0}", record);
}
static void Main() {
record = 2;
printrecord();
Console.ReadLine();
}
}
}
In the above example, StClass class is static class so it includes only static members. We can access all the
member of the static class directly; no need of instance of the class. So that members record and printrecord()
is accessing directly.
1.11 Properties:
A property is a member that provides a flexible mechanism
Syntax:
to read, write or compute the value of a private field. You
can implement properties with the type-safe get and set
set { <mutator-body> }
methods. get { <accessor-body >}
Example: The important thing is the “value” keyword, sets the value of the some property
Set { field with the contents of value token.
usn=value;
}
Note: Keep in mind about property that don’t have to have both a getter and a setter, you must have one of the
two.
➢ A property defined with both a getter and a setter is called a read-write property.
➢ A property defined with only a getter or accessor is called a read-only property.
➢ A property defined with only a setter or mutator is called a write-only property.
Example 1.8:
C# also supports “static” properties. The static members are accessed at the class level, not from an instance
(object) of that class. Static properties are manipulated in the same manner as static methods, as seen here:
For example, assume that the Student type defines a point of static data to represent the name of the institution
studying these students. You may define a static property as follows:
Example 1.10:
using System; class GetSetStatic {
namespace Chapter4_Examples{ static void Main(){
class Student { Student.Institution = "RNSIT";
string name, branch, usn; Console.WriteLine("Institution
static string instName; Name: "+Student.Institution );
public static string Institution{ Console.ReadKey();
set { instName = value; } }
get { return instName; } }
} }
}
Where,
The access modifier can be private, public, protected or internal
Return type can be any valid C# data type, such as int, float, double, string….
this keyword shows that the object is of the current class.
argument list specifies the parameters of the indexer.
Must have at least one parameter; otherwise the compiler gives and error.
Allows you to have multiple parameters and each parameter can be a different type, separated
by commas.
Parameter types can be int, enum, or string.
All indexers in the same class should have different signatures.
The get and set portions accessors is the same as that of the indexer to which they belong.
Example 1.11:
using System;
namespace Class_Demos{
class Student {
string[] usn = new string[3];
public string this[int index]{
set { usn[index] = value; }
get {
if (index < 0 || index >= usn.Length)
return null;
else
return (usn[index]);
}
} }
class IndexerDemo {
public static void Main(){
Student slist = new Student();
slist[0] = "1RN12MCA01";
slist[1] = "1RN12MCA02";
slist[2] = "1RN12MCA03";
for (int i = 0; i < 3; i++)
Console.WriteLine(slist[i]);
Console.ReadKey();
}
} }
using System;
namespace Class_Demos{
class Student{
string name,usn,branch;
public Student(string n,string u,string b) {
name = n;
usn = u;
branch= b;
}
public Student(){}
//Define a string indexer
public string this[string index] {
get{
if (index == "name")
return name;
if (index == "usn")
return usn;
if (index == "branch")
return branch;
return "Unknown";
}
set {
if(index=="name")
name = value;
if (index == "usn")
usn = value;
if (index == "branch")
branch = value;
}
}
}
class IndexerDemo1 {
static void Main(){
Student std1 = new Student("Abhilash","1RN17MCA01","MCA");
Console.WriteLine("Name: " + std1["name"]);
Console.WriteLine("USN: " + std1["usn"]);
Console.WriteLine("Branch: " + std1["branch"]);
Continued . . .
using System;
namespace Class_Demos {
public struct StDemo {
public int x;
public string y;
Continued . . .
public void Display(){
Console.WriteLine("\n X= {0} \n Y= {1}", x, y);
}
}
class StructDemo {
static void Main(){
StDemo st=new StDemo();
st.x = 10;
st.y = "Hello";
Console.WriteLine("X= {0}, \nY={1}", st.x, st.y);
Console.WriteLine("x=" + s3.x);
Console.WriteLine("Please enter to QUIT....");
Console.ReadLine();
}
}
}
Method Description
Determines whether the specified object is equal to the current
Equals(Object)
object.
Equals(Object, Determines whether the specified object instances are considered
Object) equal.
Finalize() Allows an object to try to free resources.
GetHashCode() default hash function.
GetType() Type of the current instance.
MemberwiseClone() shallow copy of the current Object.
Example 1.14:
using System;
class ObjectType
{
int x = 10;
ObjectType ShallowCopy()
{
return (ObjectType)MemberwiseClone();
}
~ObjectType()
{
Console.WriteLine("Finalize() method performs");
}
ob1 = ob2;
Console.WriteLine("Is objects type are Equal ? -> " +
Equals(ob1,ob2));
int i = 20;
Console.WriteLine(i.GetType());
Console.ReadLine();
}
}
}
Encapsulation
Introduction:
C# is an Object oriented Programming language. So, like all Object oriented languages, C# will also supports
following Object Oriented Principles.
i. Encapsulation : How does this language hide an object’s internal implementation?
ii. Inheritance : How does this language promote code reuse?
iii. Polymorphism : How does this language let you treat related objects in a similar way?
2.1. Encapsulation:
Encapsulation is the procedure of covering up of data and functions into a single unit. An encapsulated object
is often called an abstract data type.
We need of Encapsulation for the following reasons:
▪ One of the fundamental principles of object-oriented programming.
▪ A process of hiding all the internal details of an object from the outside world.
▪ Provides a way to protect data from accidental corruption.
▪ Gives the ability to validate the values before the object user change or obtain the value.
▪ Makes implementation inaccessible to other parts of the program and protect from whatever
actions might be taken outside the function or class.
i. The first method is, if we want the outside world to interact with private usn data field, tradition
dictates defining an accessor (get method) and mutator (set method).
Example 2.1: In this application, we have defined two methods set() and get(). The set() method
mutator, set the value of usn variable. The get() method accessor, displays the value of the usn variable
on the command prompt.
Suma M G, AP, Dept. of MCA, RNSIT for updates: https://sites.google.com/view/sumamg-dotnet/ 15 | 34
Module -2 Chapter - 2: Encapsulation
ii. Creating Read-Only Fields: Properties can be made read-only. This is accomplished by having only
get accessor in property implementation.
Example 2.4: In the below example, the property “Studusn” is having only get (accessor) but not set
(mutator). So can call Studusn as a “read-only property”.
iii. “static” property: C# also supports “static” properties. The static members are accessed at the class
level, not from an instance (object) of that class. Static properties are manipulated in the same manner
as static methods, as seen here:
Example 2.5: Assume that the Student type defines a point of static data to represent the name of the
institution studying these students. You may define a static property as follows:
using System; class StaticProperty{
namespace Class_Demos{ static void Main(){
class Student{ Student.Institution = "RNSIT";
string name, branch, usn; Console.WriteLine("InstitutionName:"
static string instName; +Student.Institution);
public static string Institution Console.ReadKey();
{ }
set { instName = value; } }
get { return instName; } }
}
}
2.4. Inheritance:
The next pillar of OOP, Inheritance provides you to reuse existing code and fast implementation time. The
relationship between two or more classes is termed as Inheritance.
In essence, inheritance allows to extend the behavior of a base (or parent/super) class by enabling a subclass to
inherit core functionality (also called a derived class/child class). All public or protected variables and methods
in the base class can be called in the derived classes.
Inheritance comes in two ways:
Classical inheritance ( “is-a” relationship)
Containment/delegation model (“has-a” relationship).
C# supports single, hierarchical, and multilevel inheritance because there is only a single base class. It does not
support multiple inheritance directly. To implement multiple inheritance, you need to use interfaces.
Example 2.8:
InherDemo.cs class InherDemo{
static void Main(){
using System; //Create a Base Class Object
namespace Class_Demos{ Console.WriteLine("I'm accessing Base Class Object");
class BaseClass{ BaseClass bc = new BaseClass();
public int dm; bc.dm = 10;
public void BCMethod(){ bc.BCMethod();
Console.WriteLine("I'm a Base Class Method"); //Create a Derived Class Object
} Console.WriteLine("I'm accessing Derived Class Object");
} DerivedClass dc=new DerivedClass();
class DerivedClass:BaseClass{ dc.dm = 20;
public void DCMethod(){ dc.BCMethod();
Console.WriteLine("I'm a Derived Class Method"); dc.DCMethod();
} Console.WriteLine("\nPress ENTER to quit...");
} Console.Read();
}
}
}
In this section, you learn about the following topics in the context of inheritance:
▪ Inheritance and Constructors ▪ Extension methods
▪ Sealed classes and sealed methods
It is important to note that a Base class constructors are not inherited by derived classes. Thus cannot instantiate
a base constructor using derived class object, so we need the “base” keyword to access constructor of the base
class from within a derived class.
using System;
namespace Chapter4_Examples{
public class A { // It is the base class.
protected int x;
public A(int i){
x = i;
Console.WriteLine("Base constructor A()");
}
}
public class B : A{ // This class derives from the previous class
int y;
public B(int i, int j): base(i){
y = j;
Console.WriteLine("Derived constructor B()");
}
public void show(){
Console.WriteLine("X= {0} \nY= {1}", base.x, y);
}
}
class Basekeydemo {
static void Main(){
B b = new B(10, 20);
b.show();
Console.ReadKey();
}
}
}
A sealed class can contain sealed methods. Similar to the sealed class, sealed method are also defined using
the “sealed” keyword. A derived class cannot override the sealed methods; however, you can use a sealed
method to override an inherited virtual method with the same signature. It means that in methods, you always
use sealed keyword with the combination of override keyword, as shown in the following code snippet:
Example 2.10:
using System;
namespace Class_Demos{
sealed class BClass{
public void method1(){
Console.WriteLine("This is method of Base class");
}
}
//Following lines shows compiler error as sealed class cannot be inherited
class DClass : BClass{
//Code
}
class SealedDemo{
static void Main(){
BClass obj = new BClass();
obj.method1();
Console.WriteLine("\nPress ENTER to quit...");
Console.Read();
}
}
}
using System;
namespace Class_Demos{
public static class Myclass{
//Defining extension method with
public static int myExtensionmethod(this string num){
return (Int32.Parse(num));
}
public static int Mystaticmethod(string num){
return (Int32.Parse(num));
}
}
class ExtensionDemo{
static void Main(){
string num = "100";
//invoking method of type extension
int ext = num.myExtensionmethod(); //Line A
Console.WriteLine("The output from myExtensionMethod()”+ext);
Polymorphism
The final pillar of OOP is polymorphism. Polymorphism means “one name many forms”.
Polymorphism defined as “one object behaving as multiple forms and one function behaves in different
forms”. In other words, “Many forms of a single object is called Polymorphism”.
Advantages:
• Allows you to invoke methods of a derived class through base class reference during runtime
• Provides different implementations of methods in a class that are called through the same name
You can implement compile time polymorphism through overloaded methods in three types that are mention
below:
i. Method overloading ii. Operator overloading iii. Indexer overloading
i. Method overloading:
In method overloading, can be define many methods with the same name but different signatures. A method
signature is the combination of the method’s name along with the number, type, and order of the parameters.
Example 3.1: In this application, the Area() method of Shape class is overloaded for calculating the area of
square, rectangle, circle and triangle shapes. In the Main() method, the Area() method is
called multiple times by passing different arguments.
using System;
namespace Class_Demos{
class Shape{
public void Area(int side){
Console.WriteLine("The area of Square is: " + side * side);
}
public void Area(int length, int breadth){
Console.WriteLine("The area of Rectangle is: "
+ length * breadth);
}
When overload an operator, you need to create a method that must be preceded by the “operator” keyword and
that method should define as a static method.
Example 3.2: In this application, we have created a class, UnaryOpr, which contains a constructor,
UnaryOpr, to initialize its two variables. The UnaryOpr class also contains the ShowData() method to
display the value of the class variables and overload the functionality of the – (minus) operator. The – operator
is overloaded by using the operator keyword. Next in the Main()method of the OpOverload class, the –
operator is used to show the negative value of an object of the UnaryOpr class.
using System;
class unaryopr{
int n1, n2;
public unaryopr() { }
public unaryopr(int a, int b){
n1 = a;
n2 = b;
}
public void showData(){
Console.WriteLine("The numbers are: " +n1+ " and " +n2);
}
public static unaryopr operator -(unaryopr opr){
unaryopr obj = new unaryopr();
obj.n1 = -opr.n1;
obj.n2 = -opr.n2;
return obj;
}
}
class OpOverload{
static void Main(){
unaryopr opr1 = new unaryopr(20,30);
Console.WriteLine("Before Operator Overloading");
opr1.showData();
unaryopr opr2 = new unaryopr();
opr2 = -opr1; //invoke operator overloading method
Console.WriteLine("After Operator Overloading");
opr2.showData();
Console.Read();
}
}
Example 3.3: In this application, we have created a class, BinaryOpr, which contains a constructor,
BinaryOpr, to initialize its two variables. The BinaryOpr class also contains the ShowData() method to
display the value of the class variables and overload the functionality of the + (addition) operator. The +
operator is overloaded by using the operator keyword. Next in the Main()method of the OpOverload1
class, the + operator is used to show the addition of the values of the objects of the BinaryOpr class.
using System;
namespace Class_Demos{
class Binaryopr{
int n1, n2;
public Binaryopr() { }
public Binaryopr(int a, int b){
n1 = a;
n2 = b;
}
opr3.showData();
Console.Read();
}
}
}
Continued...
get{
int count = 0;
for (int i = 0; i < arrsize; i++){
if (mydata[i] == data)
count = count + 1;
}
return count.ToString();
}
}
}
class IndOverload{
static void Main(){
int size = 10;
MyClass obj=new MyClass(size);
obj[1] = "Hello";
obj[3] = "Good Morning";
obj[7] = "Welcome";
obj["DataValue"] = "Have a nice day";
In this snippet, we have overloaded indexers by passing different type of parameters. We have defined two
indexers, with the int type and string type parameters, named position and data, respectively. These
indexers are used to display the values of different string data that is passed in the Main() method of the
IndOverload class.
When a method get called, the method defined in the derived class is invoked and executed instead of the one
in the base class.
Consider, you want to derive a class from a base class and to redefine some methods contained in this base
class. In such a case, you cannot declare the base class method as virtual.
Then, how you can override a method without declaring that method as virtual in the base class?
Ans: This can be possible with the new operator. The new operator is used to override the base class method
in the derived class without using the virtual keyword. The new operator tells the compiler that the
derived class method hides the base class method.
Example 3.6:
using System; class PolyDemo1{
namespace Class_Demos{ static void Main(string[] args){
public class Bclass{ // calling the overriden method
public void Show(){ Dclass objDc = new Dclass();
Console.WriteLine("Base Class"); objDc.Show();
} // calling the base class method
} Bclass objBc = new Bclass();
class Dclass : Bclass{ objBc.Show();
public new void Show(){
//Calling Base Class Method
Console.WriteLine("Derived Class"); objBc = new Dclass();
} objBc.Show();
} Console.ReadLine();
}
}
}
Characteristics:
❖ Restricts its implementation in an abstract derived class
❖ Allows implementation in a non-abstract derived class
❖ Requires declaration in an abstract class only
❖ Restrict declaration with static and virtual keywords
❖ Allows you to override a virtual method.
Suma M G, AP, Dept. of MCA, RNSIT for updates: https://sites.google.com/view/sumamg-dotnet/ 29 | 34
Programming using C# [16MCA52] Module -2 Chapter - 3: Polymorphism
Example 3.7:
using System;
namespace Chapter4_Examples{
abstract class absClass{
//A Non abstract method
public int AddTwoNumbers(int Num1, int Num2){
return Num1 + Num2;
}
//An abstract method to be overridden in derived class
public abstract int MultiplyTwoNumbers(int Num1,int Num2);
}
3.6 Interfaces:
“An interface is a collection of methods, events, properties and indexers, but it does not implement them”.
Interface are introduced to provide the feature of multiple inheritance to classes.
Multiple inheritance is the feature of OOP
which allows a class to inherit from interface <Interface_Name> {
multiple classes. The methods defined in
an interface do not have implementation, //Abstract method declaration in interface body
they only specify the parameters that they }
will take and the types of values they will
return.
Example: public interface Channel
{
void Next();
}
Example 3.9: We have created two interface BaseInterface and DerivedInterface. The
BaseInterface interface is inherited by the DerivedInterface interface. Then the
InterfaceImplemeter class implements the DerivedInterface interface.
using System;
namespace Class_Demos{
interface BaseInterface{
void GetPersonalDetail();
void GetContactDetail();
}
interface DerivedInterface:BaseInterface{
void ShowDetail();
}
Suma M G, AP, Dept. of MCA, RNSIT for updates: https://sites.google.com/view/sumamg-dotnet/ 31 | 34
Programming using C# [16MCA52] Module -2 Chapter - 3: Polymorphism
Console.ReadLine();
}
}
}
Chapter 2 - Encapsulation
1. • What are the three pillars of object oriented programming in C#? What are the two ways of
enforcing encapsulation? Give examples for both the methods.
• How do you enforce encapsulation using accessors and mutators, class properties and static
properties?
• What are the different methods of accessing private data fields by other classes in C#?
Explain with examples. 10
2. How do you prevent inheritance using sealed classes? Explain with an example. 5
3. Bring out the differences between interfaces and abstract base classes. 5
4. Explain with an example:
8
i. public class ii. sealed class and sealed method iii. Abstract class
5. With an example, explain Extension method. 6
Chapter 3 – Polymorphism
1. What is a polymorphism? List types of polymorphism. 4
2. Explain the overloading of equality and comparison operators in C# 6
3. What are abstract classes and abstract methods? Explain with an example. 5
4. Write a program to overload + and – operators for adding and subtracting two square matrices. 10
5. Write a C# program, which defines class Flight. The class Flight implements two interfaces
namely Ibirds and Iplane and the interface member of Ibirds and Iplane is fly(), which displays 08
some message. Write the usage class which exercises the above.
6. Write a short notes:
5
i. Static data ii. Operator overloading
7. Create a class called student which contains, USN, studentName and also total marks obtained.
Also overload comparison operators for comparing two students based upon their total marks 10
obtained.
8. What is the alternate approach to support multiple inheritance in C# .NET? List its major features
10
with code example.
9. What is Interface? Explain how to create interfaces and implemented with an example. 8
10. Distinguish between compile time and runtime polymorphism with suitable example. 8