Sunday, November 28, 2004

Inheritance, Polymorphism, and Casting

In browsing various newsgroups, I found a number of questions pertaining to inheritance, polymorphism, and casting (typically all in the same post). It seemed like quite a few people out there are confused about these concepts and how they are applied so hopefully this entry can clear things up.

Inheritance allows us to extend the functionality of a class (base class) to provide more specialized functionality in a derived (child) class. This is accomplished by: providing new functionality and/or overriding (or hiding) existing functionality.

Polymorphism, on the other hand, can almost be thought of as reverse inheritance; rather than adding functionality by becoming more specific, functionality is removed by becoming less specific. This allows for multiple, related classes that provide similar functionality to be use in a generic sense. For example: a class may be substituted with its base class in order to write code that can be used by all of the specialized classes but is not tied to the specialized classes.

Casting instructs the runtime to "convert" a variable of one type into another type. What is actually happening is that the program is saying "for the object located at X, use the memory structure for type A rather than B," A common example of casting comes from ADO.NET. When using the ExecuteScalar() method of a Command object to retrieve a count of rows, it is necessary to cast the result from Object to a numeric type: int cnt = (int)cmd.ExecuteScalar();

Casting operations can be performed implicitly or explicitly. Implicit casts (int to long) are performed automatically by the CLR when the allocated space needs to be increased. Explicit casting operations (long to int) must be specified in the code.

Note that casting requires compatible types meaning that a conversion operator must be defined. Casting from a class to its base class may be performed implicitly while casting from a base class to a derived class must be performed explicitly.

Consider the following code that demonstates these principles. To run this code, create a new Console project in Visual Studio and copy/paste it into the automatically created file. (for command line compilation, copy/paste the code into notepad, save as example.cs, and execute csc example.cs at the command line.)



After compiling and executing the code, the following is displayed:



The Animal class provides some basic functionality that each animal will need to have. Eat() and Sleep() methods have been defined along with some basic fields such as NumberOfLegs.

A Cat class and Dog class are also defined and each derives from Animal. The Cat and Dog classes each inherit the functionality provided by the Animal class and extend upon it by adding some new functionality. The added functionality is only accessible from the class in which it was defined. Notice that each class overrides the functionality provided by the Eat() method. The Cat and Dog classes also implement the interface ISpeaks which requires that a method called Speak() be defined.

The StartUp class defines the entry point (Main()) and a few other methods to demonstrate the concepts of inheritance and polymorphism. When the program executes, an instance of the Cat and Dog classes are created. Each of the methods are called for both the Cat and the Dog.

Each of the methods called by the Main() method illustrate polymorphism since each method accepts an Animal (from which Cat and Dog are derived) as an argument. At this point, only the functionality provided by the Animal class is accessible despite the fact that a Cat or Dog was passed to the method. This is illustrated by the Sleep() and Eat() methods of the StartUp class.

The Sleep() method calls a.Sleep(). As indicated in the output [above], when Sleep() is called, the Sleep() method from the Animal class is executed as expected because the functionality provided by Sleep() is inherited by the Cat and Dog classes. Where the polymorphism is truly apparent though is in the Eat() method.

When Eat() is called, the output differs based on the type of animal that was passed in despite the fact that a.Eat() was called. Both the Cat and Dog classes override the Eat() method and provide their own functionality. The CLR knows that, despite being declared as type Animal, the value of the variable "a" is really a more specialized type (Cat or Dog) and calls the appropriate method.

For another example of polymorphism in action, the Speak2() method is included. The Speak2() method accepts a parameter of type ISpeaks rather than Animal. Remember that the Cat and Dog classes both implement the ISpeaks interface and, therefore; are required to define a method called Speak().

When Speak2() is called, the Cat or Dog is implicitly cast to a variable of type ISpeaks. The Speak() method of parameter is called, and like the Speak() method, the CLR knows the actual type of the variable and calls the appropriate method.

Explicit Casting is used by the Speak() and MakeHappy() methods. Additionally, these methods use the C# "is" keyword to determine the actual type that was passed to the method. The Animal class does not provide definitions for Meow() or Woof(), for example, so the variable must be cast back to its actual type in order for the functionality to be utilized.

In conclusion, the concepts of inheritance, polymorphism, and casting can be powerful tools but also reinforce the importance of good application design. The examples shown here barely scratch the surface of the potential of these concepts but should serve as a good foundation for further study.

Thursday, November 25, 2004

CLR Integration in SQL Server 2005

I have just finished reading a white paper regarding CLR integration in SQL Server 2005. To me, the integration of the CLR into SQL Server has been the most exciting aspect of the new version so I was glad to see a paper getting into some of the details of its place in the toolbox.

When I reached the section regarding the steps that must be taken to "install" a managed code procedure I couldn't help but think that it sounded like a lot of manual steps to perform for every assembly. Luckily, Microsoft anticipated this and built functionality to automate much of this though Visual Studio 2005.

Highlights of the paper include:

  • A discussion of when managed code procedures are preferred to T-SQL.
  • Demonstrations of using managed stored procedures to validate column values using regular expressions.
  • Examples of table valued functions that retrieve their value from externally hosted XML documents (such as RSS feeds).

While the paper mentioned that other assemblies may be referenced from the assemblies that are uploaded into SQL Server 2005, a few questions on this subject were left unanswered though. [If these questions have been answered in other papers, I'd love to be directed to them.]

  • Do the referenced assemblies have to be uploaded into SQL Server too?
  • Can the managed code procedure consume Web Services?
  • Can the managed code procedures reference assemblies stored in the GAC?

I truly hope that developers take the time to thoroughly understand when managed code procedures are appropriate. Too often, features are overused simply "because they're there." I regularly see people fall into this mindset where they feel that they must use a feature or tool because of the "coolness" of it rather than actually examining if it is the proper thing to do.

A great example of this mindset is found with PowerPoint presentations. How often do people use multi-million color backgrounds or assign a sound to every animation simply for the sake of doing it and because they think that it is "cool" or "neat?"

More often than not, these presentations are unreadable because the text blends into the background. If the eyestrain from trying to read the slides doesn't give the audience members a collective headache, the constant mechanical keyboard sound certainly will!

What's worse is that these presenters typically seem to be completely oblivious to the frustration that they have given to their audience. It's as though the tool has made them forget that their purpose is to present information. Additionally, these presenters do not seem to realize that the audience has learned little from the presentation because they have gotten lost in the distractions created by the presenter.

Wednesday, November 24, 2004

Let it snow

Thanksgiving is upon us and right on cue, so is winter. My wife (Esther) and I were travelling to visit my parents when the rain changed to sleet and finally into snow, but only after a "nice" layer of ice had formed on the interstate.

What is normally a two hour trip quickly stretched into four hours of nearly bumper-to-bumper traffic with vehicles of all shapes and sizes sliding off the road. Several cars had crashed into trees while others were crushed against the concrete barrier.

Frozen, two-inch diameter branches have been breaking off of the trees in my parents' back yard. Some smaller branches had also broken off of their tree and fallen into the street. Luckily, we were able to avoid any incidents on the way.

Today was the first opportunity I have had to learn how my '05 VW Jetta TDI handles winter weather. Overall it handled well until I reached an area with about four inches of loose snow. It was then that I started missing the Quattro that was present on my old TT.

Inaugural Post

There has been a lot of buzz in the media lately about these "blogs" so I thought I'd hop on the bandwagon and start my own. This will not be updated daily but I'll try to post as often as time permits and I have something to say.

My intent here is to encourage discussion about programming practices and upcoming technologies. That being said, I'll post here and direct the subjects typically along the lines of something I'm working on. Occasionally, I'll post about an article I have read. Depending on what is going on, I may even post about something that is happening in my life.

Just for reference, I have been using the .NET Framework almost as long as it has been available. By no means do I claim to know every aspect of it. There are plenty of namespaces that I have not even begun to examine or use primarily because the applications I have developed have not needed the functionality provided therein.

My .NET language of choice is C#. I have not ventured very far into VB.NET though I typically have no problem reading it. The rationale for the language preference is partially based in syntax and partially based in capabilities.

For database technology, my area of expertise is SQL Server 2000. I have not worked with SQL Server 2005 nor have I read much about it yet but the little that I have read has gotten my attention.

Feedback on my posts is encouraged. I hope to be able to use this blog as a platform for not only contributing to the community but also to learn and grow from it.