0% found this document useful (0 votes)
16 views26 pages

Module 2 & 3

The document provides an overview of the C# object model, explaining the concepts of objects and classes, including their definitions and examples. It covers various aspects such as the use of the 'this' keyword, nested classes, partial classes and methods, access modifiers, value types using enums and structures, and arrays in C#. Additionally, it discusses the advantages and disadvantages of arrays and provides examples of different types of arrays including single-dimensional, multidimensional, jagged arrays, and their initialization.

Uploaded by

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

Module 2 & 3

The document provides an overview of the C# object model, explaining the concepts of objects and classes, including their definitions and examples. It covers various aspects such as the use of the 'this' keyword, nested classes, partial classes and methods, access modifiers, value types using enums and structures, and arrays in C#. Additionally, it discusses the advantages and disadvantages of arrays and provides examples of different types of arrays including single-dimensional, multidimensional, jagged arrays, and their initialization.

Uploaded by

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

Understanding the C# object model

C# Object and Class

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.

Let's see an example to create object using new keyword.


Student s1 = new Student ();//creating an object of Student
In this example, Student is the type and s1 is the reference variable that refers to the instance of
Student class. The new keyword allocates memory at runtime.

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.


class <Class_name> {
<access_modifier> [static] variable_type fields, constants
<access_modifier> [static] return_type methodName(args..){ - - - - }
... constructors, destructors ...
... properties ...// for component-based programming
... events ...
... indexers ... // for convenience
... overloaded operators ...
... nested types (classes, interfaces, structs, enums, delegates)
}

C# Object and Class Example


Let's see an example of class that has two fields: id and name. It creates instance of the class,
initializes the object and prints the object value.

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

Using this keyword:


The “this” keyword refers to the current instance of a class. With the “this” keyword, you can access an
instance of a class and use it with instance methods, instance constructors, and instance properties
using System;
public class Employee
{
public int id;
public String name;
public float salary;
public Employee(int id, String name,float salary)
{
this.id = id;
this.name = name;
this.salary = salary;
}
public void display()
{
Console.WriteLine(id + " " + name+" "+salary);
}
}
class TestEmployee{
public static void Main(string[] args)
{
Employee e1 = new Employee(101, "Sanjay", 890000f);
Employee e2 = new Employee(102, "Mahesh", 490000f);
e1.display();
e2.display();

}
}

Using the Nested Classes:


A Nested class is a class that is defined inside another class. This class acts as the member of the
parent class in which it is defined.
Advantage: Accessing all the members of its outer class.

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 {
...
}
}

C# - Partial Classes and Methods


C# contains a special method is known as a partial method, which contains declaration part in one
partial class and definition part in another partial class or may contain both declaration and
definition in the same partial class.
Basically, partial methods exist in the partial class, or in the struct.

Syntax:
partial void method_name
{
// Code
}

circle1.cs
public partial class Circle {

// This file only contains


// declaration of partial method
partial void area(int p);

public void Display()


{
Console.WriteLine("Example of partial method");
}
}

circle2.cs
public partial class Circle {

public void newarea(int a)


{
area(int a);
}

// This is the definition of


// partial method
partial void area(int r)
{
int A = 3.14 * r * r;
Console.WriteLine("Area is : {0}", A);
}
}

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);
}
}

Returning a Value from a Method:


A method can return a value to the caller of the method.
If the return type is void, then the method will not return any value.
If the return type is other than void, such as int, double, string or class_type then the method can
return any type of value using return keyword.

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();
}}}

Describing Access Modifiers:


Access modifiers help to avoid jumbling of data and methods with the existing code as well as
protect an object of a class from outside interference. These modifiers do this by defining a certain
scope to access data and methods in a restricted manner.
Table 1.1: List of the access modifiers

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#:

An enum is a special "class" that represents a group of constants (unchangeable/read-only variables).


To create an enum, use the enum keyword (instead of class or interface), and separate the enum
items with a comma:
enum Season
{
Spring,
Summer,
Autumn,
Winter
}

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;
};

public class testStructure {


public static void Main(string[] args) {
Books Book1; /* Declare Book1 of type Book */
Books Book2; /* Declare Book2 of type Book */

/* 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;

/* print Book1 info */


Console.WriteLine( "Book 1 title : {0}", Book1.title);
Console.WriteLine("Book 1 author : {0}", Book1.author);
Console.WriteLine("Book 1 subject : {0}", Book1.subject);
Console.WriteLine("Book 1 book_id :{0}", Book1.book_id);

/* print Book2 info */


Console.WriteLine("Book 2 title : {0}", Book2.title);
Console.WriteLine("Book 2 author : {0}", Book2.author);
Console.WriteLine("Book 2 subject : {0}", Book2.subject);
Console.WriteLine("Book 2 book_id : {0}", Book2.book_id);

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

int[,] arr2d; // two-dimensional array


int[, ,] arr3d; // three-dimensional array
int[, , ,] arr4d ; // four-dimensional array
int [,] arrjd2; // jagged 2d array
int [, ,]jdarr3; // jagged 3d array
int [, , ,]jdarr4;// jagged 4d array
Array Declaration and Initialization
An array can be declared using by specifying the type of its elements with square brackets.

Example: Array Declaration


int[] evenNums; // integer array

string[] cities; // string array


The following declares and adds values into an array in a single statement.

Example: Array Declaration & Initialization


int[] evenNums = new int[5]{ 2, 4, 6, 8, 10 };

string[] cities = new string[3]{ "Mumbai", "London", "New York" };


Above, evenNums array can store up to five integers. The number 5 in the square brackets new int[5]
specifies the size of an array. In the same way, the size of cities array is three. Array elements are
added in a comma-separated list inside curly braces { }.

Arrays type variables can be declared using var without square brackets.

Example: Array Declaration using var


var evenNums = new int[]{ 2, 4, 6, 8, 10};

var cities = new string[]{ "Mumbai", "London", "New York" };


If you are adding array elements at the time of declaration, then size is optional. The compiler will
infer its size based on the number of elements inside curly braces, as shown below.

Example: Short Syntax of Array Declaration


int[] evenNums = { 2, 4, 6, 8, 10};

string[] cities = { "Mumbai", "London", "New York" }


The following example demonstrate invalid array declarations.

Example: Invalid Array Creation


//must specify the size
int[] evenNums = new int[];

//number of elements must be equal to the specified size


int[] evenNums = new int[5] { 2, 4 };

//cannot use var with array initializer


var evenNums = { 2, 4, 6, 8, 10};

2d aray:

using System;

public class Program


{
public static void Main()
{
int[,] arr2d = new int[3,2]{
{1, 2},
{3, 4},
{5, 6}
};

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;

public class Program


{
public static void Main()
{
int[,,] arr3d1 = new int[1, 2, 2]{
{{1, 2}, {3, 4}} // 1 row of two-dimensional array
};

int[,,] arr3d2 = new int[2, 2, 2]{ // 2 rows of two-dimensional array


{{1, 2}, {3, 4}},
{{5, 6}, {7, 8}}
};

int[,,] arr3d3 = new int[2, 2, 3]{ // 2 rows of two-dimensional array


{{1, 2, 3}, {4, 5, 6}},
{{7, 8, 9}, {10, 11, 12}}
};

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;

public class Program


{
public static void Main()
{
int[,,,] arr4d1 = new int[1, 1, 2, 2]{
{
{{1, 2}, {3, 4}}
}
};

int[,,,] arr4d2 = new int[1, 2, 2, 2]{


{
{{1, 2}, {3, 4}},
{{5, 6}, {7, 8}}
}
};
Console.WriteLine("arr4d1");
Console.WriteLine(arr4d1[0, 0, 0, 0]);
Console.WriteLine(arr4d1[0, 0, 0, 1]);
Console.WriteLine(arr4d1[0, 0, 1, 0]);
Console.WriteLine(arr4d1[0, 0, 1, 1]);

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:

C# Jagged Arrays: An Array of Array


A jagged array is an array of array. Jagged arrays store arrays instead of literal values.

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.

The following example declares jagged arrays.

Example: Jagged Arrays


int[][] jArray1 = new int[2][]; // can include two single-dimensional arrays
int[][,] jArray2 = new int[3][,]; // can include three two-dimensional arrays

using System;

public class Program


{
public static void Main()
{
int[][] jArray = new int[2][]{
new int[3]{1, 2, 3},

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:

Inheritance (Derived and Base Class)


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 Vehicle // base class (parent)


{
public string brand = "Ford"; // Vehicle field
public void honk() // Vehicle method
{
Console.WriteLine("Tuut, tuut!");
}
}

class Car : Vehicle // derived class (child)


{
public string modelName = "Mustang"; // Car field
}

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);
}
}

Inheritance is of four types, which are as follows:


i. Single Inheritance: Refers to inheritance in which there is only one base class
and one derived class. This means that a derived class
inherits properties from single base class.
ii. Hierarchical Inheritance: Refers to inheritance in which multiple derived classes
are inherited from the same base class.
iii. Multilevel Inheritance: Refers to inheritance in which a child class is derived
from a class, which in turn is derived from another
class.
iv. Multiple Inheritance: Refers to inheritance in which a child class is derived from
multiple base class.

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.");
}
}

class Dog : Animal {


public void Bark() {
Console.WriteLine("Dog is barking.");
}
}

// 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.");
}
}

class Eagle : Bird {


public void Hunt() {
Console.WriteLine("Eagle is hunting.");
}
}

class Penguin : Bird {


public void Swim() {
Console.WriteLine("Penguin is swimming.");
}
}

// multiple inheritance
interface I1 {
void Method1();
}

interface I2 {
void Method2();
}

class MyClass : I1, I2 {


public void Method1() {
Console.WriteLine("Method1 is called.");
}

public void Method2() {


Console.WriteLine("Method2 is called.");
}
}

// 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

The abstract keyword is used for classes and methods:

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");
}
}

// Derived class (inherit from Animal)


class Pig : Animal
{
public override void animalSound()
{
// The body of animalSound() is provided here
Console.WriteLine("The pig says: wee wee");
}
}

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
}
}

Why And When To Use Abstract Classes and Methods?


To achieve security - hide certain details and only show the important details of an object.

Note: Abstraction can also be achieved with Interfaces

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)
}

// Pig "implements" the IAnimal interface


class Pig : IAnimal
{
public void animalSound()
{
// The body of animalSound() is provided here
Console.WriteLine("The pig says: wee wee");
}
}

class Program
{
static void Main(string[] args)
{
Pig myPig = new Pig(); // Create a Pig object
myPig.animalSound();
}
}

Garbage Collection in C#:


Garbage collection is a memory management technique used in the .NET Framework and many
other programming languages. In C#, the garbage collector is responsible for managing memory and
automatically freeing up memory that is no longer being used by the application.

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.

Some of the key features of the garbage collector in C# include:


• Automatic memory management
• Low impact on application performance: The garbage collector runs in the background and
typically has a low impact on application performance. However, in some cases, garbage
collection can cause brief pauses or slowdowns in the application, particularly when large
amounts of memory need to be freed up at once.
• Generation-based collection: The garbage collector in C# uses a generation-based approach
to memory management. Objects are initially allocated in a “young” generation and are
moved to an “old” generation if they survive multiple garbage collection cycles. This
approach helps reduce the amount of time required for garbage collection, as most objects
are collected in the young generation.
• Finalization: The garbage collector also provides support for finalization, which is a process
that allows objects to perform cleanup tasks before they are destroyed. Objects with
finalizers are moved to a separate finalization queue, which is processed by the garbage
collector after all other objects have been collected.

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.

Phases in Garbage Collection:


C# Resource Management:

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.

public class MyClass : IDisposable


{
private bool disposed = false;

// Dispose method to release resources


public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}

protected virtual void Dispose(bool disposing)


{
if (!disposed)
{
if (disposing)
{
// Dispose managed resources
}

// Dispose unmanaged resources

disposed = true;
}
}

// Finalizer (destructor) to handle cleanup in case Dispose is not called


~MyClass()
{
Dispose(false);
}
}
File I/O and Streams:

When working with files, streams, or network resources, it's important to use using statements or
call Dispose() explicitly to release resources promptly.

using (FileStream fs = new FileStream("example.txt", FileMode.Open))


{
// Use the file stream
} // The file stream is automatically closed and resources are released.

Database Connections:
When working with database connections, use using statements or explicitly close connections when
they are no longer needed.

using (SqlConnection connection = new SqlConnection(connectionString))


{
connection.Open();
// Use the database connection
} // The connection is automatically closed and resources are released.

Network Resources:
Similar to file I/O, make sure to properly close and release network resources when done using them.

using (TcpClient client = new TcpClient())


{
// Use the TcpClient
} // The TcpClient is automatically closed and resources are released.

Async/Await:
When working with asynchronous operations, ensure that resources are properly managed, and use
the using statement with asynchronous resources where applicable.

using (HttpClient httpClient = new HttpClient())


{
// Use the HttpClient asynchronously
} // The HttpClient is automatically disposed when it goes out of scope.

Resource Leak Detection:


Utilize tools and techniques (like code analysis tools and profilers) to detect potential resource leaks
and ensure proper cleanup.
Proper resource management is crucial for writing robust and efficient C# applications, preventing
memory leaks and ensuring that resources are released in a timely manner.

You might also like