C#
  Home arrow C# arrow Overloading Operators in C#
ASP Free Forums 
.NET  
ASP  
ASP Code  
ASP.NET  
ASP.NET Code  
BrainDump  
C#  
Code Examples  
Database  
Database Code  
IIS  
Microsoft Access  
MS SQL Server  
Visual Basic.NET  
Windows Scripting  
Windows Security  
XML  
ASP Web Hosting  
ASP.NET Web Hosting 
Mobile Linux 
App Generation ROI 
Windows Web Hosting
 
IBM® developerWorks 
Sun Developer Network 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
C#

Overloading Operators in C#
By: O'Reilly Media
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 5 stars5 stars5 stars5 stars5 stars / 2
    2008-10-30

    Table of Contents:
  • Overloading Operators in C#
  • Operator Overloading
  • Overloading Equality and Comparison Operators
  • Overloading true and false

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    Overloading Operators in C#


    (Page 1 of 4 )

    In this seventh part of a ten-part series on C#, you will learn how and why to overload operators, and more. This article is excerpted from chapter four of C# 3.0 in a Nutshell, Third Edition, A Desktop Quick Reference, written by Joseph Albahari and Ben Albahari (O'Reilly; ISBN: 0596527578). Copyright © 2007 O'Reilly Media, Inc. All rights reserved. Used with permission from the publisher. Available from booksellers or direct from O'Reilly Media.

    Scenarios for Nullable Types

    One of the most common scenarios for nullable types is to represent unknown values. This frequently occurs in database programming, where a class is mapped to a table with nullable columns. If these columns are strings (e.g., an Email-Address column on a Customer table), there is not a problem as string is a reference type in the CLR, which can be null. However, most other SQL column types map to CLR struct types, making nullable types very useful when mapping SQL to the CLR. For example:

      // maps to a Customer table in a database
      public class Customer
      {
        ...
        
    public decimal? AccountBalance;
      }

    A nullable type can also be used to represent the backing field of an ambient property. An ambient property, if null, returns the value of its parent. For example:

      public class Row
      {
       
    ...
       
    Grid parent;
       
    Color? backColor;

        public Color BackColor
       
    {
         
    get { return backColor ?? parent.BackColor; }
         
    set { backColor = backColor == parent.BackColor ? null : value; }
       
    }
      }

    Alternatives to Nullable Types

    Before nullable types were part of the C# language (i.e., before C# 2.0), there were many strategies to deal with nullable value types, examples of which still appear in the .NET Framework for historical reasons. One of these strategies is to designate a particular nonnull value as the “null value”; an example is in the string and array classes. String.IndexOf returns the magic value of -1 when the character is not found:

      int i = "Pink".IndexOf ('b');
      onsole.WriteLine(s);         // outputs -1

    However,Array.IndexOfreturns-1only if the index is 0-bounded. The more general formula is thatIndexOfreturns 1 less than the minimum bound of the array. In the next example,IndexOfreturns0when an element is not found:

      // Create an array whose lower bound is 1 instead of 0:

      Array a = Array.CreateInstance (typeof(string),

                  new int[] {2}, new int[] {1});
      a.SetValue("a", 1);
      a.SetValue("b", 2);
      Console.WriteLine(Array.IndexOf(a, "c")); // outputs 0

    Nominating a “magic value” is problematic for several reasons:

    1. It means that each value type has a different representation of null. In contrast, nullable types provide one common pattern that works for all value types.
    2. There may be no reasonable designated value. In the previous example, –1 could not always be used. The same is true for our earlier examples representing an unknown account balance and an unknown temperature.
    3. Forgetting to test for the magic value results in an incorrect value that may go unnoticed until later in execution—when it pulls an unintended magic trick. Forgetting to testHasValueon a null value, however, throws anInvalidOperationExceptionon the spot.

    4. The ability for a value to be null is not captured in the type. Types communicate the intention of a program, allow the compiler to check for correctness, and enable a consistent set of rules enforced by the compiler.

    More C# Articles
    More By O'Reilly Media


       · This article is an excerpt from the book "C# 3.0 in a Nutshell, Third Edition, A...
     

    Buy this book now. This article is excerpted from chapter four of C# 3.0 in a Nutshell, Third Edition, A Desktop Quick Reference, written by Joseph Albahari and Ben Albahari (O'Reilly; ISBN: 0596527578). Check it out today at your favorite bookstore. Buy this book now.

    C# ARTICLES

    - Working with Dates and Times in C#
    - Generics, Dictionaries, and More
    - More About Generics
    - Working with C# Collections
    - Generics
    - C# and XML
    - Pointers and Arrays in C#
    - C# 3.0 Extension Methods
    - Overloading Operators in C#
    - Iterators and Nullable Types
    - Patterns and Iterators in C#
    - C# Exceptions
    - Methods in C#
    - Delegates and Events in C#
    - Advanced C#

     
    Best Practices for Windows Vista Migration Presentation
    Dell and Microsoft recently held a series of face-to-face seminars entitled, &qu....

     
    Creating a Culture for Code Reuse
    If you oversee development teams you know that like it or not proprietary and ex....

     
    Keys to Web Application Acceleration: Advances in Delivery Systems
    Accelerate Web apps by up to 5x. Ensure significantly faster access to the Web a....

     
    Optimizing Application Monitoring
    Tired of finding out from your customers that you're offline? This white paper e....

     
    Solaris to Solaris Migration -- Migrating applications from Sun SPARC to Dell PowerEdge R900
    This comprehensive Migration Guide reviews the approach that Principled Technolo....

     




    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 6 hosted by Hostway
    Stay green...Green IT