Tip

The Object-Oriented Windows form


.NET Developer Tip
(Receive this column in your inbox,
click Edit your Profile to subscribe.)

The Object-Oriented Windows form
Chris Payne

If you haven't

    Requires Free Membership to View

started thinking of your forms as objects yet, now is a good time to start. Imagine the Windows Form on your screen as an actual window in your house. You can change the color of the window, the opacity (how transparent the window is), the type of knobs and locks, curtain dressing, type of glass, and on and on. You can do virtually anything you want to your window (assuming you have the necessary resources).

The same statement can be said about Windows Forms. You know from yesterday's lesson that you can change the caption and size of a form. You can also change the title bar, the way objects inside the form are arranged, the color, the opacity and visibility, the borders, the buttons, and so on...

Thus, it is helpful to think of Windows Forms as generic objects that can be manipulated and customized however you want. You can go to the .NET Class Library "store" and pick out a Form object, and then tailor it as you see fit.

Working with the Object Object

Object is the most generic class you can use in .NET. As such, it is used to represent any otherwise unknown object. For example, if you use the following statement to create a variable, CLR doesn't know what type to create it as, and just creates an Object:

dim MyObjectVariable

Because your variable is just an Object, you lose a lot of functionality that you would gain from declaring an explicit data type. For example, you can add an integer to an integer, but you cannot add Objects together; doing so would result in an error no matter your intentions. Therefore it's a good idea to always declare a specific type, rather than using Object for everything.

NOTE

By default, your applications must always declare a type for your variables to prevent misuse and increase performance. However, you can turn this safety feature off by disabling the Option Strict feature.

There are many functions you'll use in Windows Forms programming that create objects for you. For example, the ConfigurationSettings.GetConfig method retrieves configuration settings from a file. This function returns an Object data type, because it doesn't know specifically what you're going to do with the returned results. By returning an Object, you are free to transform the results to any data type you want by casting, a process that transforms one data type into another. In C#, you cast a variable with the following:

myDataType myVariable;  //declare variable of myDataType
myVariable = (myDataType) ConfigurationSettings.GetConfig ("some setting"); //retrieve settings and cast to myDataType

There are five key methods of the Object object: Equals, ReferenceEquals, GetHashCode, GetType, and ToString. These all come in handy, so let's cover them individually. Remember that every object inherits from Object, so these methods are available to every object you use.

The Equals method is both a static and non-static member. This means that you can call it from either a specific instance of an object, or from the Object type itself. For example, Listing 3.1 shows a snippet using both static and non-static versions of the Equals method.

Listing: Using the Equals Method

1: int intA;
2: int intB;
3: 
4: intA = 4;
5: intB = 5;
6: 
7: Console.WriteLine("{0}", intA.Equals(intB)); //non-static method
8: 
9: Console.WriteLine("{0}", Object.Equals(intA, intB)); //static method

Lines 7 and 9 will both print "False" to the command line because the intA and intB objects are not equal (intA is 4, and intB is 5). Line 7, however, calls the Equals method from an instance, while line 9 calls Equals from the Object class itself. There are many times you need to compare two objects, so this method will prove useful.

TIP

The Console.Writeline method prints a string to the command line. The first parameter is the string to be printed. A number in brackets means the method should refer to one of the additional supplied parameters: {0} means print the next parameter, {1} means print the parameter after that, and so on. You could also simply use the parameter in place of the numeric identifiers.
To use this method, you must compile your application as a regular executable file (use the /t:exe option when compiling).
The ReferenceEquals method is a static-only member that is similar to the Equals method. The difference is that ReferenceEquals compares two objects to see if they are the same instance, rather than the same value. This can be done because an instance in computer terms is defined by a location in memory. Therefore, two objects that point to the same memory location are the same instance. Two different memory locations can have the same value, but they are not the same instance. (Note that null -- or Nothing in VB.NET -- always equals the same instance as another null.) Take a look at [the listing below], which compares different variables.

Listing: Comparing References

1: object a = null;
2: object b = null;
3: object c = new Object();
4: 
5: Console.WriteLine(Object.ReferenceEquals(a, b));
6: Console.WriteLine(Object.ReferenceEquals(a, c));
7: a = c;
8: Console.WriteLine(Object.ReferenceEquals(a, c));

Line 5 returns true, because all null values equate to the same instance. Line 6 returns false because a and c are two different objects. Line 7 looks like it sets a and c to the same value, but when you do an assignment of one variable to another, you're actually setting the memory locations equal, and therefore, line 8 returns true.

NOTE

If you have previous programming experience, you'll know where the name ReferenceEquals comes from: this method compares the variables' memory locations (or references) rather than simply their values.

Most often, the Equals method suffices, but it is useful to have the ReferenceEquals method around as well.

The next three methods are all non-static. GetHashCode returns a hash code for your object. A hash code is a numeric representation of an object; it doesn't actually hold any meaning. Objects A and B may be different objects but generate the same hash code, for example, the number 7. However, you cannot reverse the process and go from the number 7 to an object. Thus, hashing is a one-way mechanism.

GetType, as the name implies, simply returns the specific data type of an object. This is very useful when you don't know what kind of data you're dealing with; for instance, when a function returns an unidentifiable object:

string a = "hi";
Console.WriteLine(a.GetType());

This snippet will return System.String, the data type of the variable a. Note that this method returns a type of data, rather than just the type's name. In other words, it returns a type, and not a string. This method is often used to compare data types. For example, using the GetConfig method discussed previously:

myType myVariable;
if (myVariable.GetType() != ConfigurationSettings.GetConfig ("my settings").GetType()) return false;

This code snippet tests whether the type returned by the GetConfig method (a Type object) is of the same type as myVariable. And in this case, it is not.

Finally, probably the most common method, ToString, returns a string representation of a variable's type. For example, the following code snippet would print "system.object" to the command line:

Object objA = new Object();
Console.WriteLine(objA.ToString());

Note that it does not print out an object's value, but the name of the type. Sometimes the ToString method is overridden for a particular class. The string data type, for instance, overrides ToString so that it prints out the actual value of the variable, rather than the name of the type. The following code prints out "hello world."

string strA = "hello world";
Console.WriteLine(strA.ToString());

To read the entire article from which this article comes, click over to InformIT. You have to register there, but that registration is free.

For More Information:

There are Comments. Add yours.

 
TIP: Want to include a code block in your comment? Use <pre> or <code> tags around the desired text. Ex: <code>insert code</code>

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy
Sort by: OldestNewest

Forgot Password?

No problem! Submit your e-mail address below. We'll send you an email containing your password.

Your password has been sent to:

Disclaimer: Our Tips Exchange is a forum for you to share technical advice and expertise with your peers and to learn from other enterprise IT professionals. TechTarget provides the infrastructure to facilitate this sharing of information. However, we cannot guarantee the accuracy or validity of the material submitted. You agree that your use of the Ask The Expert services and your reliance on any questions, answers, information or other materials received through this Web site is at your own risk.