ASP.NET
  Home arrow ASP.NET arrow Chapter 5
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 
Dedicated Servers 
Actuate Whitepapers 
Moblin 
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? 
ASP.NET

Chapter 5
By: aspfree
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating:  stars stars stars stars stars / 0
    2002-10-06

    Table of Contents:

    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

    Stay one step ahead of the competition. Evaluate and give feedback on some of the hottest web development tools on the market today. Make your opinion heard! Click Here

    A Twisted Look at Object Oriented Programming in C#

    By Jeff Louie
    10/05/2002

    I must admit that my first exposure to object oriented programming (OOP) was frustrating and difficult. As a hobbyist I have struggled through Z80 assembly and EPROM burners, BASIC, Turbo Pascal, Java, C++ COM and now C#. The move to event driven programming and then to object oriented programming presented major conceptual hurdles to my function driven sequential programming mindset. The “aha” moment when OOP made sense was most gratifying, but did not come quickly or easily. It has been a few years since I “got” the OOP mindset and I feel comfortable enough now to try to help fellow travelers with this journey. If OOP comes easily to you, feel free to skip this tutorial. If you are having problems getting your mind around objects and inheritance I hope this tutorial can help you. This tutorial does not represent a conventional teaching method. It assumes a passing knowledge of the C# language and familiarity with the Visual Studio .NET IDE. This is a work in progress and may require correction or revisions. 

    Comments are actively requested (email: Jeff_Louie@yahoo.com). 

    Useful Texts 

    I highly recommend the following books. Much of my understanding of OOP has been gleamed from these “classic” texts and then reinforced from coding database projects in Java, C++ and C#. At all times I willfully try to avoid plagiarizing these authors, but my understanding of OOP is so closely tied to these texts that I must cite them as sources of knowledge right from the start! 

    Object-Oriented Analysis and Design with Applications Grady Booch, Second Edition, Addison-Wesley, 1994, 589pp. 

    Design Patterns Elements of Reusable Object-Oriented Software Gamma Helm, Johnson and Vlissides, Addison-Wesley, 1994, 395pp. 

    Object-Oriented Software Construction Second Edition Bertrand Meyer, Prentice Hall, 1997, 1254pp. 

    Of course, some of this material is a descendent of my writing from our now out of print book: 

    Visual Café for Java Explorer Database Development Edition Brogden Louie and Tittle, Coriolis, 1998, 595pp.

    Chapter 5 "C++ and Java Gumption Traps" 

    It's time for another break from theory and on to some real world programming challenges. In this chapter, you take a detour into the world of gumption traps. A gumption trap is a situation that is so frustrating that it sucks the "gumption" or energy out of you. Surprisingly, a lot of gumption traps come from preconceived notions of what "should" be correct. C++ and Java programmers are prone to gumption traps due to their assumptions about the C# language. In other words, C++ and Java programmers have a bit of "language baggage" that needs to be left behind. So, if you have a language neurosis, this chapter is for you.

    Top Ten C++ Gumption Traps

    In no particular order.

    1) Arrays in C# are Objects

    In C#, arrays are objects derived from System.Array. The following code snippet creates an array object that can contain ten elements of MyClass:

    MyClass[] arrayMC= new MyClass[10];
    What may surprise you, is that this call does not create any instances of MyClass! In fact, if you iterate over the array, you will find that the array contains ten null elements. To fill the array, you must explicitly create ten instances of MyClass and fill the array:
    MyClass[] arrayMC= new MyClass[10];
    [STAThread]
    static void Main(string[] args){    //    // TODO: Add code to start application here    //    Class1 c1= new Class1();    for (int i=0; i<10; i++)    {        c1.arrayMC[i]= new MyClass();    }    Console.ReadLine();}

    2) Declaring an Object Simply Creates an Un-initialized Object Variable

    In C++, when you declare an object, the object is created. Not so in C#. The following code simply declares an un-initialized reference variable of Type MyClass. The variable occupies memory on the stack to hold an address. No object is created on the heap. If you try to use c, the compiler will complain that the variable has not been initialized.

    MyClass c;

    The following code snippet, creates a variable and initializes the variable to null, so that the reference does not refer to any object. If you try to use the reference variable to touch a field or method of the class, the code will throw a null reference exception.

    MyClass c= null;

    So, if you want to declare and initialize a reference variable and create an object in C# you must use the new keyword like this:

    MyClass c= new MyClass();

    "c" is now a reference variable of Type MyClass. If this is a local variable, then "c" uses memory on the stack which contains the address of an object of Class MyClass on the heap.

    As discussed earlier, the string class (strings are immutable and shared) is an exception to the rule. You can create a string like this:

    string s= "Hello";

    3) C# Uses Automatic Garbage Collection, Destructors are not Deterministic

    The call to new may bother a C++ programmer who may now feel obligated to call delete appropriately. All I can say is lighten up! Objects are (mostly) reclaimed automatically in C#. In a nutshell, when available memory falls, the garbage collector is called, freeing up any objects that are unreachable. If you are done with an object, you can assist the garbage collector by releasing all references to the object. Even if two objects contain references to each other (circular references), the objects can still be collected if they become "unreachable."

    Since objects in C# are garbage collected, it is not a good idea to reclaim resources in the destructor. A destructor will not be called until the object is reclaimed by the garbage collector. In other words, destructors are not deterministic in C#. Critical external resources are best released by inheriting from IDisposable and implementing the Dispose method, or by using C#'s try, catch, finally construct to insure that any allocated resources are reclaimed in the finally clause. Here is a twisted example of try, catch, finally in C#:
     try 
    {
    OpenToiletLid();
    Flush();
    }
    catch(OverflowException e)
    {
    CallPlumber();
    }
    finally 
    {
    CloseToiletLid();
    }

    4) The Assignment Operator Does Not Call the Copy Constructor

    This one really confuses a lot of coders. In C# the assignment operator simply assigns a reference variable to an existing object, to a new object, or to null. After the assignment, the reference variable contains a reference to an object or to no object (is null). The assignment operator does not call the copy constructor to create a new object. It is quite legal in C# to have two reference variables that contain references to the same object. The two variables occupy different memory locations on the stack, but contain values that point to the same memory address on the heap. Both references would have to be released (e.g. the reference variables go out of scope, be reassigned, set to null) before the object can be reclaimed. As a result, the "destructor" will only be called once. The following code simply creates two references to the same object:

    MyClass c1= new MyClass();
    MyClass c2;
    c2= c1; 
    bool isSameReference= (c1 == c2);  
    // c1 and c2 contain references to the same object on the heap Console.WriteLine(isSameReference.ToString()); // output--> true
    Be clear that if variable c1 contains the only reference to an object, setting c1 to null or reassigning c1 to another object will make the original object unreachable and eligible for garbage collection.

    5) Values and References to Objects are Passed By Value

    By default, objects in C# are not passed by reference. (Unlike Java, C# does support passing by reference using the ref keyword.) In C#, you pass a reference or a value to a method. You cannot pass an object to a method. By default, all calls to methods are by value. Now is that clear! In other words, you pass a reference to an object to a method, not the object itself. The reference is passed by value so that the a copy of the reference goes on the stack. The key here is that the object is not copied onto the stack and you can touch the object while inside the method. If you want to truly pass an object by reference (for a swap routine) use the ref keyword. Remember, you cannot pass an object, so you are actually passing a reference by reference. Oh, I have a headache.

    6) Const is Hard Coded Into the Caller and not Version-able

    I find this one a bit weird. A const field value is hard coded into the caller for optimization so that the value is not updated until you recompile the caller. If you want to version-able read only field declare it readonly. Finally, you can provide a get only Property like this:

    public string ModelName
    {
        get
        {
            return modelName; // danger, return ModelName --> stack overflow!
        }
    }

    7) Supports Single Inheritance of Implementation and Multiple Inheritance of Interfaces

    C# does not support multiple inheritance of implementation. It does support multiple inheritance of interfaces (pure virtual classes) and single inheritance of implementation.

    8) Program to Return Single Values

    Although C# does support an out parameter, in general, C# programs are designed to return single values. Consider redesigning your application or returning immutable objects.

    9) Strings are Immutable

    The string class is a very special class. First strings are immutable. Every time you concatenate a string, you may be creating a new string object. If you want a mutable class, use StringBuilder. Second, you can create a string object using the assignment operator. Third, strings are shared so that two strings that you create may occupy the same space in memory. Fourth, the equality operator is overloaded for string and checks for content equivalence, not "reference based equality."

    Note: The overloaded string equality operator only works on reference variables of Type string. Be careful! Thanks to Jon S. for this insight.

    object a= "Hello";
    object b= "Hello";
    // test if a and b contain references to the same object 
    //or to no object (are both null)
    bool isSameReference= (a == b);
    // test if string referenced by a and string referenced b have
    //the same content/value // or a and b are both null
    bool isSameContent= ((string)a == (string)b); // Error! The left hand operand is of type object! Session["KEY"]="VALUE"; //This is a reference based comparison. Do this: (String)Session["KEY"]="VALUE"; // content equivalence

    10) bool is a Value Type

    C# has a built in type for Boolean which can have a value true or false. The default value of bool is false. Enough said.

    Top Ten Java Gumption Traps

    In no particular order.

    1) No Checked Exceptions

    The compiler in C# will not enforce catching of any checked exceptions. So there is no support for declaring a checked exception (no throws keyword).

    2) All Methods are Not Virtual By Default. All Members are Private by Default.

    In Java, all methods are virtual by default and can be overridden. Not so in C#. You must explicitly declare a method virtual if you want it to allow it to be overridden. You also cannot implicitly override or hide a virtual method, but must explicitly use the override or new keyword. In Java, members have package level access by default. In C# all members are private by default.

    3) Const, ReadOnly and Get Only

    I find this one a bit weird. A const field value is hard coded into the caller for optimization so that the value is not updated until you recompile the caller. If you want to version-able read only field declare it readonly. Finally, you can provide a get only Property like this:

    public string ModelName
    {
        get
        {
            return modelName; // danger, return ModelName --> stack overflow!
        }
    }

    4) All Types in the NET Framework Derive from Object

    C# has a unified type system so that all reference and value types derive from Object. For instance, int is an alias for System.Int32. As a result, you can call ToString() on any value or reference type. This simplifies debugging in the Console mode.

    5) The Visual Studio IDE Startup Object is Empty By Default

    If the startup object string is empty and you declare more than one "Main" method in a Visual Studio project, the project will not compile. This is very frustrating. Trying to set the startup object property in the Visual Studio IDE is non-trivial. Let me save you some pain. To set the startup object, select View --> Solution Explorer. In the Solution Explorer window select the name of the project. Now select View --> Property Pages. (Do not select the Property Window!) Alternatively, right click on the project name and select Properties. Now select the Common Properties folder in the left window. You can now select the appropriate startup object from the drop down list. Don't forget to click on "Apply."

    6) Method Names Start with Upper Case

    This one is pretty self explanatory.

    7) Getters and Setters are Implemented Using Properties, Which are Upper Case

    C# formally supports the concept of getters and setters with Properties. Note that properties are upper case by convention. Here are the setter and getter methods as properties:

              // Properties
             public int SecondsToToast 
            {
                get {return secondsToToast;}  
    // danger, return SecondsToToast --> stack overflow!             set               {                  if (value > 0)                  {                     secondsToToast= value;                 }                 else                   {                     secondsToToast= 0;                 }             }         }

    The reserved word value is used to represent the caller’s input. Note the syntax used to call a property. To set a property use:

    t.SecondsToToast= 12;

    8) Use "is" instead of "instanceof", ArrayList instead of ArrayList/Vector, StringBuilder instead of StringBuffer, Hashtable instead of HashMap/Hashtable, System.Environment.NewLine instead of line.separator..

    Just trying to save you some headaches.

    9) There is an "enum"

    Java evolved before the concept of type safe enum. C# has built in support for type safe enums like this:

    public enum ColorType {Black, Red, Yellow, White};
    private static ColorType DEFAULT_COLOR= ColorType.Black;

    You can still create a custom enum in C# like this:

    sealed class MyEnum
    {
        private String name;
        private static int nextOrdinal= 1;
        private int ordinal= nextOrdinal++;
        private MyEnum(String name)
        {
            this.name= name;
        }
        public override String ToString()
        {
            return name;
        }
        public int ToOrdinal()
        {
            return ordinal;
        }
        public static MyEnum INVALID= new MyEnum("Invalid"); // ordinal 1
        public static MyEnum OPENED= new MyEnum("Opened"); // ordinal 2
        public static MyEnum CLOSED=new MyEnum("Closed"); // ordinal 3
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            //
            // TODO: Add code to start application here
            //
            Console.WriteLine(MyEnum.OPENED.ToString());
            Console.WriteLine(MyEnum.OPENED.ToOrdinal().ToString());
            Console.WriteLine(MyEnum.INVALID.ToString());
            Console.WriteLine(MyEnum.INVALID.ToOrdinal().ToString());
            Console.WriteLine(MyEnum.CLOSED.ToString());
            Console.WriteLine(MyEnum.CLOSED.ToOrdinal().ToString());
            Console.ReadLine();
        }
    }

    10) String Equality Operator is Overridden for Content Comparison

    Thankfully, the string equality operator in C# has been overloaded and checks for content/value equivalence. One less gotcha for the C# novice.

    Note: The overloaded string equality operator only works on reference variables of Type string. Be careful! Thanks to Jon S. for this insight.

    object a= "Hello";
    object b= "Hello";
    // test if a and b contain references to the same object or to no object (are both null)
    bool isSameReference= (a == b); 
    // test if string referenced by a and string referenced b have the same content/value 
    // or a and b are both null
    bool isSameContent= ((string)a == (string)b);
    // Error! The left hand operand is of type object!
    Session["KEY"]="VALUE"; 
    //This is a reference based comparison. Do this:
    (String)Session["KEY"]="VALUE"; // content equivalence

    OK, boys and girls. It's not your father's language. Get over it<g>.

    The Equality Operator Revisited

    Thanks to Jon S. I have revisited the concept of equality on operands of the reference type. The equality operator, in general, compares operands by reference. The string equality operator is overloaded to compare operands by value. In plain English, the equality operator normally checks to see if two object variables refer to the same object on the heap. The string equality operator is overloaded to check for content or value equivalence.

    In not so plain English, the equality operator normally checks to see if two reference variables contain references to the same object on the heap. In C# local reference variables go on the stack and contain the address of the object on the heap. So local reference based equality in C# checks to see if two reference variables, stored on the stack, contain addresses which are equal. In other words, it checks for address equality. This is referred to as "reference based" equality or "compare by reference" or "referential equality". Whew!

    As previously stated, the string equality operator is overloaded to check for value or content equivalence. In not so plain English, the string equality operator compares the content or value of string objects on the heap. It does this by obtaining the address of the objects from the values of the reference variables stored on the stack.

    Now I would like to simplify this discussion to that of "object" equality vs. "content" equality, but I cannot! By convention, object equality refers to content equality! I would also like to reduce this discussion to referential "equality" vs. content "equivalence", but I cannot. Unfortunately, by convention, the Equals() method is used to determine content equivalence!

    All Rights Reserved Jeff Louie 2002


    DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

    More ASP.NET Articles
    More By aspfree

     

    IBM® developerWorks developerWorks - FREE Tools!


    Build Forge Express demo: Enabling software delivery excellence for small and midsized businesses

    This demonstration gives you an overview of IBM® Rational® Build Forge Express Edition, a global offering that provides a framework to automate and execute software processes. Rational Build Forge provides a software assembly line that can support all of your tools, technologies, and platforms so you can achieve a repeatable, reliable, and traceable build and release process.
    FREE! Go There Now!


    Check out the new Jazz space on developerWorks

    <a href="http://zeus.developershed.com/shonuff.php?blackbird=3853&zoneid=442&source=&dest=http%3A%2F%2Fwww.ibm.com%2Fdeveloperworks%2Fspaces%2Fjazz%3FS_TACT%3D105AGY31%26S_CMP%3DDEVSHED&ismap="><img src="http://images.devshed.com/corp/img/news/jazz01.gif" alt="developerWorks Jazz space" align="left"></a>You've heard the buzz about Jazz... want to know more about it from a developer's perspective? Check out the Jazz space on developerWorks. This space is an up-to-date resource for developers, including technical information about Jazz and products built on Jazz, like Rational Team Concert Express. The Jazz space includes content from a wide variety of sources, including links, feeds, and comments from experts.
    FREE! Go There Now!


    IBM DB2 Deep Compression ROI Tool

    The IBM DB2 Deep Compression ROI tool is designed for DBA’s and IT management personnel to perform a clinical analysis of the cost savings gained from the Storage Optimization feature of DB2 9 for Linux, UNIX and Windows. The feature, also known as Deep Compression, compresses data that lies within a database by up to 80% at times.
    FREE! Go There Now!


    NEW! "ebook: Exploring IBM SOA Technology & Practice

    Learn field-tested SOA principles, methodology, technology and implementation from the global SOA market leader - in a new e-book by an IBM SOA expert. Written by IBM Certified SOA Solution Designer Bobby Woolf, "Exploring IBM SOA Technology & Practice" is the ultimate insider's guide to SOA - a PDF e-book packed cover to cover with IBM's specific advice on how to make your SOA implementation a success.
    FREE! Go There Now!


    NEW! Application Development Tools for the Mainframe Developer

    You probably have thousands of lines of COBOL code loaded with business intelligence and being used to run your business, along with an army of developers maintaining these applications. Learn how to prepare your applications and developers so you can keep that competitive edge and move to a service-oriented architecture with the IBM Rational Enterprise Modernization solutions. Replay is available for 9 months.
    FREE! Go There Now!


    NEW! Applying lean thinking to the governance of software development

    Effective governance for lean development isn’t about command and control. Instead, the focus is on enabling the right behaviors and practices through collaborative and supportive techniques. Hear from Scott Ambler on how it is far more effective to motivate people to do the right thing than it is to force them to do so. Learn how to form a lightweight, collaboration-based framework that reflects the realities of modern IT organizations.
    FREE! Go There Now!


    NEW! BlammoSplat: Build a community Web site of OpenLaszlo animations, Part 3: The community animation

    Learn to enable users to both rate existing animations and to combine existing animations into new snippets. This is the third in a series of three tutorials that chronicle the building of a site that enables collaborative discussion and animation building using Domino and OpenLaszlo.
    FREE! Go There Now!


    NEW! Evaluate Rational Business Developer V7.1

    Visit IBM developerWorks to download a free trial version of IBM Rational Business Developer V7.1. Rational Business Developer offers rapid and simplified development of business applications and services through Enterprise Generation Language (EGL) tools, generating Java or mainframe solutions while shielding developers from technical complexities.
    FREE! Go There Now!


    NEW! Trial download: IBM Rational Method Composer V7.2

    Get a free trial download of the latest version of IBM Rational Method Composer V7.2 which helps you deliver customized yet consistent process guidance to your project teams and IT organization, and includes the latest version of IBM Rational Unified Process (RUP), which has provided process guidance to teams since 1996.
    FREE! Go There Now!


    NEW! Whitepaper: Achieving consistency between business process models and operational guides

    Explore how Rational and WebSphere software enable enterprise documentation in SOA environments. Specifically, a new integration between IBM WebSphere® Business Modeler and IBM Rational® Method Composer software can help technical writers more easily keep enterprise operations manuals in sync with changes that are made to business processes, resulting in more accurate and timely documentation that benefits the entire enterprise.
    FREE! Go There Now!



    All FREE IBM® developerWorks Tools!

    ASP.NET ARTICLES

    - Enhancing PHP Via the ASP.NET AJAX Framework...
    - Enhancing PHP Programming with the ASP.NET A...
    - Classes and ASP.NET AJAX
    - Using ASP.NET AJAX
    - Building a Simple Storefront with LINQ
    - Developing a Dice Game Using ASP.NET Futures...
    - Completing an ASP.NET AJAX Server-Centric Ba...
    - Information Management for an ASP.NET AJAX S...
    - Comment and Order Management for an ASP.NET ...
    - Back-end Management Tasks for an ASP.NET AJA...
    - User Information Management for an ASP.NET A...
    - Adding Comments and Search to an ASP.NET AJA...
    - Order-Related Modules for an ASP.NET AJAX Se...
    - User and Role Management for an ASP.NET AJAX...
    - Programming an ASP.NET AJAX Server-Centric B...





    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 5 hosted by Hostway