Module 2 & 3
Module 2 & 3
Since C# is an object-oriented language, program is designed using objects and classes in C#.
C# Object
In C#, Object is a real-world entity, for example, chair, car, pen, mobile, laptop etc. In other words,
object is an entity that has state and behaviour. Here, state means data and behaviour means
functionality. Object is a runtime entity; it is created at runtime.
Object is an instance of a class. All the members of the class can be accessed through object.
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.
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 = "ABC";
Console.WriteLine(s1.id);
Console.WriteLine(s1.name);
}
}
Output:
101 ABC
}
}
C# Nested Class
In C#, we can define a class within another class. It is known as a nested class. For example,
class OuterClass {
...
class InnerClass {
...
}
}
Syntax:
partial void method_name
{
// Code
}
circle1.cs
public partial class Circle {
circle2.cs
public partial class Circle {
When we execute the above code, then compiler combines circle1.cs and circle2.cs into a single file,
i.e. circle as shown below.
circle
Public class Circle {
public void Display()
{
Console.WriteLine("Example of partial method");
}
public void newarea(int a)
{
area(int a);
}
private void area(int r)
{
int A = 3.14 * r * r;
Console.WriteLine("Area is : {0}", A);
}
}
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;
return (area);
}
}
class ReturnValue{ static void Main(){
MyArea obj = new MyArea();
double area1= obj.RectArea();
Console.WriteLine("Area of the Rectangle:"+area1);
Console.ReadLine();
}}}
Access Speicifiers:
1. public: The type or member can be accessed by any other code in the same assembly or
another assembly that references it. The accessibility level of public members of a type is
controlled by the accessibility level of the type itself.
2. private: The type or member can be accessed only by code in the same class or struct.
3. protected: The type or member can be accessed only by code in the same class, or in a class
that is derived from that class.
4. internal: The type or member can be accessed by any code in the same assembly, but not
from another assembly. In other words, internal types or members can be accessed from
code that is part of the same compilation.
5. protected internal: The type or member can be accessed by any code in the assembly in
which it's declared, or from within a derived class in another assembly.
6. private protected: The type or member can be accessed by types derived from the class that
are declared within its containing assembly.
Creating Value Type using enum & structures:
Enumerations and structures in c#:
Structures (struct):
A structure is a value type that allows you to group data together. The two ways to access a structure
is dot operator & arrow operator.
Syntax:
Access_Modifier struct structure_name {
// Fields
// Parameterized constructor
// Constants
// Properties
// Indexers
// Events
// Methods etc.
}
Example:
using System;
struct Books {
public string title;
public string author;
public string subject;
public int book_id;
};
/* book 1 specification */
Book1.title = "C Programming";
Book1.author = "Nuha Ali";
Book1.subject = "C Programming Tutorial";
Book1.book_id = 6495407;
/* book 2 specification */
Book2.title = "Telecom Billing";
Book2.author = "Zara Ali";
Book2.subject = "Telecom Billing Tutorial";
Book2.book_id = 6495700;
Console.ReadKey();
}
}
C# Arrays:
Like other programming languages, array in C# is a group of similar types of elements that have
contiguous memory location. In C#, array is an object of base type System.Array. In C#, array index
starts from 0. We can store only fixed set of elements in C# array.
Advantages of C# Array:
Code Optimization (less code)
Random Access
Easy to traverse data
Easy to manipulate data
Easy to sort data etc.
Disadvantages of C# Array
Fixed size
C# Array Types
There are 3 types of arrays in C# programming:
Single Dimensional Array
Multidimensional Array
Jagged Array
Arrays type variables can be declared using var without square brackets.
2d aray:
using System;
Console.WriteLine(arr2d[0, 0]);
Console.WriteLine(arr2d[0, 1]);
Console.WriteLine(arr2d[1, 0]);
Console.WriteLine(arr2d[1, 1]);
Console.WriteLine(arr2d[2, 0]);
Console.WriteLine(arr2d[2, 1]);
}
}
3d array:
using System;
Console.WriteLine("arr3d2 Values");
Console.WriteLine(arr3d2[0, 0, 0]);
Console.WriteLine(arr3d2[0, 0, 1]);
Console.WriteLine(arr3d2[0, 1, 0]);
Console.WriteLine(arr3d2[0, 1, 1]);
Console.WriteLine(arr3d2[1, 0, 0]);
Console.WriteLine(arr3d2[1, 0, 1]);
Console.WriteLine(arr3d2[1, 1, 0]);
Console.WriteLine(arr3d2[1, 1, 1]);
}
}
4d array:
using System;
Console.WriteLine("arr4d2");
Console.WriteLine(arr4d2[0, 0, 0, 0]);
Console.WriteLine(arr4d2[0, 0, 0, 1]);
Console.WriteLine(arr4d2[0, 0, 1, 0]);
Console.WriteLine(arr4d2[0, 0, 1, 1]);
Console.WriteLine(arr4d2[0, 1, 0, 0]);
Console.WriteLine(arr4d2[0, 1, 0, 1]);
Console.WriteLine(arr4d2[0, 1, 1, 0]);
Console.WriteLine(arr4d2[0, 1, 1, 1]);
}
}
Jagged Array:
A jagged array is initialized with two square brackets [][]. The first bracket specifies the size of an
array, and the second bracket specifies the dimensions of the array which is going to be stored.
using System;
new int[4]{4, 5, 6, 7}
};
Console.WriteLine(jArray[0][0]);
Console.WriteLine(jArray[0][1]);
Console.WriteLine(jArray[0][2]);
Console.WriteLine(jArray[1][0]);
Console.WriteLine(jArray[1][1]);
Console.WriteLine(jArray[1][2]);
Console.WriteLine(jArray[1][3]);
}
}
C# Inheritance:
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 Program
{
static void Main(string[] args)
{
// Create a myCar object
Car myCar = new Car();
// Call the honk() method (From the Vehicle class) on the myCar object
myCar.honk();
// Display the value of the brand field (from the Vehicle class) and the value of the modelName
from the Car class
Console.WriteLine(myCar.brand + " " + myCar.modelName);
}
}
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.
using System;
// single inheritance
class Animal {
public void Eat() {
Console.WriteLine("Animal is eating.");
}
}
// multi-level inheritance
class Mammal : Animal {
public void Run() {
Console.WriteLine("Mammal is running.");
}
}
class Horse : Mammal {
public void Gallop() {
Console.WriteLine("Horse is galloping.");
}
}
// hierarchical inheritance
class Bird : Animal {
public void Fly() {
Console.WriteLine("Bird is flying.");
}
}
// multiple inheritance
interface I1 {
void Method1();
}
interface I2 {
void Method2();
}
// main program
class Program {
static void Main(string[] args) {
// single inheritance
Dog dog = new Dog();
dog.Eat();
dog.Bark();
// multi-level inheritance
Horse horse = new Horse();
horse.Eat();
horse.Run();
horse.Gallop();
// hierarchical inheritance
Eagle eagle = new Eagle();
Penguin penguin = new Penguin();
eagle.Fly();
eagle.Hunt();
penguin.Fly();
penguin.Swim();
// multiple inheritance
MyClass myClass = new MyClass();
myClass.Method1();
myClass.Method2();
Console.ReadLine();
}
}
C# Abstraction
Abstract Classes and Methods
Data abstraction is the process of hiding certain details and showing only essential information to the
user.
Abstraction can be achieved with either abstract classes or interfaces
Abstract class: The main purpose of the Abstract classes is to make classes that only represent base
classes, and don’t want anyone to create objects of these class types.
Abstract method: Abstract methods have no implementation, so the method definitions is followed
by a semicolon instead of a normal method block.
abstract class Animal
{
public abstract void animalSound();
public void sleep()
{
Console.WriteLine("Zzz");
}
}
// Abstract class
abstract class Animal
{
// Abstract method (does not have a body)
public abstract void animalSound();
// Regular method
public void sleep()
{
Console.WriteLine("Zzz");
}
}
class Program
{
static void Main(string[] args)
{
Pig myPig = new Pig(); // Create a Pig object
myPig.animalSound(); // Call the abstract method
myPig.sleep(); // Call the regular method
}
}
C# Interface
Interfaces
An interface is a collection of data members and member functions, but it does not
implement them”.
Interface are introduced to provide the feature of multiple inheritance to classes.
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)
}
Example
// Interface
interface IAnimal
{
void animalSound(); // interface method (does not have a body)
}
class Program
{
static void Main(string[] args)
{
Pig myPig = new Pig(); // Create a Pig object
myPig.animalSound();
}
}
The garbage collector works by periodically scanning the application’s memory to determine which
objects are still being used and which are no longer needed. Objects that are no longer being used
are marked for garbage collection, and their memory is freed up automatically by the garbage
collector.
Overall, the garbage collector is a powerful and convenient feature of the .NET Framework that can
help simplify memory management in C# applications. While it may cause occasional performance
issues, these can generally be managed with careful design and optimization of the application’s
memory usage.
Resource management in C# typically refers to the proper allocation and deallocation of resources
such as memory, file handles, network connections, and other system resources. Here are some key
aspects of resource management in C#:
Memory Management:
Garbage Collection: C# uses automatic garbage collection to manage memory. Developers don't
need to explicitly allocate or deallocate memory; the garbage collector takes care of reclaiming
memory that is no longer in use.
IDisposable Interface: For resources other than memory (e.g., file handles, database connections),
the IDisposable interface is often used. Objects that implement IDisposable should be explicitly
disposed of when they are no longer needed, to release associated resources immediately.
disposed = true;
}
}
When working with files, streams, or network resources, it's important to use using statements or
call Dispose() explicitly to release resources promptly.
Database Connections:
When working with database connections, use using statements or explicitly close connections when
they are no longer needed.
Network Resources:
Similar to file I/O, make sure to properly close and release network resources when done using them.
Async/Await:
When working with asynchronous operations, ensure that resources are properly managed, and use
the using statement with asynchronous resources where applicable.