C#
  Home arrow C# arrow Handling Methods and Functions
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  
Silverlight  
Visual Basic.NET  
Windows Scripting  
Windows Security  
XML  
Mobile Linux 
App Generation ROI 
IBM® developerWorks 
ASP Web Hosting  
ASP.NET Web Hosting 
Windows Web Hosting
 
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#

Handling Methods and Functions
By: O'Reilly Media
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 5 stars5 stars5 stars5 stars5 stars / 1
    2009-11-03

    Table of Contents:
  • Handling Methods and Functions
  • Overloading Methods and Constructors
  • Encapsulating Data with Properties
  • The get Accessor
  • Property Access Modifiers

  • 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


    Handling Methods and Functions


    (Page 1 of 5 )

    In this conclusion to a four-part series on classes and objects in C#, you'll learn how to overload methods and constructors, handle property class modifiers, and more. This article is excerpted from chapter four of the book Programming C# 3.0, fifth edition, written by Jesse Liberty and Donald Xie (O'Reilly, 2008; ISBN: 0596527438). Copyright © 2008 O'Reilly Media, Inc. All rights reserved. Used with permission from the publisher. Available from booksellers or direct from O'Reilly Media.

     Overcoming Definite Assignment without Parameters

    C# imposes definite assignment, which requires that all variables be assigned a value before they are used. In Example 4-7, if you don’t initializetheHour,theMinute, andtheSecondbefore you pass them as parameters toGetTime(), the compiler will complain. Yet, the initialization that is done merely sets their values to0before they are passed to the method:

      int theHour = 0;
      int theMinute = 0;
      int theSecond = 0;
      t.GetTime( ref theHour, ref theMinute, ref theSecond);

    It seems silly to initialize these values because you immediately pass them by reference intoGetTime where they’ll be changed, but if you don’t, the following compiler errors are reported:

      Use of unassigned local variable
    'theHour'
      Use of unassigned local variable 'theMinute'
      Use of unassigned local variable 'theSecond'

    C# provides theoutparameter modifier for this situation. Theoutmodifier removes the requirement that a reference parameter be initialized. The parameters toGetTime(), for example, provide no information to the method; they are simply a mechanism for getting information out of it. Thus, by marking all three asoutparameters, you eliminate the need to initialize them outside the method. Within the called method, theoutparameters must be assigned a value before the method returns. The following are the altered parameter declarations forGetTime():

      public void GetTime(out int h, out int m, out int s)
     
    {
        h = Hour;
        m = Minute;
        s = Second;
     
    }

    And here is the new invocation of the method inMain():

      t.GetTime( out theHour, out theMinute, out theSecond);

    To summarize, value types are passed into methods by value.refparameters are used to pass value types into a method by reference. This allows you to retrieve their modified values in the calling method.outparameters are used only to return information from a method. Example 4-8 rewrites Example 4-7 to use all three.

    Example 4-8. Using in, out, and ref parameters

    #region Using directives

    using System;
    using System.Collections.Generic;
    using System.Text;

    #endregion

    namespace InOutRef
    {
      public class Time
     
    {
       
    // private member variables
        private int Year;
        private int Month;
        private int Date;
        private int Hour;
        private int Minute;
        private int Second;

        // public accessor methods
        public void DisplayCurrentTime()
        {
         
    System.Console.WriteLine( "{0}/{1}/{2} {3}:{4}:{5}",
            Month, Date, Year, Hour, Minute, Second );
        }

        public int GetHour()
        {
          return Hour;
        }

        public void SetTime( int hr, out int min, ref int sec )
       
    {
          // if the passed in time is >= 30
          // increment the minute and set second to 0
          // otherwise leave both alone
          if ( sec >= 30 )
          {
           
    Minute++;
           
    Second = 0;
          }
          Hour = hr; // set to value passed in

          // pass the minute and second back out
          min = Minute;
          sec = Second;
       
    }

        // constructor
        public Time( System.DateTime dt )
        {
         
    Year = dt.Year;
          Month = dt.Month;
          Date = dt.Day;
          Hour = dt.Hour;
          Minute = dt.Minute;
         
    Second = dt.Second;
        }
      }

      public class Tester
     
    {
        static void Main()
        {
         
    System.DateTime currentTime = System.DateTime.Now;
          Time t = new Time( currentTime );
          t.DisplayCurrentTime();

          int theHour = 3;
          int theMinute;
          int theSecond = 20;

          t.SetTime( theHour, out theMinute, ref theSecond );
         
    System.Console.WriteLine(
            "the Minute is now: {0} and {1} seconds",
            theMinute, theSecond );

          theSecond = 40;
          t.SetTime( theHour, out theMinute, ref theSecond );
          System.Console.WriteLine( "the Minute is now: " +
           
    "{0} and {1} seconds", theMinute, theSecond );
        }
      }
    }

    Output:
    11/17/2007 14:6:24
    the Minute is now: 6 and 24 seconds
    the Minute is now: 7 and 0 seconds

    SetTimeis a bit contrived, but it illustrates the three types of parameters.theHouris passed in as a value parameter; its entire job is to set the member variableHour, and no value is returned using this parameter.

    TherefparametertheSecondis used to set a value in the method. IftheSecondis greater than or equal to 30, the member variableSecond is reset to 0, and the member variableMinuteis incremented.

    You must specifyrefon the call and the destination when using reference parameters.

    Finally,theMinuteis passed into the method only to return the value of the member variableMinute, and thus is marked as anoutparameter.

    It makes perfect sense thattheHourandtheSecondmust be initialized; their values are needed and used. It is not necessary to initializetheMinute, as it is anoutparameter that exists only to return a value. What at first appeared to be arbitrary and capricious rules now make sense; values are required to be initialized only when their initial value is meaningful.

    More C# Articles
    More By O'Reilly Media


     

    C# ARTICLES

    - Coding a CRC-Generating Algorithm in C
    - Cyclic Redundancy Check
    - Handling Methods and Functions
    - Destroying Objects in C#
    - Creating Objects in C-Sharp
    - Classes and Objects
    - Programming Languages: Managed versus Native
    - LINQ-to-MySQL with DbLinq in C#
    - 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#





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 4 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek