SlideShare uma empresa Scribd logo
1 de 42
Abed El-Azeem Bukhari (MCPD,MCTS and MCP) el-bukhari.com
Operators and Casts Prepared By : Abed ElAzeem Bukhari What ‘s in this chapter? ➤  Operators in C# ➤  The idea of equality when dealing with reference and value types ➤  Data conversion between primitive data types ➤  Converting value types to reference types using boxing ➤  Converting between reference types by casting ➤  Overloading the standard operators for custom types ➤  Adding cast operators to custom types
Operators
Operators cont
Operators cont
operator shortcuts
operator shortcuts cont int x = 5; if (++x == 6) // true – x is incremented to 6 before the evaluation { Console.WriteLine("This will execute"); } if (x++ == 7) // false – x is incremented to 7 after the evaluation { Console.WriteLine("This won't"); }
Conditional operator condition ? true_value: false_value int x = 1; string s = x + " "; s += (x == 1 ? "man": "men"); Console.WriteLine(s);
The checked and unchecked operators byte b = 255; b++; Console.WriteLine(b.ToString()); ------------------------------------------------------- byte b = 255; checked { b++; } Console.WriteLine(b.ToString());
The checked and unchecked operators cont byte b = 255; unchecked { b++; } Console.WriteLine(b.ToString());
The is operator int i = 10; if (i  is  object) { Console.WriteLine("i is an object"); } int , like all C# data types, inherits from object ; therefore, the expression i is object will evaluate to true in this case, and the appropriate message will be displayed .
The as operator object o1 = "Some String"; object o2 = 5; string s1 = o1 as string; // s1 = "Some String" string s2 = o2 as string; // s2 = null
The sizeof operator Console.WriteLine(sizeof(int)); // This will display the number 4 , because an int is 4 bytes long. If you are using the  sizeof  operator with  complex types  (and not primitive types), you will need to block the code within an unsafe block as illustrated here: unsafe { Console.WriteLine(sizeof(Customer)); }
The typeof operator The typeof operator returns a System.Type object representing a specified type. For example, typeof(string)  will return a Type object representing the System.String type.  This is useful when you want to use reflection to find information about an object dynamically.
nullable Types and operators int?  a = null; int?  b = a + 4; // b = null int?  c = a * 5; // c = null int?  a = null; int?  b = -5; if (a > = b) Console.WriteLine(&quot;a > = b&quot;); else Console.WriteLine(&quot;a < b&quot;); // However, when comparing nullable types, if only one of the operands is null , the comparison will always equate to false
The null Coalescing operator ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
operator Precedence
Type Conversions byte value1 = 10; byte value2 = 23; byte total; total = value1 + value2; Console.WriteLine(total); When you attempt to compile these lines, you get the following error message: Cannot implicitly convert type ‘ int ’ to ‘ byte‘ The problem here is that when you add 2 bytes together, the result will be returned as an int , not as another byte
implicit Conversions byte value1 = 10; byte value2 = 23; long total; // this will compile fine total = value1 + value2; Console.WriteLine(total);
implicit Conversions cont
implicit Conversions cont ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
explicit Conversions These are some of the conversions that cannot be made implicitly: ➤  int to short — Data loss is possible. ➤  int to uint — Data loss is possible. ➤  uint to int — Data loss is possible. ➤  float to int — You will lose everything after the decimal point. ➤  Any numeric type to char — Data loss is possible. ➤  decimal to any numeric type — The decimal type is internally structured differently from both integers and floating-point numbers. ➤  int? to int — The nullable type may have the value null.
explicit Conversions These are some of the conversions that cannot be made implicitly: ➤  int to short — Data loss is possible. ➤  int to uint — Data loss is possible. ➤  uint to int — Data loss is possible. ➤  float to int — You will lose everything after the decimal point. ➤  Any numeric type to char — Data loss is possible. ➤  decimal to any numeric type — The decimal type is internally structured differently from both integers and floating-point numbers. ➤  int? to int — The nullable type may have the value null.
explicit Conversions cont long val = 30000; int i = (int)val; // A  valid  cast. The maximum int is  2147483647 long val = 3000000000; int i = (int)val; // An  invalid  cast. The maximum int is  2147483647 // I will be  -1294967296 long val = 3000000000; int i = checked((int)val); // to check before casting Using casts, you can convert most primitive data types from one type to another;  for example, in this code, the value 0.5 is added to price, and the total is cast to an int: double price = 25.30; int approximatePrice = (int)(price + 0.5); This gives the price rounded to the nearest dollar.
explicit Conversions cont ushort c = 43; char symbol = (char)c; Console.WriteLine(symbol); // The output is the character that has an ASCII number of 43, the + sign. --- int? a = null; int b = (int)a; // Will throw exception --- int i = 10; string s = i.ToString(); --- if you need to parse a string to retrieve a numeric or Boolean value, you can use the Parse() method supported by all the predefined value types: string s = “100”; int i =  int.Parse(s) ; Console.WriteLine(i + 50); // Add 50 to prove it is really an int
boxing and unboxing int myIntNumber = 20; object myObject = myIntNumber; // Box the int int mySecondNumber = (int)myObject; // Unbox it back into an int
Comparing objects for equality ,[object Object],[object Object],[object Object],[object Object]
The  ReferenceEquals () Method SomeClass x, y; x = new SomeClass(); y = new SomeClass(); bool B1 = ReferenceEquals(null, null); //  returns true bool B2 = ReferenceEquals(null,x); //  returns false bool B3 = ReferenceEquals(x, y);  // returns false because x and y // point to different objects
The virtual Equals() Method This method used usually by override it in your classes in order to Compare the instances of your class.
The static Equals() Method The static version of Equals() actually does the same thing as the virtual instance version. The difference is that the static version takes two parameters and compares them for equality.
Comparison operator (==) bool b = (x == y); //  x, y object references
operator overloading VectorStruct solution public static Vector  operator   +  (Vector lhs, Vector rhs) { Vector result = new Vector(lhs); result.x += rhs.x; result.y += rhs.y; result.z += rhs.z; return result; }
operator overloading cont vect1 = new Vector(3.0, 3.0, 1.0); vect2 = new Vector(2.0, - 4.0, - 4.0); vect3 = vect1 + vect2; //results vect1 = ( 3, 3, 1 ) vect2 = ( 2, - 4, - 4 ) vect3 = ( 5, - 1, - 3 )
overloading the Comparison operators ➤  == and != ➤  > and < ➤  > = and < = The C# language requires that you overload these operators in pairs.  That is, if you overload == , you must overload != too; otherwise, you get a compiler error. In addition, the comparison operators  must return a bool . If you overload == and !=, you must also override the Equals() and GetHashCode() methods inherited from System.Object; otherwise, you’ll get a compiler warning. The reasoning is that the  Equals() method should implement the same kind of equality logic as the == operator.
overloading the Comparison operators cont public static bool operator == (Vector lhs, Vector rhs) { if (lhs.x == rhs.x & & lhs.y == rhs.y & & lhs.z == rhs.z) return true; else return false; } public static bool operator != (Vector lhs, Vector rhs) { return ! (lhs == rhs); }
Which operators Can you overload?
user-defined Casts ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
implementing user-defined Casts struct Currency { public uint Dollars; public ushort Cents; public Currency(uint dollars, ushort cents) { this.Dollars = dollars; this.Cents = cents; } public override string ToString() { return string.Format( “ ${0}.{1, - 2:00} ” , Dollars,Cents); } }
implementing user-defined Casts cont Currency balance = new Currency(10,50); float f = balance;  // We want f to be set to 10.5 To be able to do this, you need to define a cast.  Hence, you add the following to your Currency definition: public static  implicit   operator   float (Currency value) { return value.Dollars + (value.Cents/100.0f); }
Casts Between Classes public static explicit operator D(C value) { // and so on } public static explicit operator C(D value) { // and so on }
Casts Between Base and Derived Classes MyBase derivedObject = new MyDerived(); MyBase baseObject = new MyBase(); MyDerived derivedCopy1 = (MyDerived) derivedObject; // OK MyDerived derivedCopy2 = (MyDerived) baseObject; // Throws exception class DerivedClass: BaseClass { public DerivedClass( BaseClass  rhs) { // initialize object from the Base instance } // etc.
Thanks For Attending Abed El-Azeem Bukhari (MCPD,MCTS and MCP) el-bukhari.com

Mais conteúdo relacionado

Mais procurados (19)

Cpu-fundamental of C
Cpu-fundamental of CCpu-fundamental of C
Cpu-fundamental of C
 
Unit 8. Pointers
Unit 8. PointersUnit 8. Pointers
Unit 8. Pointers
 
C Programming Unit-3
C Programming Unit-3C Programming Unit-3
C Programming Unit-3
 
Generic Programming seminar
Generic Programming seminarGeneric Programming seminar
Generic Programming seminar
 
Assignment c programming
Assignment c programmingAssignment c programming
Assignment c programming
 
Unit4 Slides
Unit4 SlidesUnit4 Slides
Unit4 Slides
 
C language basics
C language basicsC language basics
C language basics
 
Strings
StringsStrings
Strings
 
Cpp17 and Beyond
Cpp17 and BeyondCpp17 and Beyond
Cpp17 and Beyond
 
Chap 4 c++
Chap 4 c++Chap 4 c++
Chap 4 c++
 
C Programming Assignment
C Programming AssignmentC Programming Assignment
C Programming Assignment
 
FUNDAMENTAL OF C
FUNDAMENTAL OF CFUNDAMENTAL OF C
FUNDAMENTAL OF C
 
Chap 4 c++
Chap 4 c++Chap 4 c++
Chap 4 c++
 
What is c
What is cWhat is c
What is c
 
COM1407: Type Casting, Command Line Arguments and Defining Constants
COM1407: Type Casting, Command Line Arguments and Defining Constants COM1407: Type Casting, Command Line Arguments and Defining Constants
COM1407: Type Casting, Command Line Arguments and Defining Constants
 
Programming in C (part 2)
Programming in C (part 2)Programming in C (part 2)
Programming in C (part 2)
 
C programming part4
C programming part4C programming part4
C programming part4
 
Getting Started with C++
Getting Started with C++Getting Started with C++
Getting Started with C++
 
Web application architecture
Web application architectureWeb application architecture
Web application architecture
 

Semelhante a Csharp4 operators and_casts

CSharp Language Overview Part 1
CSharp Language Overview Part 1CSharp Language Overview Part 1
CSharp Language Overview Part 1Hossein Zahed
 
03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...Intro C# Book
 
Lesson 17. Pattern 9. Mixed arithmetic
Lesson 17. Pattern 9. Mixed arithmeticLesson 17. Pattern 9. Mixed arithmetic
Lesson 17. Pattern 9. Mixed arithmeticPVS-Studio
 
1. DSA - Introduction.pptx
1. DSA - Introduction.pptx1. DSA - Introduction.pptx
1. DSA - Introduction.pptxhara69
 
the refernce of programming C notes ppt.pptx
the refernce of programming C notes ppt.pptxthe refernce of programming C notes ppt.pptx
the refernce of programming C notes ppt.pptxAnkitaVerma776806
 
DITEC - Programming with C#.NET
DITEC - Programming with C#.NETDITEC - Programming with C#.NET
DITEC - Programming with C#.NETRasan Samarasinghe
 
DISE - Windows Based Application Development in C#
DISE - Windows Based Application Development in C#DISE - Windows Based Application Development in C#
DISE - Windows Based Application Development in C#Rasan Samarasinghe
 
POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAAiman Hud
 
Python Unit 3 - Control Flow and Functions
Python Unit 3 - Control Flow and FunctionsPython Unit 3 - Control Flow and Functions
Python Unit 3 - Control Flow and FunctionsDhivyaSubramaniyam
 

Semelhante a Csharp4 operators and_casts (20)

Csharp4 basics
Csharp4 basicsCsharp4 basics
Csharp4 basics
 
C tutorial
C tutorialC tutorial
C tutorial
 
CSharp Language Overview Part 1
CSharp Language Overview Part 1CSharp Language Overview Part 1
CSharp Language Overview Part 1
 
05 operators
05   operators05   operators
05 operators
 
C++ Language
C++ LanguageC++ Language
C++ Language
 
03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...
 
Lesson 17. Pattern 9. Mixed arithmetic
Lesson 17. Pattern 9. Mixed arithmeticLesson 17. Pattern 9. Mixed arithmetic
Lesson 17. Pattern 9. Mixed arithmetic
 
Pointers operation day2
Pointers operation day2Pointers operation day2
Pointers operation day2
 
1. DSA - Introduction.pptx
1. DSA - Introduction.pptx1. DSA - Introduction.pptx
1. DSA - Introduction.pptx
 
the refernce of programming C notes ppt.pptx
the refernce of programming C notes ppt.pptxthe refernce of programming C notes ppt.pptx
the refernce of programming C notes ppt.pptx
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
C# overview part 1
C# overview part 1C# overview part 1
C# overview part 1
 
Ch03
Ch03Ch03
Ch03
 
DITEC - Programming with C#.NET
DITEC - Programming with C#.NETDITEC - Programming with C#.NET
DITEC - Programming with C#.NET
 
c_tutorial_2.ppt
c_tutorial_2.pptc_tutorial_2.ppt
c_tutorial_2.ppt
 
unit 1 (1).pptx
unit 1 (1).pptxunit 1 (1).pptx
unit 1 (1).pptx
 
DISE - Windows Based Application Development in C#
DISE - Windows Based Application Development in C#DISE - Windows Based Application Development in C#
DISE - Windows Based Application Development in C#
 
POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIA
 
Python Unit 3 - Control Flow and Functions
Python Unit 3 - Control Flow and FunctionsPython Unit 3 - Control Flow and Functions
Python Unit 3 - Control Flow and Functions
 
Code optimization
Code optimization Code optimization
Code optimization
 

Mais de Abed Bukhari

Csharp4 arrays and_tuples
Csharp4 arrays and_tuplesCsharp4 arrays and_tuples
Csharp4 arrays and_tuplesAbed Bukhari
 
Csharp4 delegates lambda_and_events
Csharp4 delegates lambda_and_eventsCsharp4 delegates lambda_and_events
Csharp4 delegates lambda_and_eventsAbed Bukhari
 
Csharp4 strings and_regular_expressions
Csharp4 strings and_regular_expressionsCsharp4 strings and_regular_expressions
Csharp4 strings and_regular_expressionsAbed Bukhari
 
Csharp4 objects and_types
Csharp4 objects and_typesCsharp4 objects and_types
Csharp4 objects and_typesAbed Bukhari
 
Csharp4 inheritance
Csharp4 inheritanceCsharp4 inheritance
Csharp4 inheritanceAbed Bukhari
 
Whats new in_csharp4
Whats new in_csharp4Whats new in_csharp4
Whats new in_csharp4Abed Bukhari
 

Mais de Abed Bukhari (7)

Csharp4 arrays and_tuples
Csharp4 arrays and_tuplesCsharp4 arrays and_tuples
Csharp4 arrays and_tuples
 
Csharp4 delegates lambda_and_events
Csharp4 delegates lambda_and_eventsCsharp4 delegates lambda_and_events
Csharp4 delegates lambda_and_events
 
Csharp4 generics
Csharp4 genericsCsharp4 generics
Csharp4 generics
 
Csharp4 strings and_regular_expressions
Csharp4 strings and_regular_expressionsCsharp4 strings and_regular_expressions
Csharp4 strings and_regular_expressions
 
Csharp4 objects and_types
Csharp4 objects and_typesCsharp4 objects and_types
Csharp4 objects and_types
 
Csharp4 inheritance
Csharp4 inheritanceCsharp4 inheritance
Csharp4 inheritance
 
Whats new in_csharp4
Whats new in_csharp4Whats new in_csharp4
Whats new in_csharp4
 

Último

What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 

Último (20)

What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 

Csharp4 operators and_casts

  • 1. Abed El-Azeem Bukhari (MCPD,MCTS and MCP) el-bukhari.com
  • 2. Operators and Casts Prepared By : Abed ElAzeem Bukhari What ‘s in this chapter? ➤ Operators in C# ➤ The idea of equality when dealing with reference and value types ➤ Data conversion between primitive data types ➤ Converting value types to reference types using boxing ➤ Converting between reference types by casting ➤ Overloading the standard operators for custom types ➤ Adding cast operators to custom types
  • 7. operator shortcuts cont int x = 5; if (++x == 6) // true – x is incremented to 6 before the evaluation { Console.WriteLine(&quot;This will execute&quot;); } if (x++ == 7) // false – x is incremented to 7 after the evaluation { Console.WriteLine(&quot;This won't&quot;); }
  • 8. Conditional operator condition ? true_value: false_value int x = 1; string s = x + &quot; &quot;; s += (x == 1 ? &quot;man&quot;: &quot;men&quot;); Console.WriteLine(s);
  • 9. The checked and unchecked operators byte b = 255; b++; Console.WriteLine(b.ToString()); ------------------------------------------------------- byte b = 255; checked { b++; } Console.WriteLine(b.ToString());
  • 10. The checked and unchecked operators cont byte b = 255; unchecked { b++; } Console.WriteLine(b.ToString());
  • 11. The is operator int i = 10; if (i is object) { Console.WriteLine(&quot;i is an object&quot;); } int , like all C# data types, inherits from object ; therefore, the expression i is object will evaluate to true in this case, and the appropriate message will be displayed .
  • 12. The as operator object o1 = &quot;Some String&quot;; object o2 = 5; string s1 = o1 as string; // s1 = &quot;Some String&quot; string s2 = o2 as string; // s2 = null
  • 13. The sizeof operator Console.WriteLine(sizeof(int)); // This will display the number 4 , because an int is 4 bytes long. If you are using the sizeof operator with complex types (and not primitive types), you will need to block the code within an unsafe block as illustrated here: unsafe { Console.WriteLine(sizeof(Customer)); }
  • 14. The typeof operator The typeof operator returns a System.Type object representing a specified type. For example, typeof(string) will return a Type object representing the System.String type. This is useful when you want to use reflection to find information about an object dynamically.
  • 15. nullable Types and operators int? a = null; int? b = a + 4; // b = null int? c = a * 5; // c = null int? a = null; int? b = -5; if (a > = b) Console.WriteLine(&quot;a > = b&quot;); else Console.WriteLine(&quot;a < b&quot;); // However, when comparing nullable types, if only one of the operands is null , the comparison will always equate to false
  • 16.
  • 18. Type Conversions byte value1 = 10; byte value2 = 23; byte total; total = value1 + value2; Console.WriteLine(total); When you attempt to compile these lines, you get the following error message: Cannot implicitly convert type ‘ int ’ to ‘ byte‘ The problem here is that when you add 2 bytes together, the result will be returned as an int , not as another byte
  • 19. implicit Conversions byte value1 = 10; byte value2 = 23; long total; // this will compile fine total = value1 + value2; Console.WriteLine(total);
  • 21.
  • 22. explicit Conversions These are some of the conversions that cannot be made implicitly: ➤ int to short — Data loss is possible. ➤ int to uint — Data loss is possible. ➤ uint to int — Data loss is possible. ➤ float to int — You will lose everything after the decimal point. ➤ Any numeric type to char — Data loss is possible. ➤ decimal to any numeric type — The decimal type is internally structured differently from both integers and floating-point numbers. ➤ int? to int — The nullable type may have the value null.
  • 23. explicit Conversions These are some of the conversions that cannot be made implicitly: ➤ int to short — Data loss is possible. ➤ int to uint — Data loss is possible. ➤ uint to int — Data loss is possible. ➤ float to int — You will lose everything after the decimal point. ➤ Any numeric type to char — Data loss is possible. ➤ decimal to any numeric type — The decimal type is internally structured differently from both integers and floating-point numbers. ➤ int? to int — The nullable type may have the value null.
  • 24. explicit Conversions cont long val = 30000; int i = (int)val; // A valid cast. The maximum int is 2147483647 long val = 3000000000; int i = (int)val; // An invalid cast. The maximum int is 2147483647 // I will be -1294967296 long val = 3000000000; int i = checked((int)val); // to check before casting Using casts, you can convert most primitive data types from one type to another; for example, in this code, the value 0.5 is added to price, and the total is cast to an int: double price = 25.30; int approximatePrice = (int)(price + 0.5); This gives the price rounded to the nearest dollar.
  • 25. explicit Conversions cont ushort c = 43; char symbol = (char)c; Console.WriteLine(symbol); // The output is the character that has an ASCII number of 43, the + sign. --- int? a = null; int b = (int)a; // Will throw exception --- int i = 10; string s = i.ToString(); --- if you need to parse a string to retrieve a numeric or Boolean value, you can use the Parse() method supported by all the predefined value types: string s = “100”; int i = int.Parse(s) ; Console.WriteLine(i + 50); // Add 50 to prove it is really an int
  • 26. boxing and unboxing int myIntNumber = 20; object myObject = myIntNumber; // Box the int int mySecondNumber = (int)myObject; // Unbox it back into an int
  • 27.
  • 28. The ReferenceEquals () Method SomeClass x, y; x = new SomeClass(); y = new SomeClass(); bool B1 = ReferenceEquals(null, null); // returns true bool B2 = ReferenceEquals(null,x); // returns false bool B3 = ReferenceEquals(x, y); // returns false because x and y // point to different objects
  • 29. The virtual Equals() Method This method used usually by override it in your classes in order to Compare the instances of your class.
  • 30. The static Equals() Method The static version of Equals() actually does the same thing as the virtual instance version. The difference is that the static version takes two parameters and compares them for equality.
  • 31. Comparison operator (==) bool b = (x == y); // x, y object references
  • 32. operator overloading VectorStruct solution public static Vector operator + (Vector lhs, Vector rhs) { Vector result = new Vector(lhs); result.x += rhs.x; result.y += rhs.y; result.z += rhs.z; return result; }
  • 33. operator overloading cont vect1 = new Vector(3.0, 3.0, 1.0); vect2 = new Vector(2.0, - 4.0, - 4.0); vect3 = vect1 + vect2; //results vect1 = ( 3, 3, 1 ) vect2 = ( 2, - 4, - 4 ) vect3 = ( 5, - 1, - 3 )
  • 34. overloading the Comparison operators ➤ == and != ➤ > and < ➤ > = and < = The C# language requires that you overload these operators in pairs. That is, if you overload == , you must overload != too; otherwise, you get a compiler error. In addition, the comparison operators must return a bool . If you overload == and !=, you must also override the Equals() and GetHashCode() methods inherited from System.Object; otherwise, you’ll get a compiler warning. The reasoning is that the Equals() method should implement the same kind of equality logic as the == operator.
  • 35. overloading the Comparison operators cont public static bool operator == (Vector lhs, Vector rhs) { if (lhs.x == rhs.x & & lhs.y == rhs.y & & lhs.z == rhs.z) return true; else return false; } public static bool operator != (Vector lhs, Vector rhs) { return ! (lhs == rhs); }
  • 36. Which operators Can you overload?
  • 37.
  • 38. implementing user-defined Casts struct Currency { public uint Dollars; public ushort Cents; public Currency(uint dollars, ushort cents) { this.Dollars = dollars; this.Cents = cents; } public override string ToString() { return string.Format( “ ${0}.{1, - 2:00} ” , Dollars,Cents); } }
  • 39. implementing user-defined Casts cont Currency balance = new Currency(10,50); float f = balance; // We want f to be set to 10.5 To be able to do this, you need to define a cast. Hence, you add the following to your Currency definition: public static implicit operator float (Currency value) { return value.Dollars + (value.Cents/100.0f); }
  • 40. Casts Between Classes public static explicit operator D(C value) { // and so on } public static explicit operator C(D value) { // and so on }
  • 41. Casts Between Base and Derived Classes MyBase derivedObject = new MyDerived(); MyBase baseObject = new MyBase(); MyDerived derivedCopy1 = (MyDerived) derivedObject; // OK MyDerived derivedCopy2 = (MyDerived) baseObject; // Throws exception class DerivedClass: BaseClass { public DerivedClass( BaseClass rhs) { // initialize object from the Base instance } // etc.
  • 42. Thanks For Attending Abed El-Azeem Bukhari (MCPD,MCTS and MCP) el-bukhari.com