ASP.NET Code
  Home arrow ASP.NET Code arrow A Twisted Look at Object Oriented Programm...
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? 
ASP.NET CODE

A Twisted Look at Object Oriented Programming in C# (Part 1)
By: Jeff Louie
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 5
    2002-09-07

    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


    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).[bold]Useful Texts[/bold]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![bold]Object-Oriented Analysis and Design with Applications Grady Booch, Second Edition, Addison-Wesley, 1994, 589pp.[/bold][bold]Design Patterns Elements of Reusable Object-Oriented Software Gamma Helm, Johnson and Vlissides, Addison-Wesley, 1994, 395pp.[/bold][bold]Object-Oriented Software Construction Second Edition Bertrand Meyer, Prentice Hall, 1997, 1254pp.[/bold]Of course, some of this material is a descendent of my writing from our now out of print book: [bold]Visual Café for Java Explorer Database Development Edition Brogden Louie and Tittle, Coriolis, 1998, 595pp.[/bold]- Chapter 1 "Classes, Objects, and Properties" -[bold]Why program with objects and inheritance?[/bold] Simply put, programming with objects simplifies the task of creating and maintaining complex applications. OOP is a completely different way of thinking that differs significantly from the more traditional function driven sequential programming model of old. Programming with objects without inheritance is ?object-based? programming. Adding inheritance to objects is ?object-oriented? programming. OOP provides built in support for code reuse (inheritance) and support for runtime variations in program behavior (polymorphism). Without attempting to define these terms, OOP at a minimum:1. Simplifies the creation and maintenance of complex applications. 2. Promotes code reuse. 3. Allows flexibility in runtime program behavior (a very cool feature). [bold]What is OOP?[/bold]Well, lets cut right to the point. What the heck is Object Oriented Programming? Answer: It is a whole new way of thinking about programming! It is a way of modeling software that maps your code to the real world. Instead of creating programs with global data and modular functions, you create programs with ?classes?. A class is a software construct that maps to real world things and ideas. Think of a class as a blueprint that contains information to construct a software object in memory. Unlike a simple data structure, software objects contain code for both data and methods. The class binds the data and methods together into a single namespace so that the data and methods are intertwined.Just as you can build more than one house from a single blueprint, you can construct multiple software objects from a single class. Each object (represented by code in memory) is generated from a class and is considered an ?instance? of the class. Since each instance of the class exist in separate memory space, each instance of the class can have its own data values (state). Just as multiple houses built from a single blueprint can differ in properties (e.g. color) and have identity (a street address), multiple objects built from a single class can differ in data values and have a unique identifier (a C++ pointer or a reference handle in C#). Got that! Now take and break and re-read this paragraph. When you come back, you can look at some C# code.[bold]What is a class?[/bold]A class is a software construct, a blueprint that can describe both values and behavior. It contains the information needed to create working code in memory. When you create an object, you use the information in the class to generate working code. Let?s create a simple program that models a toaster! The toaster is a real life object. The toaster can have state such as secondsToToast and has a behavior, MakeToast(). Here is our first toaster class in C#:


    class Toaster1 

        
    /// <summary> 
        /// The main entry point for the application.
        /// </summary>
        
    [STAThread]
        static 
    void Main(string[] args)
        {
            
    //
            // TODO: Add code to start application here
            //
             
    Toaster1 t= new Toaster1();
            
    System.Console.WriteLine(t.MakeToast());
            
    System.Console.ReadLine();
        }
        private 
    int secondsToToast10;
        public 
    string MakeToast() 
        {
             return 
    "Toasted for "+secondsToToast.ToString()+" seconds.";
        }
    }

    If you execute this program, the output is:?Toasted for 10 seconds.?A working toaster yes, but not very useful unless you like 10-second toast .[bold]What is an object?[/bold]An object is an instance of a class. A specific class describes how to create a specific object in memory. So the class must contain information about the values and behaviors that each object will implement. You can create an object using the reserved word ?new?. In our Toaster1 application, you create a single instance of the Toaster1 class with the call:


    Toaster1 t= new Toaster1();

    The reference variable ?t?, now contains a reference to a unique instance of the Toaster1 class. You use this reference variable to ?touch? the object. In fact, if you set the reference variable ?t? to null, so that the object is no longer ?touchable?, the garbage collector will eventually delete the Toaster1 object!


    tnull;  

    // If "t" contains the only reference to the Toaster1 object, the object can be garbage collected. (Strictly speaking, if the Toaster1 object cannot be "reached", it can be garbage collected.)

    MakeToast() is a public method of the Toaster1 object so it can be called from outside the class (Main) using the reference variable ?t? to touch the object?s behavior:


    t.MakeToast();

    Since each object exists in a separate memory space, each object can have state, behavior and identity. Our Toaster1 object has identity since it is unique from any other object created from the Toaster1 class:


    Toaster1 t2= new Toaster1();

    Now there are two instances of the Toaster1 class. There are two reference variables ?t? and ?t2?. Each reference variable identifies a unique object that exists in a separate memory address. Since each object contains a method MakeToast(), each object has behavior. Finally, each object contains a value ?secondsToToast()?. In a sense, each object now has its own ?state?. However, the state is the same for each object! This is not a very useful class design. In fact, the Toaster1 class is not a good representation of a real world toaster since the toast time is immutable. Here is a second run at the Toaster class that demonstrates the use of public ?accessors?, get and set methods. This is a standard idiom in OOP. The actual data is declared private (or protected) so that users of the class cannot access the underlying data. Instead, public methods are exposed to the callers of the class to set and get the underlying hidden data values.Note: The modifiers ?private?, ?protected? and ?public? are access modifiers that control the visibility of methods and data. The compiler will enforce these visibility rules and complain if you say try to touch a private variable from outside the class. ?Public? methods and data are visible to any caller. ?Private? methods and data are only visible and ?touchable? within the class. ?Protected? is a special level of access control of great interest to object oriented programmers, but is a subject that must be deferred to the chapter on inheritance. If you don?t declare an access modifier, the method or variable is considered private by default.


    using System;namespace JAL
    {
        
    /// <summary>
        /// Summary description for class.
        /// </summary>
        ///  
        
    class Toaster2
        
    {
            
    /// <summary>
            /// The main entry point for the application.
            /// </summary>
            
    [STAThread]
             static 
    void Main(string[] args
            {
                
    Toaster2 t= new Toaster2();
                
    t.SetSecondsToToast(12);
                
    Console.WriteLine(t.MakeToast());
                
    Console.ReadLine();
            }
        private 
    int secondsToToast0;
        public 
    string MakeToast() 
        {
            return 
    "Toasted for "+GetSecondsToToast().ToString()+" seconds.";
        }
        
    // Public Accessor Functions, Get and Set
        
    public bool SetSecondsToToast(int seconds
        {
            if (
    seconds 0
            {
                
    secondsToToastseconds;
                return 
    true;
            }
            else 
            {
                
    secondsToToast0;
                return 
    false;
            }
        }
        public 
    int GetSecondsToToast() 
        {
             return 
    secondsToToast;
        }
        }


    The callers of the class cannot ?touch? the secondsToToast variable which remains private or ?hidden? from the caller. This idiom is often called ?encapsulation? so that the class encapsulates or hides the underlying data representation. This is an important aspect of OOP that allows the writer of the class to change the underlying data representation from say several variables of type int to an array of ints without affecting the caller. The class is a ?black box? that hides the underlying data representation. In this new version of toaster, Toaster2, there are two new methods: SetSecondsToToast() and GetSecondsToToast(). If you look at the ?setter? method it validates the callers input and sets the value to zero if the callers input is invalid (<0):


    public void SetSecondsToToast(int seconds
    {
        if (
    seconds 0
        {
            
    secondsToToastseconds;
        }
        else 
        {
            
    secondsToToast0;
        }
    }

    The ?getter? method really does not do much simply returning the private data value ?secondsToToast?:


    public int GetSecondsToToast() 
    {
        return 
    secondsToToast;
    }

    [bold]What is a property?[/bold]C#.NET implements a language idiom called a ?property?. In a nutshell, ?a property is a method that appears as a variable?. By convention, a property name starts with an uppercase letter. Here is our new version of Toaster that replaces the get and set methods with properties:


    using System;namespace JAL
    {
        
    /// <summary>
        /// Summary description for class.
        /// </summary>
        ///  
        
    class Toaster3
        
    {
            
    /// <summary>
            /// The main entry point for the application.
            /// </summary>
            
    [STAThread]
            static 
    void Main(string[] args
            {    
                
    Toaster3 t= new Toaster3();
                
    t.SecondsToToast12;  // the property idiom
                
    Console.WriteLine(t.MakeToast());
                
    Console.ReadLine();
            }
            private 
    int secondsToToast0;
            public 
    string MakeToast() 
            {
                return 
    "Toasted for "+secondsToToast.ToString()+" seconds.";
            }
            
    // Properties
             
    public int SecondsToToast 
            
    {
                
    get {return secondsToToast;}
                
    set  
                
    {
                     if (
    value 0
                    {
                        
    secondsToToastvalue;
                    }
                    else  
                    {
                        
    secondsToToast0;
                    }
                }
            }
        }
    }

    Here are the new setter and getter methods as properties:


              // Properties
             
    public int SecondsToToast 
            
    {
                
    get {return secondsToToast;}
                
    set  
                
    {
                     if (
    value 0
                    {
                        
    secondsToToastvalue;
                    }
                    else  
                    {
                        
    secondsToToast0;
                    }
                }
            }

    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.SecondsToToast12;

    The method set() now appears as a variable ?SecondsToToast?. So ?a property is a method that appears as a variable?.Well, congratulations. You have constructed your first real world class in C#. Since this is a hands on tutorial, I strongly urge you to compile the Toaster3 code and experiment.[bold]All Rights Reserved Jeff Louie 2002[/bold]
    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 Code Articles
    More By Jeff Louie

     

    IBM® developerWorks developerWorks - FREE Tools!


    NEW! Trial download: IBM Lotus Forms V3.0

    Get a free trial download of IBM Lotus Forms V3.0 (formerly Workplace Forms), which provides a zero-footprint eForms solution to help you automate and move forms-based business processes off the desktop and onto the Web. With Lotus Forms, you can extend applications beyond the firewall by creating a single electronic form document ready for use in both thick and Web 2.0 thin client format.
    FREE! Go There Now!


    NEW! Maintaining QoS and Process Integrity in an SOA Environment

    This webcast outlines the best practices that must be instituted to gain the maximum benefit from SOA while maintaining high quality of service. Whether you are deploying new applications or managing and monitoring your existing infrastructure, learn how you can ensure high quality of services with SOA based solutions from IBM. All registrants who attend this live Web Seminar will receive complimentary access to a white paper titled “Maintaining QoS in an SOA Environment”.
    FREE! Go There Now!


    NEW! Download DB2 9.5 for Linux, Unix, and Windows

    Download a free trial version of IBM DB2 9.5 for Linux, UNIX, and Windows. DB2 9 is the result of a five-year development project that transformed traditional (static) database technology into an interactive data server that merges the high performance and ease of use of DB2 with the self-describing benefits of XML.
    FREE! Go There Now!


    NEW! Harnessing the power of SQL and Java for high performance data access

    Join this webcast to see how IBM Data Studio Developer and pureQuery can take the pain out of Java data access. uApplications developed using both Java and SQL have become a common requirement. Database connectivity using Java Database Connectivity (JDBC) to create an application is a multi-step tedious process, and tooling that covers both SQL and Java has been unavailable, until now. IBM Data Studio introduces the pureQuery platform: a high-performance, Java data access platform focused on simplifying the tasks of developing, managing, and optimizing database applications and services.
    FREE! Go There Now!


    NEW! Section 508 of the U.S. Rehabilitation Act: Web accessibility compliance

    Because access to government information continues to be an area of concern for many U.S. citizens with disabilities, the U.S. government enacted Section 508 of the Rehabilitation Act in 2001 to ensure that government agencies create accessible Web content, enabling all citizens to access the information they need. A fully accessible Web site makes Web content accessible to all individuals, including those with disabilities, who may be accessing Web content via a variety of user agents. Common user agents include standard Web browsers, text-only browsers, assistive devices and mobile devices such as cell phones or personal digital assistants (PDAs).
    FREE! Go There Now!


    NEW! Rational Asset Manager eKit

    Learn how to do more with your reusable assets with the free Rational Asset Manager eKit. The eKit includes demos on how Rational Asset Manager tracks and audits your assets in order to utilize them for reuse. Plus you’ll find white papers and a Webcast that discuss the challenges of a Service Oriented Architecture and how Rational Asset Manager can provide quick and effective solutions.
    FREE! Go There Now!


    NEW! Software Change and Configuration Management Solution Guidelines

    This whitepaper provides areas to consider when evaluating any software configuration management solution. It addresses how the IBM solutions (Rational ClearCase and Rational ClearQuest) meet the needs and requirements of both project leaders and developers to provide successful Software Change and Configuration Management.
    FREE! Go There Now!


    NEW! The role of integrated requirements management in software delivery

    This paper is about the critical role that a discipline called integrated require­ments management can play in helping to ensure that your business goals and IT investments are continuously aligned—whether you are sourcing, integrat­ing, building or maintaining software. It also looks at ways that automated IBM Rational® products can work together to help you use requirements in the very best way.
    FREE! Go There Now!


    Role of Integrated Requirements Management in Software Delivery

    As organizations integrate software into every aspect of business, they are constantly pressured to deliver faster, better, and cheaper results. Unfortunately, a “dis-integrated” software delivery approach reduces returns while increasing costs. This IBM Rational White Paper shows how Integrated Requirements Management aligns organizations around maximizing value and keeping pace with change.
    FREE! Go There Now!


    NEW! The dirty dozen: preventing common application-level hack attacks

    As organizations have grown increasingly dependent on online software, the risk of malicious attacks has also become far more serious. Fortunately, well-governed organizations can protect their Web applications by injecting vulnerability assessments and ethical hacks into their software development and delivery processes. This paper describes 12 of the most common hacker attacks and provides basic rules that you can follow to help create more hack-resistant Web applications.
    FREE! Go There Now!



    All FREE IBM® developerWorks Tools!

    ASP.NET CODE ARTICLES

    - How to Use the ListBox Control in ASP.NET 2.0
    - How to Load XML Documents in ASP.NET 2.0
    - DataGrid Code
    - ASP.NET Guestbook
    - User Controls and Client Side Scripting
    - ASP.NET Programming with Microsoft's AS...
    - ASP.NET Basics (part 3): Hard Choices
    - ASP.NET Basics (part 2): Not My Type
    - ASP.NET Basics (part 1): Nothing But .Net
    - Directory Tree Browser
    - How to get the confirmation of Yes/No from a...
    - Complete example using custom errors and wri...
    - Paging Certain # records per page .NET style
    - General Methods of formatting and Subtractin...
    - .NET LinkButton web control





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