C Sharp Unit IV Notes

Download as pdf or txt
Download as pdf or txt
You are on page 1of 9

UNIT-IV

Operator overloading (V.Imp)


 Operator is a symbol that usually represents an action or process.

 Operator overloading is a type of polymorphism in which an operator is overloaded to


give a user defined meaning.

 The mechanism of giving a special user defined meaning ( additional meaning) to an


operator is known as operator overloading.

 Operator overloading provides a flexible option for the creation of new definition for
most of the c# operators.

 We can create a new language of our own by the creative use of the method and operator
overloading techniques.

 Operators that are currently not defined in c# cannot be overloaded.

 Logical operators must be overloaded in pairs. Meaning that == and != must be


done together.

 When we overload a binary operator , it’s compound assignment equivalent is implicitly


overloaded.

Need of Operator Overloading:

Although operator overloading gives us syntactical convenience, it also help us to greatly to


generate more readable and intuitive code in a number of situations.

 Mathematical and physical modeling where we use classes to represent objects such as
co-ordinates, vectors, matrices, complex numbers and so on.

 Graphical programs where co-ordinate related objects are used to represent positions on
the screen.

 Financial programs where a class represents an amount of money.

 Text manipulations where classes are used to represent strings and sentences.
Overloadable Operators
The list of overloadable operators in c#

Category Overladable Operators


Binary Arithmetic +,*,/, -,%
Unary Arithmetic + , - , ++ , --
Binary Bitwise & , | , ^ , << , >>
Unary Bitwise ! , ~ , true , false
Logical Operators == , != , > , >= , < , <= ,

Operators that cannot be overloaded

category Not overlodable operators


Conditional operators && , ||
Compound assignment += , -= , *= , /= , %=
Other operators [ ] , { } , = , ? , -> , new , sizeof , typeof etc.

Defining Operator overloading

Overloading Unary Operators ( V.V. Imp)

The return type can be of any type except void for unary operators like !, ~, + and dot (.) but the return
type must be the type of ‘Type’ for – and ++ operators and must be a bool type for true as well as false
operators. But do remember that the true and false operators can be overloaded as pairs only. The
compilation error arises if a class declares one of these operators without declaring the other.

The following syntax shows the use of Unary operator –


operator (object) ; // here, operator is a symbol/ keyword that denotes a overloading of
operator.
operator a;

// PR- 12 C# program to illustrate the unary operator overloading


using System;
namespace Calculator {

class Calculator {

public int number1 , number2;


public Calculator(int num1 , int num2)
{ number1 = num1;
number2 = num2;
}

// Function to perform operation By changing sign of integers


public static Calculator operator -(Calculator c1)
{
c1.number1 = -c1.number1;
c1.number2 = -c1.number2;
return c1;
}
// Function to print the numbers
public void Print()
{
Console.WriteLine ("Number1 = " + number1);
Console.WriteLine ("Number2 = " + number2);
}
}

class EntryPoint
{
// Driver Code
static void Main(String []args)
{
// using overloaded - operator with the class object
Calculator calc = new Calculator(15, -25);

calc = -calc;

// To display the result


calc.Print();
}
}
}
Output :
Number1 = -15
Number2 = 25

Overloading Binary Operators

An overloaded binary operator must take two arguments; at least one of them must be of the type class or
struct, in which the operation is defined. But overloaded binary operators can return any value except the
type void. The general form of a overloaded binary operator is as follows.
public static return type operator op (Type1 t1, Type2 t2)
{
//Statements ;
}

An example to demonstrate a binary operator overloading.

// PR- 13 Binary operator overloading to perform addition on two complex numbers


using System;
class Complex
{
private int x;
private int y;
public Complex()
}
public Complex(int i, int j)
{
x = i;
y = j;
}
public void ShowXY()
{
Console.WriteLine("{0} {1}",x,y);
}
public static Complex operator +(Complex c1,Complex c2)
{
Complex temp = new Complex();
temp.x = c1.x+c2.x;
temp.y = c1.y+c2.y;
return temp;
}
}
class MyClient
{
public static void Main()
{
Complex c1 = new Complex(10,20);
c1.ShowXY(); // displays 10 & 20
Complex c2 = new Complex(20,30);
c2.ShowXY(); // displays 20 & 30
Complex c3 = new Complex();
c3 = c1 + c2;
c3.ShowXY(); // dislplays 30 & 50
}
}

What is Interface? ( V. Imp)


An interface is defined as a syntactical contract that all the classes inheriting the interface should
follow. The interface defines the 'what' part of the syntactical contract and the deriving classes define
the 'how' part of the syntactical contract.
Interfaces define properties, methods, and events, which are the members of the interface. Interfaces
contain only the declaration of the members. It is the responsibility of the deriving class to define the
members. It often helps in providing a standard structure that the deriving classes would follow.

Abstract classes to some extent serve the same purpose, however, they are mostly used when only few
methods are to be declared by the base class and the deriving class implements the functionalities.

Declaring Interfaces
Interfaces are declared using the interface keyword. It is similar to class declaration. Interface
statements are public by default. Following is an example of an interface declaration
public interface ITransactions {
// interface members
void showTransaction();
double getAmount();
}
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System;

namespace InterfaceApplication {

public interface ITransactions {


// interface members
void showTransaction();
double getAmount();
}
public class Transaction : ITransactions {
private string tCode;
private string date;
private double amount;

public Transaction() {
tCode = " ";
date = " ";
amount = 0.0;
}
public Transaction(string c, string d, double a) {
tCode = c;
date = d;
amount = a;
}
public double getAmount() {
return amount;
}
public void showTransaction() {
Console.WriteLine("Transaction: {0}", tCode);
Console.WriteLine("Date: {0}", date);
Console.WriteLine("Amount: {0}", getAmount());
}
}
class Tester {

static void Main(string[] args) {


Transaction t1 = new Transaction("001", "8/10/2012", 78900.00);
Transaction t2 = new Transaction("002", "9/10/2012", 451900.00);

t1.showTransaction();

t2.showTransaction();

Console.ReadKey();

}
Transaction: 001
Date: 8/10/2012
Amount: 78900
Transaction: 002
Date: 9/10/2012
Amount: 451900

What is an abstract class in c#? ( V. imp 3 marks)


An abstract class is an incomplete class or special class we can't instantiate. We can use an
abstract class as a base Class. An abstract method must be implemented in the non-abstract
class using the override keyword. After overriding the abstract method is in the non-Abstract class.
We can derive this class in another class and again we can override the same abstract method with
it.

Features

1. An abstract class can inherit from a class and one or more interfaces.
2. An abstract class contains abstract and non-Abstract methods.
3. An Abstract class can have modifiers for methods, properties etc.
4. An Abstract class can have constants and fields.
5. An abstract class can implement a property.
6. An abstract class can have constructors or destructors.
7. An abstract class cannot be inherited from by structures.
8. An abstract class cannot support multiple inheritance.
Abstract class and Interface Difference

Abstract Class Interface


Interface can be only variable type and not
We cannot create an instance of the this class.
instance.
It can have constructor. It cannot have constructor.
It can be derived to some other class. It is created to be derived by other class.
It can have implementation(non abstract) of one or more
It cannot have function definition.
methods.
Concrete class can implement many
Concrete class can implement only one abstract class
interfaces
It can or cannot contain the abstract methods It should only have the method signatures.
All the members of interface are public by
It can have private, protected, internal data members.
default.
It cannot be derived to a structure. It can be derived by a structure.

Exception Handling in c# ( V.V. Imp)


Debugging is process of finding and correcting errors in the program code.

An exception is a problem that arises during the execution ( Run


Time) of a program. A C# exception is a response to an exceptional
circumstance that arises while a program is running, such as an attempt to
divide by zero.

Exceptions provide a way to transfer control from one part of a program to


another. C# exception handling is built upon four
keywords: try, catch, finally, and throw.

 try − A try block enclose the code that could throw an exception. A try
block identifies a block of code for which particular exceptions is
activated. It is followed by one or more catch blocks.

 catch − A program catches an exception with an exception handler at the place


in a program where you want to handle the problem. The catch keyword
indicates the catching of an exception.

 finally − The finally block is used to execute a given set of statements,


whether an exception is thrown or not thrown i.e. Finally clause will be
executed even if no exception found . For example, if you open a file, it
must be closed whether an exception is raised or not.

 throw − A program throws an exception when a problem shows up. This


is done using a throw keyword.

Exception Classes ( Imp)

Sr.No. Exception Class & Description

1 System.IO.IOException
Handles I/O errors.

2 System.IndexOutOfRangeException

Handles errors generated when a method refers to an array index out of


range.

3 System.ArrayTypeMismatchException

Handles errors generated when type is mismatched with the array type.

4 System.NullReferenceException

Handles errors generated from referencing a null object.

5 System.DivideByZeroException

Handles errors generated from dividing a dividend with zero.

6
System.InvalidCastException
Handles errors generated during typecasting.

System.OutOfMemoryException
7 Handles errors generated from insufficient free memory.

8
System.StackOverflowException
Handles errors generated from stack overflow.

Exception objects are derived from the exception class.

You might also like