C#Unit-2 Notes
C#Unit-2 Notes
OOPs Concepts
The key concepts of OOPs are
Abstraction
Encapsulation
Inheritance
Polymorphism
Abstration:
Abstraction is a concept in OOPS in which only essential details will be
represented and background details will be hidden.
Encapsulation:
Encapsulation is a concept in OOPs wrapping up of data and its
associated functions into a single unit called class.
Inheritance:
Inheritance is a property of OOPs in which a class can inherit the
property of another class. The class which inherits the property of
another class is derived class. The class whose properties are inherited
by derived class is base class.
Polymorphism:
Polymorphism is a concept in OOPs which means one name and
multiple forms.
There are two types of polymorphism in C#:
Static / Compile Time Polymorphism
Dynamic / Runtime Polymorphism
Overloading is the concept in which method names are the same with
different parameters.
Method Overriding in C#
If the same method is present in both the base class and the derived
class, the method in the derived class overrides the method in the base
class. This is called method overriding in C#.
Creating a class:
To create a class, use the class keyword:
using System;
class Dog {
//field
string breed;
//method
public void bark(){
Console.WriteLine("Bow Bow!!")
}
}
Creating an object:
An object is an instance of a class. Suppose, we have a class Dog. Bulldog,
German Shepherd, Pug are objects of the class.
Syntax for creating an object:
ClassName obj = new ClassName();
Example:
Dog bullDog = new Dog();
Now, the bullDog object can access the fields and methods of the Dog
class.
//Console.ReadKey();
}
}
}
Output
Bull Dog
Bark Bark !!
C# this Keyword
In C#, this keyword refers to the current instance of a class. For example,
using System;
namespace ThisKeyword {
class Test {
int num;
Test(int num) {
// this.num refers to the instance field
this.num = num;
Console.WriteLine("object of this: " + this);
}
Output
object of this: ThisKeyword.Test
object of t1: ThisKeyword.Test
Note:
The reference variable "this" is allocated within the method stack
whenever a non-static method or constructor is called. It means the
"this" reference variable can be allocated several times to hold the
address of a single object.
The reference variable "this" is automatically initialized with the
reference of the current object for which the non-static method or
constructor is called.
class Member
{
public Member(){
Console.WriteLine("Default Constructor was called.");
}
~Member(){
Console.WriteLine("Destructor was called.");
}
}
class Program{
static void Main(string[] args){
Member member1 = new Member();
public Car(string c)
{
color=c;
}
static void main(string[] args)
{
//Creating object array.
Car[] obj = new Car[3];
//Initializing objects
obj[0]=new Car("Cian");
obj[1]=new Car("Dodger Blue");
C# Nested classes:
In C#, we can define a class within another class. It is known as a nested
class. For example,
class OuterClass {
//Body of the outer class.
class InnerClass {
//Body of the inner class.
}
}
Here, we have created the class InnerClass inside the class OuterClass.
The InnerClass is called the nested class.
Access Members
To access members of the nested classes we first need to create their
objects.
Once we have created the object of individual classes, we can use the
object name and dot operator to access members of each class.
// outer class
public class Car {
// inner class
public class Engine {
public void displayEngine() {
Console.WriteLine("Engine: Petrol Engine");
}
}
}
class Program {
static void Main(string[] args) {
Console.ReadLine();
}
}
}
In the above program, we have nested the Engine class inside the Car
class.
Inside the Program class, we have created objects of both the outer class
and the inner class.
Note: We cannot access the members of the inner class using the object
of the outer class.
For example,
// error code
sportsCar.displayEngine();
Here, we cannot access the displayEngine() method of the inner class
Engine using the sportsCar object of the outer class.
We can access members of the outer class inside the inner class. For this
we use an object of the outer class.
If we need to access static members of the outer class, we don't need to
create its object. Instead, we can directly use the name of the outer class.
Notice that we have used the name of the outer class along with the
nested class to inherit the inner class.
class Laptop : Computer.CPU {}
Partial classes:
While programming in C# (or OOP), we can split the definition of a class
over two or more source files. The source files contains a section of the
definition of class, and all parts are combined when the application is
compiled. For splitting a class definition, we need to use the partial
keyword.
The partial keyword specify that other parts of the class can be defined in
the namespace. It is mandatory to use the partial keyword if we are
trying to make a class partial. All the parts of the class should be in the
same namespace and available at compile time to form the final type. All
the parts must have same access modifier i.e. private, public, or so on.
If any part is declared abstract, then the whole type is considered
abstract.
If any part is declared sealed, then the whole type is considered sealed.
If any part declares a base type, then the whole type inherits that class.
Any class member declared in a partial definition are available to all
other parts.
All parts of a partial class should be in the same namespace.
**Note: The partial modifier is not available on delegate or enumeration
declarations
namespace HeightWeightInfo
{
class File2
{
}
public partial class Record
{
public void PrintRecord()
{
Console.WriteLine("Height:"+ h);
Console.WriteLine("Weight:"+ w);
}
}
}
Here now we can see the main method of the project:
namespace HeightWeightInfo
{
class Program
{
static void Main(string[] args)
{
Record myRecord = new Record(10, 15);
myRecord.PrintRecord();
Console.ReadLine();
}
}
}
Here we have the object of the class Record as myRecord which is
passing the parameter values as 10 and 15 to h and w respectively to the
method defined in File1.cs.
This shows that the partial keyword helps to combine all the attributes of
a class defined in various files to work as a single class.
Here,
name - public field that can be accessed from anywhere
num - private field can only be accessed within the Student class
That's why when we run an assembly all classes and interfaces inside the
assembly run together.
C# static keyword:
In C#, if we use a static keyword with class members, then there will be a
single copy of the type member.
And, all objects of the class share a single copy instead of creating
individual copies.
C# Static Variables
If a variable is declared static, we can access the variable using the class
name. For example,
Suppose if we declare a static variable name in student class,
// static variable
public static string name = "Kamal Hassan";
C# Static Methods
Just like static variables, we can call the static methods using the class
name.
using System;
class Test {
public static void display() {
Console.WriteLine(“Hello”);
}
}
class Program {
static void Main(string[] args) {
Test.display();
}
}
In the above example display is the static method. Only a single copy of
this method is accessible by all objects of class.
As it belongs to the class Test. Test.display() method is used to access the
method.
namespace StaticKeyword {
Since we cannot make an object of the static class, we get the following
error:
error CS0723: Cannot declare a variable of static type 'Test'
error CS0712: Cannot create an instance of the static class
Notice the field and method of the static class are also static because we
can only have static members inside the static class.
Access static Members within the Class
If we are accessing the static variables and methods inside the same
class, we can directly access them without using the class name. For
example,
using System;
namespace StaticKeyword {
class Test {
static int age = 25;
public static void display() {
Console.WriteLine("Static method");
}
static void Main(string[] args) {
Console.WriteLine(age);
display();
Console.ReadLine();
}
}
}
Output
25
Static method
Here, we are accessing the static field age and static method display()
without using the class name.
1. Readonly Fields:
In C#, you are allowed to declare a field using readonly modifier.
It indicates that the assignment to the fields is only the part of the
declaration or in a constructor to the same class.
Such types of fields can only be assigned or reassigned multiple times
only at the declaration or in a constructor.
They are not assigned after the constructor exit. If the readonly
modifier is used with a value type field, then the field is immutable.
And if the readonly modifier is used with a reference type field, then
the readonly modifier prevents the field from replaced by the different
instances of the reference type, here the readonly modifier does not
stop the instance data of the field from being modified through the
read-only field.
In static and instance constructors, you are allowed to pass a readonly
field as an out or ref parameter.
// how to create a readonly field
using System;
class example {
// readonly variables
public readonly string str1;
public readonly string str2;
// Readonly variable
// This variable is
// initialized at declaration time
public readonly string str3 = "VcetMCA";
str1 = a;
str2 = b;
Console.WriteLine("Display value of string 1 {0}, "
+ "and string 2 {1}", str1, str2);
}
// Main method
static public void Main()
{
example ob = new example("VCET", "MCA");
}
}
Display value of string 1 VCET, and string 2 MCA
Static Readonly
A Static Readonly type variable's value can be assigned at runtime or
assigned at compile time and changed at runtime. But this variable's
value can only be changed in the static constructor. And cannot be
changed further. So it can change only once at runtime.
C# Indexers
An indexer allows us to access instances of a class using an index just like
an array.
Example: C# indexer
using System;
class Program
{
// declare an array to store elements
private string[] studentName = new string[10];
// define an indexer
public string this[int index]
{
get
{
// return value of stored at studentName array
return studentName[index];
}
set
{
// assigns value to studentName
studentName[index] = value;
}
}
Here, the set method assigns values to studentName using index. And
the get method returns values stored at studentName.
Here, we have used obj (instance of the Program class) like the
studentName array.
Note: Without using indexer, we access the studentName array through
obj as:
// insert value to studentName array when indexer is not used
obj.studentName[0] = "Harry";
Indexer helps to simplify the syntax.
C# Structures:
The struct (structure) is like a class in C# that is used to store data.
However, unlike classes, a struct is a value type.
Suppose we want to store the name and age of a person. We can create
two variables: name and age and store value.
In this case, creating variables for an individual person might be a
tedious task. To overcome this we can create a struct that stores name
and age. Now, this struct can be used for every person.
Define struct in C#
In C#, we use the struct keyword to define a struct.
For example,
struct Employee {
public int id;
public string name;
public double salary;
}
Here, id, name and salary are fields inside the struct. A struct can include
methods, indexers, etc as well.
Declare struct variable
Before we use a struct, we first need to create a struct variable. We use a
struct name with a variable to declare a struct variable. For example,
// declare emp of struct Employee
Employee emp;
Access C# struct
We use the struct variable along with the . operator to access members of
a struct. For example,
// access member of struct
emp.id = 1;
emp.name = “John Cena”;
emp.salary = 25000.213;
Here, we have used variable emp of a struct Employee with . operator to
access members of the Employee.
Note: We can also instantiate a struct using the new keyword. For
example,
Employee emp = new Employee();
Constructors in C# struct
In C#, a struct can also include constructors. For example,
struct Employee {
System.objectClass
All .NET classes are ultimately derived from the System.Object class.
In fact, when you don’t specify a base class while defining a class, the
compiler automatically assumes that it derives from System.Object.
Lastly, because of this behavior, you have access to many public,
protected member methods that have been defined for the Object
class.
System.Object is the parent of all classes within the .NET.
All class builtin and/or defined is a subclass of System.Object
The Object class is the base class for all the classes in the .Net
Framework.
It is present in the System namespace.
In C#, the .NET Base Class Library(BCL) has a language-specific alias
which is Object class with the fully qualified name as System.Object.
Every class in C# is directly or indirectly derived from the Object
class. If a class does not extend any other class then it is the direct
child class of the Object class and if extends another class then it is
indirectly derived.
Therefore the Object class methods are available to all C# classes.
Hence Object class acts as a root of the inheritance hierarchy in any
C# Program.
The main purpose of the Object class is to provide low-level services
to derived classes.
Encapsulation in C#
Encapsulation allows an object to control access to its data and methods,
which can improve the security and stability of the system.
//Mutators
public string set(string name) {
Name = name;
}
}
public class MainClass {
public static void Main(string[] args) {
EmployeeDetail detail = new EmployeeDetail();
detail.set("Ghost");
Console.WriteLine("The Employee Name is :" + detail.get());
Console.ReadLine();
}
}
}
Output:
The Employee Name is :Ghost
We have defined two methods set and get. The set method, mutator, sets
the value of the Name variable. The get method, accessor, displays the
value of the Name variable on the screen.
C# Inheritance:
In C#, it is possible to inherit fields and methods from one class to
another. We group the "inheritance concept" into two categories:
Derived Class (child) - the class that inherits from another class
Base Class (parent) - the class being inherited from
To inherit from a class, use the : symbol.
In the example below, the Car class (child) inherits the fields and
methods from the Vehicle class (parent):
class Animal {
// fields and methods
}
Here, we are inheriting the derived class Dog from the base class Animal.
The Dog class can now access the fields and methods of Animal class.
Note:
protected Members in C# Inheritance
When we declare a field or method as protected, it can only be accessed
from the same class and its derived classes.
3. Hierarchical Inheritance
In hierarchical inheritance, multiple derived classes inherit from a single
base class.
Syntax:
AccessSpecifier derieved_class1 : base_class
{Body of derieved class}
AccessSpecifier derieved_class2 : base_class
{Body of derieved class}
4. Multiple Inheritance
In multiple inheritance, a single derived class inherits from multiple base
classes. C# doesn't support multiple inheritance. However, we can
achieve multiple inheritance through interfaces.
5. Hybrid Inheritance
Hybrid inheritance is a combination of two or more types of inheritance.
The combination of multilevel and hierarchical inheritance is an example
of Hybrid inheritance.
Example:
class Base
{
public Base() {
Console.WriteLine("Inside Base Constructor");
}
~Base() {
Console.WriteLine("Inside Base Destructor");
}
}
class Derived: Base {
public Derived() {
Console.WriteLine("Inside The Derived Constructor");
}
~Derived() {
Console.WriteLine("Inside The Derived Destructor");
}
}
The derived class is getting inherited from the base class. Both the
classes have a default constructor, where I am printing appropriate
messages.
The important point to note from this output is that the base class
constructor is being called first and then derived class constructor.
Now, to manually call the constructor of the base class from the derived
class constructor. We need to do this, using base keyword.
Thus, the base class constructor, that takes two parameters is called first
and then the derived class constructor. Output of this is:
Inside Baseclass parameterized constructor.
Inside Derivedclass parameterized constructor.
Sealed Classes in C#
A sealed class, in C#, is a class that cannot be inherited by any class but
can be instantiated.
class Program {
static void Main (string [] args) {
Sealed method:
During method overriding, if we don't want an overridden method to be
further overridden by another class, we can declare it as a sealed
method.
class Main_Method
{
static void Main()
{
derived_class d = new derived_class();
d.display();
}
}
In the above example the display() function from the derived class
overrides the display() function in the base_class.
Abstract Class
In C#, we cannot create objects of an abstract class. We use the abstract
keyword to create an abstract class. For example,
using System;
namespace abstractclass{
// create an abstract class
abstract class absclass {
// fields and methods
}
// try to create an object Language
class abs{
public static void Main (string [] args) {
An abstract class can have both abstract methods (method without body)
and non-abstract methods (method with the body). For example,
abstract class Language {
// abstract method
public abstract void display1();
// non-abstract method
public void display2() {
Console.WriteLine("Non abstract method");
}
}
using System;
namespace AbstractClass {
abstract class absclass {
// non-abstract method
public void display() {
Console.WriteLine("Non abstract method");
}
}
Output:
Non abstract method
In the above example, we have created an abstract class named
Language. The class contains a non-abstract method display().
We have created the Program class that inherits the abstract class.
Notice the statement,
obj.display();
Here, obj is the object of the derived class Program. We are calling the
method of the abstract class using the object obj.
Note: We can use abstract class only as a base class. This is why abstract
classes cannot be sealed.
C# Abstract Method
A method that does not have a body is known as an abstract method. We
use the abstract keyword to create abstract methods.
For example,
public abstract void display();
using System;
namespace AbstractClass {
Console.WriteLine("Bark Bark");
}
}
class Program {
static void Main (string [] args) {
// create an object of Dog class
Dog obj = new Dog();
obj.makeSound();
Console.ReadLine();
}
}
}
Output:
Bark Bark
In the above example, we have created an abstract class named Animal.
We have an abstract method makeSound() inside the class.
We have a Dog class that inherits from the Animal class. Dog class
provides the implementation of the abstract method makeSound().
If the Dog class had not provided the implementation of the abstract
method makeSound(), Dog class should have been marked abstract as
well.
Note: Unlike the C# inheritance, we cannot use virtual with the abstract
methods of the base class. This is because an abstract class is implicitly
virtual.
C# interface
In C#, an interface is similar to abstract class. However, unlike abstract
classes, all methods of an interface are fully abstract (method without
body).
We use the interface keyword to create an interface. For example,
interface IPolygon {
// method without body
void calculateArea();
}
Here,
Implementing an Interface
We cannot create objects of an interface. To use an interface, other
classes must implement it. Same as in C# Inheritance, we use : symbol to
implement an interface.
For example,
using System;
namespace CsharpInterface {
interface IPolygon {
// method without body
void calculateArea(int l, int b);
class Program {
static void Main (string [] args) {
Rectangle r1 = new Rectangle();
r1.calculateArea(100, 200);
}
}
}
Output
Area of Rectangle: 20000
Inheritance of Interface:
// C# program to illustrate the concept of inheritance in interface
using System;
// declaring an interface
public interface A {
// method of interface
void mymethod1();
void mymethod2();
}
// method of interface B
void mymethod3();
}
// Below class is inheriting
// only interface B
// This class must
// implement both interfaces
class Inherited : B
{
// Driver Class
class Program {
// Main method
static void Main(String []args)
{