0% found this document useful (0 votes)
69 views16 pages

Unit - 2 (Chapter 1)

C#

Uploaded by

kampanagowda999
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)
69 views16 pages

Unit - 2 (Chapter 1)

C#

Uploaded by

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

UNIT – 2 (CHAPTER – 1 OOPS with C#)

OOP stands for Object-Oriented Programming.

Classes and Objects:


A Class is like an object constructor, or a "blueprint" for creating objects.
Object is a real world entity
Create a Class

To create a class, use the class keyword:


Create a class named "Car" with a variable color:
Create an Object

An object is created from a class. We have already created the class named Car, so now we can use
this to create objects.

To create an object of Car, specify the class name, followed by the object name, and use the
keyword new:
Example

Create an object called "myObj" and use it to print the value of color:
using System;
namespace MyApplication
{
class Car OUTPUT:
{
string color = "red"; red
static void Main(string[] args)
{
Car myObj = new Car();
Console.WriteLine(myObj.color);
}
}
}

Class Members
Fields and methods inside classes are often referred to as "Class Members":
Fields
variables inside a class are called fields
Example:
using System;

namespace MyApplication
{
class Car
{
string color = "red";
int maxSpeed = 200;

HBA ASST PROF CS DEPT, PESSAC MANDYA 1


UNIT – 2 (CHAPTER – 1 OOPS with C#)

static void Main(string[] args)


OUTPUT:
{
Car myObj = new Car(); red
Console.WriteLine(myObj.color);
Console.WriteLine(myObj.maxSpeed); 200
}
}
}
Constructors
A constructor is a special method that is used to initialize objects.

Example:

car.cs
using System;

namespace MyApplication
{
class Car
{
public string model;
public string color;
public int year;

public Car(string modelName, string modelColor, int modelYear)


{
model = modelName;
color = modelColor;
year = modelYear;
}
}
}

program.cs

using System;

namespace MyApplication

class Program

static void Main(string[] args)

HBA ASST PROF CS DEPT, PESSAC MANDYA 2


UNIT – 2 (CHAPTER – 1 OOPS with C#)

Car Ford = new Car("Mustang", "Red", 1969);


OUTPUT:
Car Opel = new Car("Astra", "White", 2005); Mustang
Astra
Console.WriteLine(Ford.model);

Console.WriteLine(Opel.model);

Access Modifiers

Modifier Description

Public The code is accessible for all classes

Private The code is only accessible within the same class

protected The code is accessible within the same class, or in a class that is inherited from that class.

Internal The code is only accessible within its own assembly, but not from another assembly.

There's also two combinations: protected internal and private protected.

lets focus on public and private modifiers.

Private Modifier
If you declare a field with a private access modifier, it can only be accessed within the same
class:
Example
class Car
{
private string model = "Mustang";
static void Main(string[] args)
{ output:
Car myObj = new Car();
Console.WriteLine(myObj.model); Mustang
}
}

HBA ASST PROF CS DEPT, PESSAC MANDYA 3


UNIT – 2 (CHAPTER – 1 OOPS with C#)

Public Modifier

If you declare a field with a public access modifier, it is accessible for all classes:

Example
class Car
{
public string model = "Mustang"; output:
}
class Program Mustang
{
static void Main(string[] args)
{
Car myObj = new Car();
Console.WriteLine(myObj.model);
}
}

Properties (Get and Set)


Properties and Encapsulation

The meaning of Encapsulation, is to make sure that "sensitive" data is hidden from users. To
achieve this, you must:

 declare fields/variables as private


 provide public get and set methods, through properties, to access and update the
value of a private field

Properties

the private variables can only be accessed within the same class (an outside class has no
access to it). However, sometimes we need to access them - and it can be done with
properties.

A property is like a combination of a variable and a method, and it has two methods:
a get and a set method:

read-only (if you only use the get method), or write-only (if you only use the set method)

Example
Now we can use the Name property to access and update the private field of the Person class:
class Person
{
private string name; // field
public string Name // property
{

HBA ASST PROF CS DEPT, PESSAC MANDYA 4


UNIT – 2 (CHAPTER – 1 OOPS with C#)

get { return name; }


set { name = value; } output:
}
} Liam

class Program
{
static void Main(string[] args)
{
Person myObj = new Person();
myObj.Name = "Liam";
Console.WriteLine(myObj.Name);
}
}

Inheritance (Derived and Base Class)

In C#, it is possible to inherit fields and methods from one class to another(to create a new
class from an existing class).

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

Example:

using System;
namespace MyApplication
{
class Vehicle
{
public string brand = "Ford";
public void honk()
{
Console.WriteLine("Tuut, tuut!");
}
}
class Car : Vehicle // Derived class
{
public string modelName = "Mustang";
}
class Program
{
static void Main(string[] args)

HBA ASST PROF CS DEPT, PESSAC MANDYA 5


UNIT – 2 (CHAPTER – 1 OOPS with C#)

{
Car myCar = new Car();
OUTPUT:
myCar.honk(); Tuut, tuut!
Console.WriteLine(myCar.brand + " " + myCar.modelName); Ford Mustang
}
}
}

Polymorphism:

Polymorphism means "many forms",

Polymorphism uses those methods to perform different tasks. This allows us to perform a
single action in different ways.

For example, think of a base class called Animal that has a method called animalSound().
Derived classes of Animals could be Pigs, Cats, Dogs, Birds - And they also have their own
implementation of an animal sound (the pig oinks, and the cat meows, etc.):

using System;
namespace MyApplication
{
class Animal
{
public virtual void animalSound()
{
Console.WriteLine("The animal makes a sound");
}
}

class Pig : Animal


{ OUTPUT:
public override void animalSound()
{ The animal makes a sound
Console.WriteLine("The pig says: wee wee");
} The pig says: wee wee
} The dog says: bow wow
class Dog : Animal
{
public override void animalSound()
{
Console.WriteLine("The dog says: bow wow");
}
}
class Program
{
static void Main(string[] args)

HBA ASST PROF CS DEPT, PESSAC MANDYA 6


UNIT – 2 (CHAPTER – 1 OOPS with C#)

{
Animal myAnimal = new Animal();
Animal myPig = new Pig();
Animal myDog = new Dog();
myAnimal.animalSound();
myPig.animalSound();
myDog.animalSound();
}
}
}
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: is a restricted class that cannot be used to create objects (to access it,
it must be inherited from another class).
 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).

An abstract class can have both abstract and regular methods:

using System;
namespace MyApplication
{
// Abstract class
abstract class Animal
{
// Abstract method (does not have a body)
public abstract void animalSound();
// Regular method
public void sleep() OUTPUT:
{
Console.WriteLine("Zzz"); The pig says:Wee Wee
}
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");

HBA ASST PROF CS DEPT, PESSAC MANDYA 7


UNIT – 2 (CHAPTER – 1 OOPS with C#)

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

myPig.animalSound();
myPig.sleep();
}
}
}

That we use the : symbol to inherit from a class, and that we use the override keyword to
override the base class method.

Interfaces:
An interface is a completely "abstract class", which can only contain abstract methods and
properties (with empty bodies):

To access the interface methods, the interface must be "implemented" (kinda like inherited)
by another class. To implement an interface, use the : symbol (just like with inheritance). The
body of the interface method is provided by the "implement" class. Note that you do not have
to use the override keyword when implementing an interface:

Example
using System;
namespace MyApplication
{
interface IAnimal
{
void animalSound();
}
class Pig : IAnimal
{
public void animalSound()
{
Console.WriteLine("The pig says: wee wee");
}
} OUTPUT:
class Program
{ The pig says: wee wee
static void Main(string[] args)
{
Pig myPig = new Pig();

HBA ASST PROF CS DEPT, PESSAC MANDYA 8


UNIT – 2 (CHAPTER – 1 OOPS with C#)

myPig.animalSound();
}
}
}

Notes on Interfaces:

 Like abstract classes, interfaces cannot be used to create objects (in the example
above, it is not possible to create an "IAnimal" object in the Program class)
 Interface methods do not have a body - the body is provided by the "implement" class
 On implementation of an interface, you must override all of its methods
 Interfaces can contain properties and methods, but not fields/variables
 Interface members are by default abstract and public
 An interface cannot contain a constructor (as it cannot be used to create objects)

Why And When To Use Interfaces?

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

2) C# does not support "multiple inheritance" (a class can only inherit from one base class).
However, it can be achieved with interfaces, because the class can implement multiple
interfaces.

Multiple Interfaces

To implement multiple interfaces, separate them with a comma:

Example
using System;
namespace MyApplication
{
interface IFirstInterface
{
void myMethod();
}

interface ISecondInterface
{
void myOtherMethod();
}
class DemoClass : IFirstInterface, ISecondInterface
{
public void myMethod()
{
Console.WriteLine("Some text..");
}

HBA ASST PROF CS DEPT, PESSAC MANDYA 9


UNIT – 2 (CHAPTER – 1 OOPS with C#)

public void myOtherMethod()


{
Console.WriteLine("Some other text...");
}
}

class Program
{
static void Main(string[] args)
{ OUTPUT:
DemoClass myObj = new DemoClass(); Some text..
myObj.myMethod();
myObj.myOtherMethod(); Some other text...
}
}
}

Operator overloading:
 The concept of overloading a function can also be applied to operator
 Operator overloading gives the ability to use the same operator to do various operations.
 It provides additional capabilities to C# operators when they are applied to user-defined data
types.
 It enables to make user-defined implementation of various operations where one or both of
the operands are of a user-defined class.
 Only the predefined set of C# operators can be overloaded.
 To make operations on a user-defined data type is not as simple as the operations on a built-in
data type.
 To use operators with user-defined data types, they need to be overloaded according to a
programmer’s requirement.
 An operator can be overloaded by defining a function to it.
 The function of the operator is declared by using the operator keyword.
 Operators may be considered as functions internal to the compiler.
The following table describes the overloading ability of the various operators available in C#:

Operators Description
+, -, !, ~, ++, – – unary operators take one operand and can be overloaded.

+, -, *, /, % Binary operators take two operands and can be overloaded.


==, !=, = Comparison operators can be overloaded.
&&, || Conditional logical operators cannot be overloaded directly

+=, -+, *=, /=, %=, = Assignment operators cannot be overloaded.

HBA ASST PROF CS DEPT, PESSAC MANDYA 10


UNIT – 2 (CHAPTER – 1 OOPS with C#)

Example:
using System;
namespace OperatorOverloading
{
class NewClass
{
public string str;
public int num;
public static NewClass operator +(NewClass obj1, NewClass obj2)
{
NewClass obj3=new newClass();
obj3.str=obj1.str+obj2.str;
obj3.num=obj1.num+obj2.num;
return obj3;
}
}
class Program
{
static void main(string[] args)
{
NewClass obj1=new NewClass();
obj1.str=”Mohammad”;
obj1.num=20; OUTPUT:
NewClass obj2=new NewClass();
obj2.str=”Adil”; MohammadAdil
obj2.num=30; 50
NewClass obj3=new NewClass();
obj3=obj1+obj2;
Console.WriteLine(obj3.str);
Console.WriteLine(obj3.num);
Console.ReadLine();
}
}
}
}

Delegates:
 Delegate Meaning From Google: A person sent or Authorized to represent others, In
Particular An elected Representative Sent To a Conference.
 Delegate Is a type which holds a method’s reference in an object.
 it is also called function pointer.
 Delegate is of reference type.
 Delegate signature should be as same as the method signature referencing by a Delegate.
 Delegate can point to a parameterized method OR non-parameterized method.
 Delegate Has No Implementation Means No Body with {}.

HBA ASST PROF CS DEPT, PESSAC MANDYA 11


UNIT – 2 (CHAPTER – 1 OOPS with C#)

 we can use Invoke() Method with Delegates.


 Delegates are used to Encapsulate methods.
 In the .Net framework, A Delegate points to one or more methods. once you Instantiate the
Delegate, the corresponding methods Invoke.
 Delegates are objects that contain references to methods that need to be Invoked Instead of
containing the actual method names
 Using Delegates, you can call any method, which Identified only at run-time.
 A delegate like having a general method name that points to various methods at different
times and invokes the required method at run-time.
 In C#, Invoking a delegate will execute the referenced method at run-time.
 To Associate a Delegate with a particular method, the method must have the same return type
and parameter type as that of the Delegate.
Example:
using System;
using System.Threading.Tasks;
namespace Delegate
{
public delegate void Calculation(int a, int b);
class Program
{
public void Addition(int a, int b)
{
int result=a+b;
Console.WriteLine(“Addition result is:{0}”, result);
}
public void subtraction(int a, int b) OUTPUT:
{
Addition result is:30
int result=a-b;
Console.WriteLine(“subtraction result is:{0}”, result); Subtraction result is:10
}

static void Main(string[] args)


{
Calculation obj=new calculation(Program.Addition);
obj1.Invoke(20,10);
Calculation obj=new calculation(Program.Subtraction);
obj2.Invoke(20,10);
Console.ReadLine();
}
}
}

HBA ASST PROF CS DEPT, PESSAC MANDYA 12


UNIT – 2 (CHAPTER – 1 OOPS with C#)

Events:
 Events are encapsulated over delegates.
 Just like properties encapsulate private fields events encapsulate delegates.
 In many scenarios we need our delegate to fire automatically when something changes so we
use Events.
 Delegates enable a publisher subscriber pattern where delegate object is the publisher and
target methods are subscribers.
 Events formalize this publisher subscribe pattern.
 All the classes subscribed to the event are notified at once.
 Common example of events is Email and Cellphone notification on completion of some task.

Example:

using System;
namespace SampleApp {
public delegate string MyDel(string str);
class EventProgram {
event MyDel MyEvent;
public EventProgram() {
this.MyEvent += new MyDel(this.WelcomeUser);
}
public string WelcomeUser(string username) {
return "Welcome " + username; OUTPUT:
}
static void Main(string[] args) { Welcome Tutorials Point
EventProgram obj1 = new EventProgram();
string result = obj1.MyEvent("Tutorials Point");
Console.WriteLine(result);
}
}
}

Errors and Exception


Errors:
Errors refer to the mistake or faults which occur during program development or
execution.
two types of error occurrences. They are as follows:
1. Compilation Errors
2. Runtime Errors

1. Compilation Error in C#
The error that occurs in a program at the time of compilation is known as a compilation error
(compile-time error). These errors occur due to syntactical mistakes in the program. That means
these errors occur by typing the wrong syntax like missing double quotes in a string value and
missing terminators in a statement, typing wrong spelling for keywords, assigning wrong data
to a variable, trying to create an object for abstract class and interface, etc. So, whenever we
compile the program, the compiler recognizes these errors and it will show us the list of errors.

HBA ASST PROF CS DEPT, PESSAC MANDYA 13


UNIT – 2 (CHAPTER – 1 OOPS with C#)

So, in simple words, we can say that this type of error occurs due to a poor understanding of
the programming language. These errors are identified by the compiler and can be rectified
before the execution of the program only. So, these errors do not cause any harm to the program
execution.

2. Runtime Error in C#
The errors which are occurred at the time of program execution are called runtime errors. These
errors occurred at runtime due to various reasons such as when we are entering the wrong data
into a variable, trying to open a file for which there is no permission, trying to connect to the
database with the wrong user id and password, the wrong implementation of logic, and missing
required resources, etc. So, in simple words, we can say that the errors which are come while
running the program are called runtime errors.
Runtime errors are dangerous because whenever they occur in the program, the program
terminates abnormally on the same line where the error gets occurred without executing the
next line of code.

Exception:
An Exception is a class in C# which is responsible for abnormal termination of the program when
runtime errors occur while running the program. So, these errors (runtime) are very dangerous
because whenever the runtime errors occur in the programs, the program gets terminated abnormally
on the same line where the error gets occurred without executing the next line of code.
Objects of Exception classes are responsible for abnormal termination of the program whenever
runtime errors occur. These exception classes are predefined under BCL (Base Class Libraries) where
a separate class is provided for each and every different type of exception like
The follow is a list of common .NET exceptions:

 System.NullReferenceException – Very common exception related to calling a method on a null


object reference
 System.IndexOutOfRangeException – Occurs attempting to access an array element that does not
exist
 System.IO.IOException – Used around many file I/O type operations
 System.Net.WebException – Commonly thrown around any errors performing HTTP calls
 System.Data.SqlClient.SqlException – Various types of SQL Server exceptions
 System.StackOverflowException – If a method calls itself recursively, you may get this exception
 System.OutOfMemoryException – If your app runs out of memory
 System.InvalidCastException – If you try to cast an object to a type that it can’t be cast to
 System.InvalidOperationException – Common generic exception in a lot of libraries
 System.ObjectDisposedException – Trying to use an object that has already been disposed

Each exception class provides a specific exception error message. All the above exception classes are
responsible for abnormal termination of the program as well as they will be displaying an error
message which specifies the reason for abnormal termination i.e. they provide an error message
specific to that error.
So, whenever a runtime error occurs in a program, first the Exception Manager under the CLR
(Common Language Runtime) identifies the type of error that occurs in the program, then creates an
object of the Exception class related to that error and throws that object which will immediately
terminate the program abnormally on the line where error got occur and display the error message
related to that class.

HBA ASST PROF CS DEPT, PESSAC MANDYA 14


UNIT – 2 (CHAPTER – 1 OOPS with C#)

Example:
using System;
namespace ExceptionHandlingDemo
{
class Program
{
static void Main(string[] args)
{ OUTPUT:
int a = 20; A VALUE:20
int b = 0;
int c; B VALUE=0
Console.WriteLine("A VALUE = " + a);
Console.WriteLine("B VALUE = " + b);
c = a / b;
Console.WriteLine("C VALUE = " + c);
Console.ReadKey();
}
}
}

Exception handling in C# using Try Catch implementation


To implement the try-catch implementation, the .NET framework provides three keywords. They are as
follows:
1. Try
2. Catch
3. finally

Try Block:
The try keyword establishes a block in which we need to write the exception causing and its related
statements. That means exception-causing statements and the related statements which we should not
execute when an exception occurred must be placed in the try block. When the exception occurred, the
CLR will create an instance of the Exception class based on the logical error and then throw that
Exception object which is going to be handled by the corresponding catch block.

Catch Block:
The catch block is used to catch the exception that is thrown from its corresponding try block. It has the
logic to take necessary actions on that caught exception. The Catch block syntax in C# looks like a
constructor. It does not take accessibility modifiers, normal modifiers, or return types. It takes only a
single parameter of type Exception or any child class of the parent Exception class. Inside the catch
block, we can write any statement which is legal in .NET including raising an exception. In this case,
we can stop the abnormal termination of the program and we can also give user understandable error
message so that the user can take necessary action to resolve the error.

Finally Block:
The keyword finally establishes a block that definitely executes the statements placed in it irrespective
of whether any exception has occurred or not. That means the statements that are placed in finally block

HBA ASST PROF CS DEPT, PESSAC MANDYA 15


UNIT – 2 (CHAPTER – 1 OOPS with C#)

are always going to be executed irrespective of whether any exception is thrown or not, irrespective of
whether the thrown exception is handled by the catch block or not.
Syntax to use Exception Handling in C#:

Example:
using System;
namespace ExceptionHandlingDemo
{
class Program
{
static void Main(string[] args)
{
int Number1, Number2, Result;
try
{
Console.WriteLine("Enter First Number:");
Number1 = int.Parse(Console.ReadLine()); OUTPUT:
Console.WriteLine("Enter Second Number:"); Enter First Number:10
Number2 = int.Parse(Console.ReadLine());
Result = Number1 / Number2; Enter Second Number:0
Console.WriteLine($"Result = {Result}");
Some Error Occurred...
}
catch
{
Console.WriteLine("Some Error Occurred...");
}
Console.ReadKey();
}
}
}

HBA ASST PROF CS DEPT, PESSAC MANDYA 16

You might also like