SlideShare a Scribd company logo
Operator Overloading
• C# allows you to define the meaning of an
operator relative to a class that you create. This
process is called operator overloading.
• A principal advantage of operator overloading is
that it allows you to seamlessly integrate a new
class type into your programming environment.
• Once operators are defined for a class, you can
operate on objects of that class using the normal
C# expression syntax.
• You can even use an object in expressions
involving other types of data.
• Operator overloading is closely related to
method overloading. To overload an operator,
use the operator keyword to define an
operator method, which defines the action of
the operator relative to its class.
There are two forms of operator methods:
• one for unary operators and
• one for binary operators.
// General form for overloading a unary operator
public static ret-type operator op (param-type operand)
{
// operations
}
// General form for overloading a binary operator
public static ret-type operator op (param-type1
operand1, param-type1 operand2 )
{
// operations
}
• the operator that you are overloading, such as
+ or /, is substituted for op .
• The ret-type specifies the type of value
returned by the specified operation.
• the return value is often of the same type as
the class for which the operator is being
overloaded.
• For unary operators, the operand is passed in
operand. For binary operators, the operands
are passed in operand1 and operand2.
• Operator methods must be both public and
static.
• For unary operators, the operand must be of
the same type as the class for which the
operator is being defined.
• For binary operators, at least one of the
operands must be of the same type as its
class.
• Operator parameters must not use the ref or
out modifier.
class ThreeD {
int x, y, z;
public ThreeD() { x = y = z = 0; }
public ThreeD(int i, int j, int k) { x = i; y = j; z = k; }
public static ThreeD operator +(ThreeD op1,
ThreeD op2)
{ ThreeD result = new ThreeD();
result.x = op1.x + op2.x;
result.y = op1.y + op2.y;
result.z = op1.z + op2.z;
return result; }
public static ThreeD operator -(ThreeD op1, ThreeD
op2)
{
ThreeD result = new ThreeD();
result.x = op1.x - op2.x;
result.y = op1.y - op2.y;
result.z = op1.z - op2.z;
return result;
}
public void Show()
{ Console.WriteLine(x + ", " + y + ", " + z);
}
class ThreeDDemo {
static void Main() {
ThreeD a = new ThreeD(1, 2, 3);
ThreeD b = new ThreeD(10, 10, 10);
ThreeD c;
Console.Write("Here is a: ");
a.Show();
Console.Write("Here is b: ");
b.Show();
c = a + b; Console.Write("Result of a + b: ");
c.Show();
c = a + b + c; // add a, b, and c together
Console.Write("Result of a + b + c: ");
c.Show();
c = c - a; Console.Write("Result of c - a: ");
c.Show();
c = c - b; Console.Write("Result of c - b: ");
c.Show();
}
output
Here is a: 1, 2, 3
Here is b: 10, 10, 10
Result of a + b: 11, 12, 13
Result of a + b + c: 22, 24, 26
Result of c - a: 21, 22, 23
Result of c - b: 11, 12, 13
Overload unary(- or ++)
class ThreeD {
int x, y, z;
public ThreeD() { x = y = z = 0; }
public ThreeD(int i, int j, int k) { x = i; y = j; z = k; }
public static ThreeD operator -(ThreeD op)
{
ThreeD result = new ThreeD();
result.x = -op.x;
result.y = -op.y;
result.z = -op.z;
return result; }
public static ThreeD operator ++(ThreeD op)
{
ThreeD result = new ThreeD();
result.x = op.x + 1;
result.y = op.y + 1;
result.z = op.z + 1;
return result;
}
public void Show()
{ Console.WriteLine(x + ", " + y + ", " + z);
}}
class ThreeDDemo {
static void Main() {
ThreeD a = new ThreeD(1, 2, 3);
ThreeD b = new ThreeD(10, 10, 10);
ThreeD c = new ThreeD();
c = -a;
// assign -a to c
Console.Write("Result of -a: ");
c.Show();
c = a++;
// post-increment a
Console.WriteLine("Given c = a++");
Console.Write("c is ");
c.Show();
Console.Write("a is ");
a.Show();
Next..
The operators that you can overload are:
The operators that you can not
overload are:
Binary with int

class ThreeD {
int x, y, z;
public ThreeD() { x = y = z = 0; }
public ThreeD(int i, int j, int k) { x = i; y = j; z = k; }
public static ThreeD operator +(ThreeD op1, int
op2)
{
ThreeD result = new ThreeD();
result.x = op1.x + op2;
result.y = op1.y + op2;
result.z = op1.z + op2;
•
•
•
•
•
•
•
•
•

public void Show()
{
Console.WriteLine(x + ", " + y + ", " + z);
}}
class ThreeDDemo {
static void Main() {
ThreeD a = new ThreeD(1, 2, 3);
ThreeD b = new ThreeD(10, 10, 10);
ThreeD c = new ThreeD();
a.Show();
b.Show();
c = b + 10; // ThreeD + int
Console.Write("Result of b + 10: ");
c.Show();
Next..
Conversion Operators
• C# allows you to create a special type of
operator method called a conversion
operator.
• A conversion operator converts an object of
your class into another type.
• Conversion operators help fully integrate
class types into the C# programming
environment by allowing objects of a class to
be freely mixed with other data types as long
as a conversion to those other types is
defined.
two forms of conversion operators,
implicit and explicit
• public static operator implicit target-type
(source-type v) { return value; }
• public static operator explicit target-type
(source-type v) { return value; }
• target-type is the target type that you are
converting to; source-type is the type you
are converting from; and value is the value of
the class after conversion.
• If the conversion operator specifies implicit ,
then the conversion is invoked automatically,
such as when an object is used in an
expression with the target type.
• When the conversion operator specifies
explicit, the conversion is invoked when a
cast is used.
• You cannot define both an implicit and
explicit conversion operator for the same
target and source types.
Implicit type conversion
using System.Collections;
public class TestClass
{
public void Test(Author a)
{
Console.WriteLine("Name {0} {1}", a.First, a.Last);
}
public void Test(Writer w)
{
Console.WriteLine("Name {0} {1}", w.FirstName,
w.LastName);
public class Author
{
public string First;
public string Last;
public string[] BooksArray;
public static implicit operator Writer(Author a)
{
Writer w = new Writer();
w.FirstName = a.First; w.LastName = a.Last;
w.Books = a.BooksArray != null ?
a.BooksArray.ToList():null;

return w;

} }
public class Writer
{
public string FirstName;
public string LastName ;
public IList Books ;
}
class Program
{
static void Main(string[] args)
{ Author a = new Author {
First = "Vijaya",
Last = "Anand",
BooksArray = new string[] { "book1" }
};
Writer w = a;
TestClass t = new TestClass();
t.Test(w);
t.Test(a);
} }
an explicit conversion operator, which is
invoked only when an explicit cast is used

class ThreeD {
int x, y, z;
public ThreeD() { x = y = z = 0; }
public ThreeD(int i, int j, int k) { x = i; y = j; z = k; }
public static ThreeD operator +(ThreeD op1, ThreeD op2)
{
ThreeD result = new ThreeD();
result.x = op1.x + op2.x;
result.y = op1.y + op2.y;
result.z = op1.z + op2.z;
return result;
This is now explicit
public static explicit operator int(ThreeD op1)
{
return op1.x * op1.y * op1.z;
}
public void Show()
{
Console.WriteLine(x + ", " + y + ", " + z);
}
}
• class ThreeDDemo {
• static void Main() {
•
ThreeD a = new ThreeD(1, 2, 3);
•
ThreeD b = new ThreeD(10, 10, 10);
•
ThreeD c = new ThreeD();
•
int i;
•
c = a + b;
•
Console.Write("Result of a + b: ");
•
c.Show();
•
Console.WriteLine();
i = (int) a; // explicitly convert to int -- cast required
Console.WriteLine("Result of i = a: " + i);
Console.WriteLine();
i = (int)b- (int)a; // casts required
Console.WriteLine("result of b-a: " + i);

More Related Content

PPTX
Templates in C++
PDF
Constructors and Destructors
PPT
Operators in C++
PPTX
classes and objects in C++
PPT
OOP in C++
PPTX
Operators and expressions in c language
PPTX
Pointers, virtual function and polymorphism
PPTX
Operator overloading
Templates in C++
Constructors and Destructors
Operators in C++
classes and objects in C++
OOP in C++
Operators and expressions in c language
Pointers, virtual function and polymorphism
Operator overloading

What's hot (20)

PPTX
Arrays in Java
PPTX
Operator overloading
PDF
Friend function in c++
PDF
What is Python Lambda Function? Python Tutorial | Edureka
PDF
Python functions
PPT
Inheritance in java
PPTX
Interface in java
PPTX
Operators in Python
PPT
16 virtual function
PPTX
Inheritance in java
PPTX
Access modifier and inheritance
PDF
Operator overloading
PPTX
Interface in java ,multiple inheritance in java, interface implementation
PPTX
Object oriented programming in java
PPTX
Exception Handling in Java
PPTX
Operator overloading
PPT
Function overloading(c++)
PDF
Operator overloading C++
PPT
presentation_jumping_statements_.ppt
PPTX
INHERITANCE IN JAVA.pptx
Arrays in Java
Operator overloading
Friend function in c++
What is Python Lambda Function? Python Tutorial | Edureka
Python functions
Inheritance in java
Interface in java
Operators in Python
16 virtual function
Inheritance in java
Access modifier and inheritance
Operator overloading
Interface in java ,multiple inheritance in java, interface implementation
Object oriented programming in java
Exception Handling in Java
Operator overloading
Function overloading(c++)
Operator overloading C++
presentation_jumping_statements_.ppt
INHERITANCE IN JAVA.pptx
Ad

Viewers also liked (8)

PPTX
Presentation on overloading
PPTX
Phpmyadmin administer mysql
PDF
phpMyAdmin
PDF
C# .net lecture 3 objects 3
PDF
PDF
Database design
PPT
Dr archana dhawan bajaj - c# dot net
PPT
JSP Standart Tag Lİbrary - JSTL
Presentation on overloading
Phpmyadmin administer mysql
phpMyAdmin
C# .net lecture 3 objects 3
Database design
Dr archana dhawan bajaj - c# dot net
JSP Standart Tag Lİbrary - JSTL
Ad

Similar to Operator overloading (20)

PPT
Lecture5
PPTX
New C# features
PPTX
Ch2 Elementry Programmin as per gtu oop.pptx
PDF
Functional Programming You Already Know - Kevlin Henney - Codemotion Rome 2015
PPTX
Chapter 6.6
PPTX
Operator overloading2
PPTX
Constructors and Destructors
PPTX
Chap2 class,objects contd
PPTX
05 Object Oriented Concept Presentation.pptx
PPT
Class & Object - User Defined Method
PPTX
Intro to object oriented programming
PPTX
Constructor in c++
PDF
22 scheme OOPs with C++ BCS306B_module2.pdfmodule2.pdf
PDF
Operator_Overloaing_Type_Conversion_OOPC(C++)
PPS
Class method
PPT
3 functions and class
DOCX
Bc0037
PPT
CppOperators.ppt
PPS
Let Us Learn Lambda Using C# 3.0
PPSX
C# 6.0 - April 2014 preview
Lecture5
New C# features
Ch2 Elementry Programmin as per gtu oop.pptx
Functional Programming You Already Know - Kevlin Henney - Codemotion Rome 2015
Chapter 6.6
Operator overloading2
Constructors and Destructors
Chap2 class,objects contd
05 Object Oriented Concept Presentation.pptx
Class & Object - User Defined Method
Intro to object oriented programming
Constructor in c++
22 scheme OOPs with C++ BCS306B_module2.pdfmodule2.pdf
Operator_Overloaing_Type_Conversion_OOPC(C++)
Class method
3 functions and class
Bc0037
CppOperators.ppt
Let Us Learn Lambda Using C# 3.0
C# 6.0 - April 2014 preview

More from abhay singh (15)

PPT
Iso 27001
PPT
Web service
PPT
Unsafe
PPTX
Threading
PPT
Preprocessor
PPT
Networking and socket
PPT
Namespace
PPT
Inheritance
PPT
Generic
PPT
PPT
Exception
PPT
Delegate
PPT
Constructor
PPT
Collection
PPT
Iso 27001
Web service
Unsafe
Threading
Preprocessor
Networking and socket
Namespace
Inheritance
Generic
Exception
Delegate
Constructor
Collection

Recently uploaded (20)

PDF
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PDF
Basic Mud Logging Guide for educational purpose
PDF
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PPTX
Lesson notes of climatology university.
PDF
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PDF
Computing-Curriculum for Schools in Ghana
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PPTX
Pharma ospi slides which help in ospi learning
PDF
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
PPTX
GDM (1) (1).pptx small presentation for students
PPTX
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PDF
Supply Chain Operations Speaking Notes -ICLT Program
PDF
102 student loan defaulters named and shamed – Is someone you know on the list?
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PPTX
Cell Types and Its function , kingdom of life
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
Basic Mud Logging Guide for educational purpose
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
human mycosis Human fungal infections are called human mycosis..pptx
Lesson notes of climatology university.
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
Pharmacology of Heart Failure /Pharmacotherapy of CHF
Computing-Curriculum for Schools in Ghana
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
Pharma ospi slides which help in ospi learning
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
GDM (1) (1).pptx small presentation for students
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
Microbial diseases, their pathogenesis and prophylaxis
Supply Chain Operations Speaking Notes -ICLT Program
102 student loan defaulters named and shamed – Is someone you know on the list?
2.FourierTransform-ShortQuestionswithAnswers.pdf
Cell Types and Its function , kingdom of life

Operator overloading

  • 1. Operator Overloading • C# allows you to define the meaning of an operator relative to a class that you create. This process is called operator overloading. • A principal advantage of operator overloading is that it allows you to seamlessly integrate a new class type into your programming environment. • Once operators are defined for a class, you can operate on objects of that class using the normal C# expression syntax. • You can even use an object in expressions involving other types of data.
  • 2. • Operator overloading is closely related to method overloading. To overload an operator, use the operator keyword to define an operator method, which defines the action of the operator relative to its class. There are two forms of operator methods: • one for unary operators and • one for binary operators.
  • 3. // General form for overloading a unary operator public static ret-type operator op (param-type operand) { // operations } // General form for overloading a binary operator public static ret-type operator op (param-type1 operand1, param-type1 operand2 ) { // operations }
  • 4. • the operator that you are overloading, such as + or /, is substituted for op . • The ret-type specifies the type of value returned by the specified operation. • the return value is often of the same type as the class for which the operator is being overloaded. • For unary operators, the operand is passed in operand. For binary operators, the operands are passed in operand1 and operand2. • Operator methods must be both public and static.
  • 5. • For unary operators, the operand must be of the same type as the class for which the operator is being defined. • For binary operators, at least one of the operands must be of the same type as its class. • Operator parameters must not use the ref or out modifier.
  • 6. class ThreeD { int x, y, z; public ThreeD() { x = y = z = 0; } public ThreeD(int i, int j, int k) { x = i; y = j; z = k; } public static ThreeD operator +(ThreeD op1, ThreeD op2) { ThreeD result = new ThreeD(); result.x = op1.x + op2.x; result.y = op1.y + op2.y; result.z = op1.z + op2.z; return result; }
  • 7. public static ThreeD operator -(ThreeD op1, ThreeD op2) { ThreeD result = new ThreeD(); result.x = op1.x - op2.x; result.y = op1.y - op2.y; result.z = op1.z - op2.z; return result; } public void Show() { Console.WriteLine(x + ", " + y + ", " + z); }
  • 8. class ThreeDDemo { static void Main() { ThreeD a = new ThreeD(1, 2, 3); ThreeD b = new ThreeD(10, 10, 10); ThreeD c; Console.Write("Here is a: "); a.Show(); Console.Write("Here is b: "); b.Show();
  • 9. c = a + b; Console.Write("Result of a + b: "); c.Show(); c = a + b + c; // add a, b, and c together Console.Write("Result of a + b + c: "); c.Show(); c = c - a; Console.Write("Result of c - a: "); c.Show(); c = c - b; Console.Write("Result of c - b: "); c.Show(); }
  • 10. output Here is a: 1, 2, 3 Here is b: 10, 10, 10 Result of a + b: 11, 12, 13 Result of a + b + c: 22, 24, 26 Result of c - a: 21, 22, 23 Result of c - b: 11, 12, 13
  • 11. Overload unary(- or ++) class ThreeD { int x, y, z; public ThreeD() { x = y = z = 0; } public ThreeD(int i, int j, int k) { x = i; y = j; z = k; } public static ThreeD operator -(ThreeD op) { ThreeD result = new ThreeD(); result.x = -op.x; result.y = -op.y; result.z = -op.z; return result; }
  • 12. public static ThreeD operator ++(ThreeD op) { ThreeD result = new ThreeD(); result.x = op.x + 1; result.y = op.y + 1; result.z = op.z + 1; return result; } public void Show() { Console.WriteLine(x + ", " + y + ", " + z); }}
  • 13. class ThreeDDemo { static void Main() { ThreeD a = new ThreeD(1, 2, 3); ThreeD b = new ThreeD(10, 10, 10); ThreeD c = new ThreeD(); c = -a; // assign -a to c Console.Write("Result of -a: "); c.Show(); c = a++; // post-increment a Console.WriteLine("Given c = a++"); Console.Write("c is "); c.Show(); Console.Write("a is "); a.Show();
  • 15. The operators that you can overload are:
  • 16. The operators that you can not overload are:
  • 17. Binary with int class ThreeD { int x, y, z; public ThreeD() { x = y = z = 0; } public ThreeD(int i, int j, int k) { x = i; y = j; z = k; } public static ThreeD operator +(ThreeD op1, int op2) { ThreeD result = new ThreeD(); result.x = op1.x + op2; result.y = op1.y + op2; result.z = op1.z + op2;
  • 18. • • • • • • • • • public void Show() { Console.WriteLine(x + ", " + y + ", " + z); }} class ThreeDDemo { static void Main() { ThreeD a = new ThreeD(1, 2, 3); ThreeD b = new ThreeD(10, 10, 10); ThreeD c = new ThreeD();
  • 19. a.Show(); b.Show(); c = b + 10; // ThreeD + int Console.Write("Result of b + 10: "); c.Show();
  • 21. Conversion Operators • C# allows you to create a special type of operator method called a conversion operator. • A conversion operator converts an object of your class into another type. • Conversion operators help fully integrate class types into the C# programming environment by allowing objects of a class to be freely mixed with other data types as long as a conversion to those other types is defined.
  • 22. two forms of conversion operators, implicit and explicit • public static operator implicit target-type (source-type v) { return value; } • public static operator explicit target-type (source-type v) { return value; } • target-type is the target type that you are converting to; source-type is the type you are converting from; and value is the value of the class after conversion.
  • 23. • If the conversion operator specifies implicit , then the conversion is invoked automatically, such as when an object is used in an expression with the target type. • When the conversion operator specifies explicit, the conversion is invoked when a cast is used. • You cannot define both an implicit and explicit conversion operator for the same target and source types.
  • 24. Implicit type conversion using System.Collections; public class TestClass { public void Test(Author a) { Console.WriteLine("Name {0} {1}", a.First, a.Last); } public void Test(Writer w) { Console.WriteLine("Name {0} {1}", w.FirstName, w.LastName);
  • 25. public class Author { public string First; public string Last; public string[] BooksArray; public static implicit operator Writer(Author a) { Writer w = new Writer(); w.FirstName = a.First; w.LastName = a.Last; w.Books = a.BooksArray != null ? a.BooksArray.ToList():null; return w; } }
  • 26. public class Writer { public string FirstName; public string LastName ; public IList Books ; } class Program {
  • 27. static void Main(string[] args) { Author a = new Author { First = "Vijaya", Last = "Anand", BooksArray = new string[] { "book1" } }; Writer w = a; TestClass t = new TestClass(); t.Test(w); t.Test(a); } }
  • 28. an explicit conversion operator, which is invoked only when an explicit cast is used class ThreeD { int x, y, z; public ThreeD() { x = y = z = 0; } public ThreeD(int i, int j, int k) { x = i; y = j; z = k; } public static ThreeD operator +(ThreeD op1, ThreeD op2) { ThreeD result = new ThreeD(); result.x = op1.x + op2.x; result.y = op1.y + op2.y; result.z = op1.z + op2.z; return result;
  • 29. This is now explicit public static explicit operator int(ThreeD op1) { return op1.x * op1.y * op1.z; } public void Show() { Console.WriteLine(x + ", " + y + ", " + z); } }
  • 30. • class ThreeDDemo { • static void Main() { • ThreeD a = new ThreeD(1, 2, 3); • ThreeD b = new ThreeD(10, 10, 10); • ThreeD c = new ThreeD(); • int i; • c = a + b; • Console.Write("Result of a + b: "); • c.Show(); • Console.WriteLine();
  • 31. i = (int) a; // explicitly convert to int -- cast required Console.WriteLine("Result of i = a: " + i); Console.WriteLine(); i = (int)b- (int)a; // casts required Console.WriteLine("result of b-a: " + i);