0% found this document useful (0 votes)
25 views127 pages

Unit Ii

Uploaded by

Geetha Smiley
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views127 pages

Unit Ii

Uploaded by

Geetha Smiley
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 127

VISUAL PROGRAMMING

UNIT-II

BY

THATIKONDA RADHIKA REDDY


Topics to be Covered:
• Overview of Object Oriented Programming for C#
• Classes and Objects – Constructing and Initializing objects,
• Properties, Indexers,
• Methods and Constructors,
• Parameter Passing to Methods and Constructors,
• Abstraction,
• Encapsulation,
• Static fields and methods.
• Inheritance – Overview, Controlling accessibility
• Overloading, Method Hiding.
Topics to be Covered:
• Interfaces – Overview,
• Using .NET provided interfaces,
• Writing and using your interfaces.
• Polymorphism – Overview,
• Dynamic vs. Static Binding,
• Abstract Classes,
• Generics – Generic Features,
• Generic Methods,
• Arrays and
• Tuples,
• Delegates
• and Events
What is OOP?
• OOP stands for Object-Oriented Programming.
Object-oriented programming has several advantages over procedural
programming:
• OOP is faster and easier to execute
• OOP provides a clear structure for the programs
• OOP helps to keep the C# code DRY "Don't Repeat Yourself", and
makes the code easier to maintain, modify and debug
• OOP makes it possible to create full reusable applications with less
code and shorter development time
Pillars of OOPs
• The major concepts that we have discussed above are
known as pillars of OOPs. There are four pillars on
which OOP rests.
• Abstraction:Hide the implementation from the user
• Encapsulation:To bind data and functions of a class into
an entity
• Inheritance: To inherit or acquire the properties of an
existing class(Reusabilty)
• Polymorphism:It allows us to create methods with the
same name but different method signatures.
Classes and Objects
• Classes are special kinds of templates from which you can create
objects. Each object contains data and methods to manipulate and
access that data. The class defines the data and the functionality that
each object of that class can contain.
• Classes and objects are the two main aspects of object-oriented
programming.
Classes and Objects
Constructing and Initializing objects
• Object is an instance of a class. All the members of the
class can be accessed through object.
• Object is a runtime entity, it is created at runtime.
• Let's see an example to create object using new keyword.
Student s1 = new Student();//creating an object of Student
C# Class
• In C#, class is a group of similar objects. It is a
template from which objects are created. It can have
fields, methods, constructors etc.
• Let's see an example of C# class that has two fields
only.
public class Student
{
int id;//field or data member
String name;//field or data member
}
C# Object and Class Example
• using System;
• public class Student
• {
• int id; //data member (also instance variable)
• String name; //data member(also instance variable)

• public static void Main(string[] args)
• {
• Student s1 = new Student(); //creating an object of Student
• s1.id = 101;
• s1.name = "Sonoo Jaiswal";
• Console.WriteLine(s1.id);
• Console.WriteLine(s1.name);

• }
• }
• Output:
C# Properties
• A property is a member that provides a flexible mechanism to read,
write, or compute the value of a private field.
Usage of C# Properties:
• C# Properties can be read-only or write-only.
• We can have logic while setting values in the C# Properties.
• We make fields of the class private, so that fields can't be accessed
from outside the class directly. Now we are forced to use C#
properties for setting or getting values.
C# Properties Example
using System; }
public class Employee
{ class TestEmployee{
private string name; public static void Main(string[] args)
{
public string Name Employee e1 = new Employee();
{ e1.Name = "Sonoo Jaiswal";
get Console.WriteLine("Employee Name: " + e1.Name
{ );

return name;
} }
set }

{
name = value; Output:
} Employee Name: Sonoo Jaiswal
}
C# indexer
• A C# indexer is a class property that allows you to access a member variable
of a class or struct using the features of an array.
Syntax:
[access_modifier] [return_type] this [argument_list] {
get { // get block code
}
set { // set block code
}
}
In the above syntax:
• access_modifier: It can be public, private, protected or internal.
• return_type: It can be any valid C# type.
• this: It is the keyword which points to the object of the current class.
• argument_list: This specifies the parameter list of the indexer.
• get{ } and set { }: These are the accessors.
using System; set {
if( index >= 0 && index <= size-1 ) {
namespace IndexerApplication { namelist[index] = value;
}
class IndexedNames { }
private string[] namelist = new string[size]; }
static public int size = 10; static void Main(string[] args) {
IndexedNames names = new IndexedNames();
public IndexedNames() { names[0] = "Zara";
for (int i = 0; i < size; i++) names[1] = "Riz";
namelist[i] = "N. A."; names[2] = "Nuha";
} names[3] = "Asif";
public string this[int index] { names[4] = "Davinder";
get { names[5] = "Sunil";
string tmp; names[6] = "Rubic";

if( index >= 0 && index <= size-1 ) { for ( int i = 0; i < IndexedNames.size; i++ ) {
tmp = namelist[index]; Console.WriteLine(names[i]);
} else { }
tmp = ""; Console.ReadKey();
} }
}
return ( tmp ); }
}
Access Specifiers
• Access Specifiers defines the scope of a class member. A
class member can be variable or function.
• In C# there are five types of access specifiers are available.
Type Access Specifiers:
1.Public Access Specifiers
2.Private Access Specifiers
3.Protected Access Specifiers
4.Internal Access Specifiers
5.Protected Internal Access Specifiers.
• Private Modifier
• If we declare a field with a private access modifier, it can only
be accessed within the same class.

class Car
{
private string model = "Mustang";
static void Main(string[] args)
{
Car myObj = new Car(); Console.WriteLine(myObj.model);
}
}
• Public Modifier
• If you declare a field with a public access modifier, it is
accessible for all classes:
class Car
{
public string model = "Mustang";
}
class Program
{
static void Main(string[] args)
{
Car myObj = new Car();
Console.WriteLine(myObj.model);
}}
• protected
• Access is limited to the class that contains the member and derived
types of this class.
• It means a class which is the subclass of the containing class
anywhere in the program can access the protected members.
• Syntax:
• protected TypeName
• internal
• Access is limited to only the current Assembly, that is any class or
type declared as internal is accessible anywhere inside the same
namespace. It is the default access modifier in C#.
• internal TypeName
• protected internal
• Access is limited to the current assembly or the derived types of
the containing class. It means access is granted to any class
which is derived from the containing class within or outside the
current Assembly.
• protected internal TypeName
• private protected
• Access is granted to the containing class and its derived types
present in the current assembly. This modifier is valid in C#
version 7.2 and later.
• private protected TypeName
Methods
• A method is a group of statements that together perform
a task.
Methods
Type of Methods According parameter methods are
divided into two types:
• Parameterized method
• Parameter less method
According to return type Methods are divide into two
types:
• Void Method
• Non-void Method
Parameter less method

While defining a method we didn’t declared parameter which is


called as Parameterized method.
class Program {
static void Main(string[] args) {
squareVal();
console.ReadKey();
}
static void squareVal() {
int arg;
arg = 4;
arg *= arg;
Console.WriteLine(arg);
}
}
Parameterized method

While defining a method we have declared parameter


which is called as Parameterized method.
In C#, arguments can be passed to parameters either by
value or by reference. Passing by reference enables
function members.
To pass a parameter by reference, use the ref or out
keyword. For simplicity, only the ref keyword is used in the
examples in this topic.
Parameterized method
Parameterized method
• Void Method: A method which is not returning any
values according to its functionality is called as void
Method
Void fun()
{}
• Non-void Method: A method which is returning some
values according to its functionality is called as void
Method
Int fun()
{ return }
Constructors in C#
• A constructor is a special method that is used to initialize
objects.
• The advantage of a constructor, is that it is called when an
object of a class is created.
• It can be used to set initial values for fields.
Important points:

• The constructor of a class must have the same name as the class
name in which it resides.
• A constructor can not be abstract, final, and Synchronized.
• A constructor doesn’t have any return type, not even void.
• A class can have any number of constructors.
• Access modifiers can be used in constructor declaration to
control its access
• i.e. which other class can call the constructor.
Constructors in C#

Constructors can be divided into 5 types:


• Default Constructor
• Parametrized Constructor
• Copy Constructor
• Static Constructor
• Private Constructor
Default Constructor

• A constructor with no parameters is called a default


constructor.
• A default constructor has every instance of the class to
be initialized to the same values.
• The default constructor initializes all numeric fields to
zero and all string and object fields to null inside a
class.
using System;
namespace DefaultConstractor
{
class addition
{
int a, b;
public addition() //default contructor
{
a = 100;
b = 175;
}
public static void Main()
{
addition obj = new addition(); //an object is created , constructor is called
Console.WriteLine(obj.a);
Console.WriteLine(obj.b);
Console.Read();
}}}
Parameterized Constructor

• A constructor having at least one parameter is called as


parameterized constructor.
• It can initialize each instance of the class to different values.
using System; class MainClass
namespace Constructor {
{ static void Main()
class paraconstrctor {
{ paraconstrctor v = new paraconstrctor(100,
public int a, b; 175);
Console.WriteLine("-----------parameterized
public paraconstrctor(int x, int y)
constructor example by vithal
{ wadje---------------");
a = x; Console.WriteLine("\t");
b = y; Console.WriteLine("value of a=" + v.a );
} Console.WriteLine("value of b=" + v.b);
} }}}
Copy Constructor

• The constructor which creates an object by copying variables


from another object is called a copy constructor.
• The purpose of a copy constructor is to initialize a new
instance to the values of an existing instance.
using System;
namespace copyConstractor
{
class employee
{
private string name;
private int age;
public employee(employee emp) // declaring Copy constructor.
{
name = emp.name;
age = emp.age;
}
public employee(string name, int age) // Instance constructor.
{
this.name = name;
this.age = age;
}
public string Details // Get deatils of employee
{get
{
return " The age of " + name +" is "+ age.ToString();
}}}
class empdetail
{
static void Main(){
employee emp1 = new employee("Vithal", 23); // Create a new employee object.
employee emp2 = new employee(emp1); // here is emp1 details is copied to emp2.
Console.WriteLine(emp2.Details);
}}}
Static Constructor
• When a constructor is created as static, it will be invoked
only once for all of instances of the class.
• it is invoked during the creation of the first instance of the
class or the first reference to a static member in the class.
• A static constructor is used to initialize static fields of the
class and to write the code that needs to be executed only
once.
Some key points of a static constructor is:

• A static constructor does not take access modifiers or have


parameters.
• A static constructor is called automatically to initialize the
class before the first instance is created or any static members
are referenced.
• A static constructor cannot be called directly.
• The user has no control on when the static constructor is
executed in the program.
using System;
namespace staticConstractor
{
public class employee
{
static employee() // Static constructor declaration
{
Console.WriteLine("The static constructor "); }
public static void Salary()
{
Console.WriteLine();
Console.WriteLine("The Salary method");
}}
class details
{
static void Main()
{
Console.WriteLine("-Static constrctor-");
Console.WriteLine();
employee.Salary();
}
}
}
Private Constructor
• If a constructor is created with a private specifier is known as
a Private Constructor.
• It is not possible for other classes to derive from this class
and also it’s not possible to create an instance of this class.
using System;
namespace defaultConstractor
{
public class Counter
{
private Counter() //private constrctor declaration
{
}
public static int currentview;
public static int visitedCount()
{
return ++ currentview;
}
}
class viewCountedetails
{
static void Main()
{
// Counter aCounter = new Counter(); // Error
Console.WriteLine("-------Private constructor example by vithal
wadje----------");
Console.WriteLine();
Counter.currentview = 500;
Counter.visitedCount();
Console.WriteLine("Now the view count is: {0}", Counter.currentview);
Console.ReadLine();
}} }
• Abstraction
• Data abstraction is the process of hiding certain details and
showing only essential information to the user.

Abstraction can be achieved by two ways:


• Abstract class
• Interface
• The abstract keyword is used for classes and methods:
• Abstract class: is a restricted class that cannot be used to
create objects (to access it, it must be inherited from another
class).
• An abstract class can have both abstract and regular methods:

• Abstract method: can only be used in an abstract class, and it


does not have a body. The body is provided by the derived
class (inherited from).
abstract class Animal
{
public abstract void animalSound();
public void sleep()
{
Console.WriteLine("Zzz");
}
}
• abstract class Animal • class Dog : Animal
•{ •{
• public abstract void • public override void
animalSound(); animalSound()
• public void sleep() •{
• { • Console.WriteLine("The dog
• Console.WriteLine("Zzz"); says: bow bow");
•} •}
• } •}
• class Program
•{
• static void Main(string[] args)
• {
• Dog d= new Dog(); // Create a object
• d.animalSound(); // Call the abstract method
• d.sleep(); // Call the regular method
• }
•}
• C# Interface
• Another way to achieve abstraction in C#, is with interfaces.
• An interface is a completely "abstract class", which can only
contain abstract methods and properties (with empty bodies):
Example
// interface
interface Animal
{
void animalSound(); // interface method (does not have a body)
void run(); // interface method (does not have a body)
}
using System;
namespace CsharpInterface { class Program
interface Ipolygon {
{ static void Main (string [] args)
void calculateArea(int l, int b); {
} Rectangle r1 = new
class Rectangle : IPolygon Rectangle();
{ r1.calculateArea(100, 200);
public void calculateArea(int l, int b) { }
int area = l * b; }
Console.WriteLine("Area of }
Rectangle: " + area);
}
}
C# Encapsulation
• Encapsulation is a process of binding the data members and member functions
into a single unit. Encapsulation, the variables or data of a class are hidden from
any other class.
• A fully encapsulated class has getter and setter functions that are used to read
and write data.
• Encapsulation is implemented by using access specifiers. An access
specifier defines the scope and visibility of a class member.
• C# supports the following access specifiers −
• Public
• Private
• Protected
• Internal
• Protected internal
Static fields and methods
• In C#, one is allowed to create a static class, by using static keyword.
• A static class can only contain static data members and static methods. It is
not allowed to create objects of the static class and since it does not allow
to create objects it means it does not allow instance constructor.
• Static classes are sealed, means you cannot inherit a static class from
another class.
• static class Class_Name
{
// static data members
// static method
}
• In C#, the static class contains two types of static members as follows:
• Static Data Members: As static class always contains static data
members, so static data members are declared using static keyword
and they are directly accessed by using the class name.
• The memory of static data members is allocating individually without
any relation with the object.
• static class Class_name
{
public static nameofdatamember;
}
• Static Methods: As static class always contains static methods, so
static methods are declared using static keyword.
• These methods only access static data members, they can not access
non-static data members.

• static class Class_name {


public static nameofmethod()
{
// code
}
}
using System; Driver Class
public class GFG {
namespace ExampleOfStaticClass {
// Main Method
static class Author { static public void Main()
public static string A_name = "Ankita"; {
public static string L_name = "CSharp";
// Calling static method of Author
public static int T_no = 84;
Author.details();
// Static method of Author // Accessing the static data members of Author
public static void details() Console.WriteLine("Author name : {0} ",
{ Author.A_name);
Console.WriteLine("The details of Author Console.WriteLine("Language : {0} ",
is:"); Author.L_name);
} Console.WriteLine("Total number of articles :
} {0} ",
Author.T_no);
} }
}
C# Inheritance

• In C#, inheritance allows us to create a new class from an


existing class. It is a key feature of Object-Oriented
Programming (OOP).
• The class from which a new class is created is known as the
base class (parent or superclass).
• And, the new class is called derived class (child or subclass).
• The derived class inherits the fields and methods of the base
class. This helps with the code reusability in C#.
• In C#, we use the : symbol to perform inheritance.
using System; class Program {
namespace Inheritance static void Main(string[] args)
{ {
// base class // object of derived class
class Animal Dog labrador = new Dog();
{ // access field and method of base class
public string name; labrador.name = "Rohu";
public void display() labrador.display();
{ // access method from own class
Console.WriteLine("I am an animal"); labrador.getName();
}} Console.ReadLine();
class Dog : Animal }
{ }
public void getName() }
{ Console.WriteLine("My name is " +
name); } }
Types of Inheritance in C#

• Single Inheritance
• Multilevel Inheritance
• Hierarchical Inheritance
• Multiple Inheritance
• Hybrid Inheritance
Single Inheritance

• In single inheritance, a single derived class inherits from a single base


class.
using System;
class Vehicle {
public void Engine() {
Console.WriteLine("A vehicle has an engine.");
}}
class Car : Vehicle {
public void run() {
Console.WriteLine("Car is running.");
}}
class Example {
static void Main(string[] args) {
Car c = new Car();
c.Engine();
c.run();
}
}
Multilevel Inheritance

• In this type of inheritance, a derived class inherits from a base class, and at the
same time, the derived class itself also acts as a base class for some other class.
using System;
class Son : Father
class GrandFather
{
{
public void written()
public void write()
{ Console.WriteLine("Son");
{ }}
Console.WriteLine("GrandFather"); class Example
}} {
class Father : GrandFather static void Main(string[] args)
{ {
public void wrote() Son s = new Son();
{ s.write();
Console.WriteLine("Father"); s.wrote();
}} s.written();
}}
Hierarchical Inheritance

• In hierarchical inheritance, multiple derived classes inherit from a


single base class.
using System; class Chemistry : Science
class Science {
{ public void love()
public void study() {
{ Console.WriteLine("Students love
Console.WriteLine("Students study Chemistry");
Science"); }}
}} class Example {
class Physics : Science static void Main(string[] args)
{ { Physics p = new Physics();
public void like() Chemistry ch = new Chemistry();
{ p.study();
Console.WriteLine("Students like p.like();
Physics"); ch.study();
}} ch.love(); } }
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.
class Transport : Car, Bike
using System;
{
public void display1()
interface Car {
Console.WriteLine("Car is a base class");
{ }
void display1(); public void display2()
} {
Console.WriteLine("Bike is a base class");
}
interface Bike public void display()
{ { Console.WriteLine("Transport is a derived class");
}
void display2(); }
}
class Example
{
static void Main(string[] args)
{
Transport t = new Transport();
t.display1();
t.display2();
t.display();
}
}
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.
The sealed Keyword

If we don't want other classes to inherit from a class,


use the sealed keyword:
sealed class Vehicle
{
...
}
class Car : Vehicle
{
...
}
C# Method Overloading

• In C#, there might be two or more methods in a class


with the same name but different numbers, types, and
order of parameters, it is called method overloading.
• Example:
• void display() { ... }
• void display(int a) { ... }
• float display(double a) { ... }
• float display(int a, float b) { ... }
• We can perform method overloading in the following ways:
• 1. By changing the Number of Parameters
• We can overload the method if the number of parameters in the
methods is different.
using System;
namespace MethodOverload
{ class Program
{
void display(int a)
{
Console.WriteLine("Arguments: " + a); }
void display(int a, int b) {
Console.WriteLine("Arguments: " + a + " and " + b); }
static void Main(string[] args)
{
Program p1 = new Program();
p1.display(100);
p1.display(100, 200);
} }}
• By changing the Data types of the parameters
using System;
namespace MethodOverload {
class Program {
void display(int a) {
Console.WriteLine("int type: " + a); }
void display(string b) {
Console.WriteLine("string type: " + b);}
static void Main(string[] args) {
Program p1 = new Program();
p1.display(100);
p1.display("Programiz");
Console.ReadLine();
}}
By changing the Order of the parameters
using System;
namespace MethodOverload {
class Program {
void display(int a, string b) {
Console.WriteLine("int: " + a);
Console.WriteLine("string: " + b);
}
void display(string b, int a) {
Console.WriteLine("string: " + b);
Console.WriteLine("int: " + a);
}
static void Main(string[] args) {
Program p1 = new Program();
p1.display(100, "Programming");
p1.display("Programiz", 400);
Console.ReadLine();
}}}
Method Hiding in C#

• C# also provides a concept to hide the methods of the base


class from derived class, this concept is known as Method
Hiding.
• It is also known as Method Shadowing.
• In method hiding, we can hide the implementation of the
methods of a base class from the derived class using
the new keyword.
• Or in other words, in method hiding, we can redefine the
method of the base class in the derived class by using
the new keyword.
using System;
public class My_Family {
public void member()
{
Console.WriteLine("Total number of family members: 3");
}
}
public class My_Member : My_Family {
public new void member()
{
Console.WriteLine("Name: Rakesh, Age: 40 \nName: Somya, "+ "Age: 39 \
nName: Rohan, Age: 20 ");
}
}
class GFG {
static public void Main()
{
My_Member obj = new My_Member();
Polymorphism
• Polymorphism is one of the features provided by Object Oriented
Programming. Polymorphism simply means occurring in more than
one form.
• That is, the same entity (method or operator or object) can perform
different operations in different scenarios.
using System; static void Main(string[] args)
class Program {
{ Program p1 = new Program();
public void greet(){ // calls method without any
Console.WriteLine("Hello");} argument
// method takes one string p1.greet();
parameter
public void greet(string name) //calls method with an argument
{ p1.greet("Tim");
Console.WriteLine("Hello " + }}
name);
}
Types of Polymorphism
There are two types of polymorphism:
• Compile Time Polymorphism / Static Polymorphism
• Run-Time Polymorphism / Dynamic Polymorphism
Compile Time Polymorphism
In compile time polymorphism, the compiler identifies which method is
being called at the compile time.
In C#, we achieve compile time polymorphism through 2 ways:
• Method overloading
• Operator overloading
C# Operator Overloading
• + operator is overloaded to Concatenating two strings
perform numeric addition as well string firstString = "Harry";
as string concatenation.
string secondString = "Styles";
Adding two numbers
string concatenatedString =
int x = 7; firstString + secondString;
int y = 5; Console.WriteLine(concatenatedStrin
int sum = x + y; g);
Console.WriteLine(sum); // Output: HarryStyles
// Output: 12
Runtime Polymorphism

• In runtime polymorphism, the method that is called is determined at


the runtime not at compile time.
• The runtime polymorphism is achieved by:
• Method Overriding
Method Overriding in C#
• During inheritance in C#, if the same method is present in both the
superclass and the subclass.
• Then, the method in the subclass overrides the same method in the
superclass. This is called method overriding.
• In this case, the same method will perform one operation in the
superclass and another operation in the subclass.
• We can use virtual and override keywords to achieve method
overriding.
• virtual - allows the method to be overridden by the derived class
• override - indicates the method is overriding the method from the
base class
using System;
class Polygon { class myProgram
// method to render a shape public virtual {
void render()
{ Console.WriteLine("Rendering public static void Main()
Polygon...");
{
}
} Polygon obj1 = new Polygon();
class Square : Polygon {
obj1.render();
// overriding render() method public
override void render() class Square obj = new Square();
{ obj.render();
Console.WriteLine("Rendering Square...");
} }
} }
Interfaces – Overview
• Interface in C# is a blueprint of a class. It is like abstract class because all the
methods which are declared inside the interface are abstract methods. It cannot
have method body and cannot be instantiated.
• It is used to achieve multiple inheritance which can't be achieved by class. It is
used to achieve fully abstraction because it cannot have method body.
Declaring Interfaces
• Interfaces are declared using the interface keyword.
public interface ITransactions {
// interface members
void showTransaction();
double getAmount();
}
C# interface example
using System; } }
public interface Drawable public class TestInterface
{ {
void draw(); public static void Main()
} {
public class Rectangle : Drawable Drawable d;
{ public void draw() d = new Rectangle();
{ d.draw();
Console.WriteLine("drawing rectangle..."); d = new Circle();
} } d.draw();
public class Circle : Drawable }
{ }
public void draw() Output:
{ drawing ractangle...
Console.WriteLine("drawing circle..."); drawing circle...
Using .NET provided interfaces
• .NET framework provides interfaces that implement by collections in
language to provide the functionality of iterating over objects in the
collection, adding and removing an object from collection to
randomly access an object from the collection.
Here are the interfaces considering at
present:
•IEnumerable and IEnumerable<T>
•IEnumerator and IEnumerator<T>
•IComparable and IComparable<T>
•IComparer and IComparer<T>
•ICollection and ICollection<T>
•IEquatable and IEquatable<T>
•IEqualityComparer and
IEqualityComparer<T>
•ICloneable
•IConvertible
Writing and using your own
interfaces
• 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 Rectangle : IPolygon {
// implementation of methods inside interface
public void calculateArea(int l, int b) {
int area = l * b;
Console.WriteLine("Area of Rectangle: " + area);
}
}
class Program {
static void Main (string [] args) {
Rectangle r1 = new Rectangle();
r1.calculateArea(100, 200);
}
C# Indexers

• An indexer allows us to access instances of a class using an index just


like an array.
• In C#, we define an indexer just
like properties using this keyword followed by [ ] index
notation .
Here,
•public - access modifier

•int - return type of indexer

•this - indicates we are defining indexer in current class

•int index - access values using integer index position

•get - ,method that returns values

•set - method that assigns values


using System; public static void Main()
class Program
{
{ // declare an array to store elements
// create instance of Program class
private string[] studentName = new string[10];
// define an indexer Program obj = new Program(); // insert
public string this[int index] values in obj[] using indexer i.e index
{ get {
position
// return value of stored at studentName array obj[0] = "Harry";
return studentName[index]; obj[1] = "Ron";
} obj[2] = "Hermoine";
set { Console.WriteLine("First element in
// assigns value to studentName obj: " + obj[0]);
studentName[index] = value;
Console.WriteLine("Second element in
}}
obj: " + obj[1]); } }
C# Arrays

• An array is a collection of similar types of data.


• C# Array Declaration
• In C#, here is how we can declare an array.
Syntax: datatype[] arrayName;
Example:int[] age;
• To define the number of elements that an array can hold, we have to
allocate memory for the array in C#.
• // declare an array
• int[] age;
• // allocate memory for array
• age = new int[5];
• We can also declare and allocate the memory of an array in a single
line. For example,
• Example: int[] age = new int[5];

• Array initialization in C#
• In C#, we can initialize an array during the declaration.
• For example, int [] numbers = {1, 2, 3, 4, 5};

• We can access the elements in the array using the index of the array.
• In C#, we can use loops to iterate through each element of an array.
using System;
namespace AccessArrayFor
{
class Program {
static void Main(string[] args) {
int[] numbers = { 1, 2, 3};
for(int i=0; i < numbers.Length; i++) {
Console.WriteLine("Element in index " + i + ": " + numbers[i]);
}
}
}
}
Using foreach loop
using System;
namespace AccessArrayForeach {
class Program
{
static void Main(string[] args)
{
int[] numbers = {1, 2, 3};
Console.WriteLine("Array Elements: ");
foreach(int num in numbers)
{
Console.WriteLine(num);
}
}}}
Advantages of C# Array
• Code Optimization (less code)
• Random Access
• Easy to traverse data
• Easy to manipulate data
• Easy to sort data etc.

An array can be of three types:


• Single-dimensional
• Multidimensional
• Jagged array.
• Single Dimensional Array:
• To create single dimensional array, you need to use square brackets [] after the type.
• int[] arr = new int[5];//creating array
using System;
public class ArrayExample
{
public static void Main(string[] args)
{
int[] arr = new int[5];//creating array
arr[0] = 10;//initializing array
arr[2] = 20;
arr[4] = 30;

//traversing array
for (int i = 0; i < arr.Length; i++)
{
Console.WriteLine(arr[i]);
C# Multidimensional Array
• The multidimensional array is also known as rectangular arrays in C#.
• It can be two dimensional or three dimensional.
• The data is stored in tabular form (row * column) which is also known
as matrix.
• To create multidimensional array, we need to use comma inside the
square brackets.
• For example:

• int[,] arr=new int[3,3];//declaration of 2D array


• int[,,] arr=new int[3,3,3];//declaration of 3D array
using System;
namespace MultiDArray {
class Program {
static void Main(string[] args) {
//initializing 2D array
int[ , ] numbers = {{2, 3}, {4, 5}};
// access first element from the first row
Console.WriteLine("Element at index [0, 0] : "+numbers[0, 0]);
// access first element from second row
Console.WriteLine("Element at index [1, 0] : "+numbers[1, 0]);
}
}
}
C# Jagged Array
• In C#, a jagged array consists of multiple arrays as its element.
• In C#, jagged array is also known as "array of arrays" because its elements
are arrays. The element size of jagged array can be different.
• C# Jagged Array Declaration:
• dataType[ ][ ] nameOfArray = new dataType[rows][ ];
Let's see an example,
• // declare jagged array
• int[ ][ ] jaggedArray = new int[2][ ];
• int - data type of the array
• [][] - represents jagged array
• jaggedArray - name of the jagged array
• [2][] - represents the number of elements (arrays) inside the jagged array
• Initializing Jagged Array
• There are different ways to initialize a jagged array. For example,
1. Using the index number
• Once we declare a jagged array, we can use the index number to initialize it. For
example,
• // initialize the first array
• jaggedArray[0][0] = 1;
• jaggedArray[0][1] = 3;
• jaggedArray[0][2] = 5;

• // initialize the second array


• jaggedArray[1][0] = 2;
• jaggedArray[1][1] = 4;
2. Initialize without setting size of array elements:

• // declaring string jagged array


• int[ ][ ] jaggedArray = new int[2] [ ];

• // initialize each array


• jaggedArray[0] = new int[] {1, 3, 5};
• jaggedArray[1] = new int[] {2, 4};
3. Initialize while declaring Jagged Array:

int[ ][ ] jaggedArray = {
• new int[ ] {10, 20, 30},
• new int[ ] {11, 22},
• new int[ ] {88, 99}
• };
Accessing elements of a jagged array:
• We can access the elements of the jagged array using the index number. For
example,
• // access first element of second array
• jaggedArray[1][0];

• // access second element of the second array


• jaggedArray[1][1];

• // access second element of the first array


• jaggedArray[0][1];
• using System;
• namespace JaggedArray {
• class Program {
• static void Main(string[] args) {
• // create a jagged array
• int[ ][ ] jaggedArray = {
• new int[] {1, 3, 5},
• new int[] {2, 4},
• };
• // print elements of jagged array
• Console.WriteLine("jaggedArray[1][0]: " + jaggedArray[1][0]);
• Console.WriteLine("jaggedArray[1][1]: " + jaggedArray[1][1]);
• Console.WriteLine("jaggedArray[0][2]: " + jaggedArray[0][2]);
• }
• }}
C# Array Operations using System.Linq

• In C#, we have the System.Linq namespace that provides different methods to perform various
operations in an array.
using System;
using System.Linq; // provides us various methods to use in an array
namespace ArrayMinMax {
class Program {
static void Main(string[] args) {
int[] numbers = {51, 1, 3, 4, 98};
// get the minimum element
Console.WriteLine("Smallest Element: " + numbers.Min());
// Max() returns the largest number in array
Console.WriteLine("Largest Element: " + numbers.Max());
Console.WriteLine("Sum is: " + numbers.Sum());
Console.WriteLine( "Average is: " +numbers.Average());

} }}
• The System.Array class also includes methods for creating, manipulating, searching, and
sorting arrays. See list of all Array methods
using System;
public class Program
{
public static void Main(){
int[] nums = { 10, 15, 16, 8, 6 };
Console.WriteLine("Original Array");
foreach(var element in nums)
Console.WriteLine(element);
Array.Sort(nums);
Console.WriteLine("Sorted Array");
foreach(var element in nums)
Console.WriteLine(element);
Array.Reverse(nums);
Console.WriteLine("Reversed Array");
Array.ForEach<int>(nums, n => Console.WriteLine(n));
Console.WriteLine(Array.BinarySearch(nums, 15));
}}
C# Tuples
• A tuple in C# allows us to store elements of different data types.
For example,
• var student = ("Taylor", 27, "Orlando");
• Create Tuple in C#:
• C# provides various ways for creating tuples.

1. Using Parentheses
2. Using the Create() Function
1. C# Tuple Using Parentheses
• We can create a tuple by directly assigning different values using parentheses ().

using System;
class Program {
public static void Main() {
// create a tuple containing 3 elements
var student= ("Taylor", 5, "Orlando");
Console.WriteLine(student);
}
}
• In this way, we can store data elements of different data types inside a tuple
without mentioning the datatype.

using System;
class Program {
public static void Main() {
(string,int,string) student = ("Taylor", 5, "Orlando");
Console.WriteLine(student);
}
}
// Output: (Taylor, 5, Orlando)
2. C# Tuple using Create() Method
• Create() method to create a tuple without having to mention the
datatypes of the tuple elements.
• The syntax for creating tuple using Create() is:
• var t1 = Tuple.Create(value);
using System;
class Program
{
public static void Main() {
// create a tuple containing 3 elements
var programming = Tuple.Create("programiz", "java", 12);
Console.WriteLine(programming);
}
}
Note: While creating a tuple using the Create() method it can only include a
maximum of eight elements.
Access Tuple Elements

• In the previous example, we have directly displayed the


whole tuple. However, it is possible to access each element of
the tuple.
• In C# each element of the tuple is associated with a default
name.
first element - Item1
second element - Item2
and so on
• We can access elements of the tuple using the default name.
using System;
class Program {
public static void Main() {

var subjects = Tuple.Create("Science", "Maths", "English");


// access the first element
Console.WriteLine("The first element is " + subjects.Item1);
// access the second element
Console.WriteLine("The second element is " +subjects.Item2);
}
}
Change Value of the Tuple Element
• We can change the value of data inside a tuple. To change the elements of the tuple, we can
reassign a new value to the default name.

using System;
class Program {
public static void Main() {
var roll_num = (5, 7, 8, 3);
// original tuple
Console.WriteLine("Original Tuple: " + roll_num);
// replacing the value 7 with 6
roll_num.Item2 = 6;
Console.WriteLine("Changing value of 2nd element to " + roll_num.Item2);
Console.WriteLine("Modified Tuple: " + roll_num);
}}
• Note: If we have used Create() to create a tuple, then we
cannot change the value of the elements. That means the
elements of the tuple are read-only.
using System;
class Program {
public static void Main() {
var t1= Tuple.Create("Taylor", "Jack");
t1.Item2 = "Monica";
Console.WriteLine(t1.Item2);
}
}
Delegate
• Any method which has the same signature as delegate can be assigned
to delegate.
• in C#, delegate is a reference to the method.
• It is very similar to the function pointer but with a difference that
delegates are a type-safe.
• In other words, delegates are used to pass methods as arguments to
other methods
• There are three steps for defining and using delegates:
• Declaration
• A delegate is declared by using the keyword delegate, otherwise it
resembles a method declaration.
• Instantiation
• To create a delegate instance, we need to assign a method (which has
same signature as delegate) to delegate.
• Invocation
• Invoking a delegate is like as invoking a regular method.
Types of delegates
1) Singlecast delegates
Singlecast delegate point to single method at a time.
2) Multiplecast delegates
In C#, delegates are multicast, which means that they can point to
more than one function at a time.
using System;
public static void Main()
{
namespace DemoDelagates Example obj = new Example();
{
MyDelagate delob = new
public delegate int MyDelagate(int a, int b); MyDelagate(obj.Sum);

public class Example


{ Console.WriteLine("Sum of two integer
is = " + delob(10, 20));
public int Sum(int a, int b)
{ }
}
return a + b; }
}
using System; static void Main(string[] args)
namespace delegate_Example {
{ TestMultipleDelegate obj = new
TestMultipleDelegate();
class Program
{ mydelegate delobj = new
public delegate void mydelegate(int x, int y); mydelegate(obj.add_Method);
// Here we have multicast
delobj += new mydelegate(obj.subtract_Method);
public class TestMultipleDelegate
{ delobj(50, 10);
public void add_Method(int x, int y)
{ delobj -= new mydelegate(obj.add_Method);

}}}
Console.WriteLine("addition ="+(x + y));
}
public void subtract_Method(int x, int y) Out put :
{ addition =60
subtraction=40
Console.WriteLine("subtraction="+(x - y));
}
Multicast example
Generic Features
• Generic means the general form, not specific. In C#, generic means
not specific to a particular data type.
• Generic is a concept that allows us to define classes and methods with
placeholder.
• C# compiler replaces these placeholders with specified type at compile
time. The concept of generics is used to create general purpose classes
and methods.
• A generic type is declared by specifying a type parameter in an angle
brackets after a type name, e.g. TypeName<T> where T is a type
parameter.
• It helps you to maximize code reuse, type safety, and performance.
• You can create generic collection classes. The .NET Framework class
library contains several new generic collection classes in the
System.Collections.Generic namespace.
• You can create your own generic interfaces, classes, methods, events,
and delegates.
• You may create generic classes constrained to enable access to
methods on particular data types.
Generic Class

• Generic classes are defined using a type parameter in an angle brackets


after the class name. The following defines a generic class.

Example: Define Generic Class


class DataStore<T>
{
public T Data { get; set; }
}
using System; Output:
namespace CSharpProgram
{ This is generic class
101
class GenericClass<T>
H
{
public GenericClass(T msg)
{
Console.WriteLine(msg);
}
}
class Program
{
public static void Main(string[] args)
{
GenericClass<string> g1 = new GenericClass<string> ("This is
generic class");
GenericClass<int> g2 = new GenericClass<int>(101);
GenericClass<char> g3= new GenericClass<char>(‘H');
}
class Program
{
• using System; static void Main(string[] args)
namespace CSharpProgram {
GenericClass genC = new GenericClass();
{ genC.Show("This is generic method");
genC.Show(101);
class GenericClass genC.Show(“visual programming”);
}
{ }
public void Show<T>(T msg) }

{
Console.WriteLine(msg);
}
}

You might also like