SlideShare a Scribd company logo
1 of 31
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

What's hot (20)

Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
Constructors and Destructors
Constructors and DestructorsConstructors and Destructors
Constructors and Destructors
 
Friend function
Friend functionFriend function
Friend function
 
Unary operator overloading
Unary operator overloadingUnary operator overloading
Unary operator overloading
 
Classes and objects
Classes and objectsClasses and objects
Classes and objects
 
Polymorphism in C++
Polymorphism in C++Polymorphism in C++
Polymorphism in C++
 
Virtual function in C++ Pure Virtual Function
Virtual function in C++ Pure Virtual Function Virtual function in C++ Pure Virtual Function
Virtual function in C++ Pure Virtual Function
 
Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++
 
Friend functions
Friend functions Friend functions
Friend functions
 
Function overloading
Function overloadingFunction overloading
Function overloading
 
Function overloading ppt
Function overloading pptFunction overloading ppt
Function overloading ppt
 
Abstract class in c++
Abstract class in c++Abstract class in c++
Abstract class in c++
 
Constructors and destructors
Constructors and destructorsConstructors and destructors
Constructors and destructors
 
Constructors and Destructor in C++
Constructors and Destructor in C++Constructors and Destructor in C++
Constructors and Destructor in C++
 
Chapter 07 inheritance
Chapter 07 inheritanceChapter 07 inheritance
Chapter 07 inheritance
 
Inline function
Inline functionInline function
Inline function
 
Static Data Members and Member Functions
Static Data Members and Member FunctionsStatic Data Members and Member Functions
Static Data Members and Member Functions
 
Classes and objects
Classes and objectsClasses and objects
Classes and objects
 
06. operator overloading
06. operator overloading06. operator overloading
06. operator overloading
 

Viewers also liked

Presentation on overloading
Presentation on overloading Presentation on overloading
Presentation on overloading Charndeep Sekhon
 
Phpmyadmin administer mysql
Phpmyadmin administer mysqlPhpmyadmin administer mysql
Phpmyadmin administer mysqlMohd yasin Karim
 
phpMyAdmin
phpMyAdminphpMyAdmin
phpMyAdminWarawut
 
C# .net lecture 3 objects 3
C# .net lecture 3 objects 3C# .net lecture 3 objects 3
C# .net lecture 3 objects 3Doron Raifman
 
Database design
Database designDatabase design
Database designWarawut
 
JSP Standart Tag Lİbrary - JSTL
JSP Standart Tag Lİbrary - JSTLJSP Standart Tag Lİbrary - JSTL
JSP Standart Tag Lİbrary - JSTLseleciii44
 

Viewers also liked (8)

Presentation on overloading
Presentation on overloading Presentation on overloading
Presentation on overloading
 
Phpmyadmin administer mysql
Phpmyadmin administer mysqlPhpmyadmin administer mysql
Phpmyadmin administer mysql
 
phpMyAdmin
phpMyAdminphpMyAdmin
phpMyAdmin
 
C# .net lecture 3 objects 3
C# .net lecture 3 objects 3C# .net lecture 3 objects 3
C# .net lecture 3 objects 3
 
P2P Networks
P2P NetworksP2P Networks
P2P Networks
 
Database design
Database designDatabase design
Database design
 
Dr archana dhawan bajaj - c# dot net
Dr archana dhawan bajaj - c# dot netDr archana dhawan bajaj - c# dot net
Dr archana dhawan bajaj - c# dot net
 
JSP Standart Tag Lİbrary - JSTL
JSP Standart Tag Lİbrary - JSTLJSP Standart Tag Lİbrary - JSTL
JSP Standart Tag Lİbrary - JSTL
 

Similar to Operator overloading

Functional Programming You Already Know - Kevlin Henney - Codemotion Rome 2015
Functional Programming You Already Know - Kevlin Henney - Codemotion Rome 2015Functional Programming You Already Know - Kevlin Henney - Codemotion Rome 2015
Functional Programming You Already Know - Kevlin Henney - Codemotion Rome 2015Codemotion
 
Chapter 6.6
Chapter 6.6Chapter 6.6
Chapter 6.6sotlsoc
 
Operator overloading2
Operator overloading2Operator overloading2
Operator overloading2zindadili
 
Constructors and Destructors
Constructors and DestructorsConstructors and Destructors
Constructors and DestructorsKeyur Vadodariya
 
Chap2 class,objects contd
Chap2 class,objects contdChap2 class,objects contd
Chap2 class,objects contdraksharao
 
Class & Object - User Defined Method
Class & Object - User Defined MethodClass & Object - User Defined Method
Class & Object - User Defined MethodPRN USM
 
Intro to object oriented programming
Intro to object oriented programmingIntro to object oriented programming
Intro to object oriented programmingDavid Giard
 
Constructor in c++
Constructor in c++Constructor in c++
Constructor in c++Jay Patel
 
Operator_Overloaing_Type_Conversion_OOPC(C++)
Operator_Overloaing_Type_Conversion_OOPC(C++)Operator_Overloaing_Type_Conversion_OOPC(C++)
Operator_Overloaing_Type_Conversion_OOPC(C++)Yaksh Jethva
 
3 functions and class
3   functions and class3   functions and class
3 functions and classtrixiacruz
 
Let Us Learn Lambda Using C# 3.0
Let Us Learn Lambda Using C# 3.0Let Us Learn Lambda Using C# 3.0
Let Us Learn Lambda Using C# 3.0Sheik Uduman Ali
 
C# 6.0 - April 2014 preview
C# 6.0 - April 2014 previewC# 6.0 - April 2014 preview
C# 6.0 - April 2014 previewPaulo Morgado
 
Lec 9 05_sept [compatibility mode]
Lec 9 05_sept [compatibility mode]Lec 9 05_sept [compatibility mode]
Lec 9 05_sept [compatibility mode]Palak Sanghani
 

Similar to Operator overloading (20)

Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
Lecture5
Lecture5Lecture5
Lecture5
 
New C# features
New C# featuresNew C# features
New C# features
 
Functional Programming You Already Know - Kevlin Henney - Codemotion Rome 2015
Functional Programming You Already Know - Kevlin Henney - Codemotion Rome 2015Functional Programming You Already Know - Kevlin Henney - Codemotion Rome 2015
Functional Programming You Already Know - Kevlin Henney - Codemotion Rome 2015
 
Chapter 6.6
Chapter 6.6Chapter 6.6
Chapter 6.6
 
Operator overloading2
Operator overloading2Operator overloading2
Operator overloading2
 
Constructors and Destructors
Constructors and DestructorsConstructors and Destructors
Constructors and Destructors
 
Chap2 class,objects contd
Chap2 class,objects contdChap2 class,objects contd
Chap2 class,objects contd
 
Class & Object - User Defined Method
Class & Object - User Defined MethodClass & Object - User Defined Method
Class & Object - User Defined Method
 
Intro to object oriented programming
Intro to object oriented programmingIntro to object oriented programming
Intro to object oriented programming
 
Constructor in c++
Constructor in c++Constructor in c++
Constructor in c++
 
Operator_Overloaing_Type_Conversion_OOPC(C++)
Operator_Overloaing_Type_Conversion_OOPC(C++)Operator_Overloaing_Type_Conversion_OOPC(C++)
Operator_Overloaing_Type_Conversion_OOPC(C++)
 
Class method
Class methodClass method
Class method
 
3 functions and class
3   functions and class3   functions and class
3 functions and class
 
Bc0037
Bc0037Bc0037
Bc0037
 
CppOperators.ppt
CppOperators.pptCppOperators.ppt
CppOperators.ppt
 
Let Us Learn Lambda Using C# 3.0
Let Us Learn Lambda Using C# 3.0Let Us Learn Lambda Using C# 3.0
Let Us Learn Lambda Using C# 3.0
 
C# 6.0 - April 2014 preview
C# 6.0 - April 2014 previewC# 6.0 - April 2014 preview
C# 6.0 - April 2014 preview
 
02.adt
02.adt02.adt
02.adt
 
Lec 9 05_sept [compatibility mode]
Lec 9 05_sept [compatibility mode]Lec 9 05_sept [compatibility mode]
Lec 9 05_sept [compatibility mode]
 

More from abhay singh (15)

Iso 27001
Iso 27001Iso 27001
Iso 27001
 
Web service
Web serviceWeb service
Web service
 
Unsafe
UnsafeUnsafe
Unsafe
 
Threading
ThreadingThreading
Threading
 
Preprocessor
PreprocessorPreprocessor
Preprocessor
 
Networking and socket
Networking and socketNetworking and socket
Networking and socket
 
Namespace
NamespaceNamespace
Namespace
 
Inheritance
InheritanceInheritance
Inheritance
 
Generic
GenericGeneric
Generic
 
Gdi
GdiGdi
Gdi
 
Exception
ExceptionException
Exception
 
Delegate
DelegateDelegate
Delegate
 
Constructor
ConstructorConstructor
Constructor
 
Collection
CollectionCollection
Collection
 
Ado
AdoAdo
Ado
 

Recently uploaded

Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfSumit Tiwari
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...M56BOOKSTORE PRODUCT/SERVICE
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application ) Sakshi Ghasle
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 

Recently uploaded (20)

Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application )
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 

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