Properties

   

Now that the Ball objects are alive and ready to use, you can begin to tell ASP.NET what they look like. Looking at an object class and object instances from the previous example, there is something you should understand.

When you create an instance from a class, the class builds the object with default properties. These properties may simply have a default value that is empty. A ball has a color attribute because the class defines it. However, it may not have a value yet. Or maybe the Ball class creates a ball with a default color property of white. This is determined within the class; you'll learn more later when we investigate the Ball class in detail.

Setting Properties

As we've discussed before, the Ball has properties things that describe what the object is like. It has a color, shape, and texture property. When you create an instance of an object, you can now set and retrieve the value of a property for a specific instance.

Visual Basic .NET
objMyBall.Color = "White"  objYourBall.Color = "Blue" 
C#
objMyBall.Color = "White";  objYourBall.Color = "Blue"; 

Notice that the statements are virtually the same with the exception of the semicolon at the end of each line in the C# version. This is how you set the value of property in ASP.NET.

Caution

If you choose C# as your language for programming in ASP.NET, you must remember that it is very picky (as I stated in Chapter 1 when showing that C# would misbehave because it is case sensitive). Another thing to be aware of is that C# loves semicolons. It needs semicolons to terminate a line of code. This has advantages and disadvantages. In Visual Basic .NET there is an assumption that every line in the document is equal to a line of code and if you want to continue your code on the next line you must indicate this with an underscore. So Visual Basic .NET terminates a line of code by default unless otherwise told. C#, on the other hand, continues a line of code unless it is terminated with a semicolon.


Properties can be set in other ways, too, as you'll see in the next section on methods. Properties can have values assigned to them in three ways:

  • When an instance of an object is created, the class (template) has a default value, even if it's nothing.

  • You can set it by writing objectname.propertyname = value .

  • They can be set by an object's methods.

There isn't any limitation on how many times you can set these properties within a page or application. It's there for you to manipulate and you can feel free to go hog wild and change these values as much or as little as is necessary to suit what you are trying to do in your application.

Retrieve Properties

Now that we've set these properties , you need to know how to retrieve them. Just as writing Objectname.PropertyName sets the Ball's Color property, you also retrieve its value this way. Following are two different examples of situations that involve getting the value of the Color properties.

Visual Basic .NET
dim strMyBallColor,strYourBallColor as String  strMyBallColor = objMyBall.Color  strYourBallColor = objYourBall.Color  OurLabel.Text = objMyBall.Color  OurLabel.Text = objYourBall.Color 
C#
String strMyBallColor,strYourBallColor;  strMyBallColor = objMyBall.Color;  strYourBallColor = objYourBall.Color;  OurLabel.Text = objMyBall.Color;  OurLabel.Text = objYourBall.Color; 

In this example, you first create two variables and then set their values to the value of the objects' color properties. Next, you set the text of an ASP.NET Label server control to the value of the property.

So we can say that properties are the attributes that describe the condition of an object. This can be what an object looks like, but as you'll see as we start to explore the balls methods, it also can include a new property that can't be paralleled to its "appearance" but deals with its condition.

Imagine being in Hawaii (I wish!!!!). The sun is beating down on you and the things around you. You decide that it's time to go to the beach and enjoy some of the beautiful Hawaiian surf. You step off the boardwalk onto the sand and begin to hop around like a kangaroo. Why, you ask? Because of this:

 Sand.Temperature = "Hot" 

The Sand.Temperature property is "Hot", as you can feel. It doesn't describe an attribute of what sand looks like, but what type of state it is in. Properties describe objects and have the potential of describing any type of attribute. They outline what something is like.

Methods

Methods are simply ways for us to tell an object what to do. They can be simple things such as rolling the ball, which actually could be considered complex, but for this example we will keep it simple. Methods can also be very complex, as well. For instance, imagine you have a car object and want to call its StartEngine() method. This method must put many things into motion before you can alter the state of the car object from not having a running motor to having a running motor.

Executing a method or calling a method is not a whole lot more difficult than referring to a property. You simply refer to the ObjectName.MethodName(). The parentheses are required when calling a method, so be sure to include them.

Let's take a look at the Roll() method of the ball object and see how it affects the state of the ball. The Roll() method does just that: It rolls the ball. But you need a way to see that the ball is rolling. I am going to introduce you to an additional property of the ball now. It is the Motion property. This property identifies whether the ball is in motion or not. It has a default value of 'still' set by the Ball class. This code is run in the Page_Load() event and the text attribute of the label is set to the values of the ball at different times. So, now let's roll the ball.

Visual Basic .NET ball_roll_method_vb.aspx
dim objMyBall as New Ball()  OurLabel.Text = "<u>Before Roll Method</u><br>"  OurLabel.Text += "MyBall: " & objMyBall.Motion & "<br><br>"  objMyBall.Roll()  OurLabel.Text += "<u>After Roll Method</u><br>"  OurLabel.Text += "MyBall: " & objMyBall.Motion 
C# ball_roll_method_cs.aspx
Ball objMyBall = new Ball();  OurLabel.Text += "<u>Before Roll Method</u><br>";  OurLabel.Text += "MyBall: " + objMyBall.Motion + "<br><br>";  objMyBall.Roll();  OurLabel.Text += "<u>After Roll Method</u><br>";  OurLabel.Text += "MyBall: " + objMyBall.Motion; 

Now you see how to call a method. Tough? I don't think so! Figure 2.2 shows how this code will appear in a browser.

Figure 2.2. Notice that the ball is still before the roll() method is called and rolling after it is called.
graphics/02fig02.gif

You can see that the ball initially is still, which is its default property set by the class (Remember Template) when objMyBall was created. After you call the Roll() method, you can see that the ball is rolling. Keep in mind that this is over-simplified. Under this situation the ball would roll infinitely without some other intervention, but ignore this problem for this example so we can move on.

You can even pass directives to your methods if they allow for it. Imagine that the Roll() method allowed you to adjust how hard you roll the ball. Maybe you can determine whether you want to roll the ball softly, moderately, or hard. You can pass these values in the parentheses and affect how hard the ball rolls. You can even pass directives to your methods if they allow for it. You'll learn more about this later after you learn how to create methods.

Creating a Class

Now we're gonna take some time to put together all this stuff you've learned on the last few pages about objects, properties, and methods. We are going to build a real living object in ASP.NET, and you will see how easy it is to come up with a concept and turn it into an object.

Remember, you don't have to build your own objects to use ASP.NET; there are hundreds of pre-built ones that cover tons of typical web application situations. We are going to build this object as a demonstration of how to build one if you want to. The greatest part is YOU CAN!!! This is part of the freedom that ASP.NET gives to you when you program web applications in this language.

Inside the Class

Let's take a look at the full-fledged Ball class with properties of Color and Motion and a method of Roll() and dissect it into its different parts so you can easily understand it. Don't be overwhelmed by the big block of code that follows. Think of it as a sizzling, juicy steak that is being placed in front of you. It would be difficult to enjoy if you tried to swallow it whole (and I'd be hard pressed to save you from choking considering you're only reading a book and I'm not there with you). But if you cut it up into bite-sized pieces you can chew it, savor it, and finally swallow the whole steak.

Visual Basic .NET
Public Class Ball      Private _Color as String      Private _Motion as String      Public Sub New()          _Motion = "Still"      End Sub      Public Property Color as String          Get              Return _Color          End Get          Set              _Color = value          End Set      End Property      Public ReadOnly Property Motion as String          Get              Return _Motion          End Get      End Property      Public Sub Roll()          _Motion="Rolling"      End Sub  End Class 
C#
public class Ball {      private string _Color;      private string _Motion;       public Ball(){          _Motion = "Still";      }      public string Color{          get {              return _Color;          }          set {              _Color = value;          }      }      public string  Motion {          get {              return _Motion;          }      }      public void Roll() {              _Motion="Rolling";      }  } 

The first thing I think you'll notice is that the C# language is definitely more compact or concise maybe less wordy is a way to say it. Visual Basic .NET does tend to be wordier to accomplish the same thing in a side-by-side comparison with C#, but there are tradeoffs to writing less characters of code in C#. Keep in mind that C# is very picky. Did I mention C# is picky? As you can see, Visual Basic .NET, in references to keywords such as return, is indifferent to case sensitivity. Not so in C#. So the tradeoff is that to program in C# you might have to type fewer characters, but you must pay special attention to what those characters are.

Class Delimiter

Now let's get out our steak sauce, a knife, and a fork, and carve up some of that delicious steak. The first thing you need to do when building a class is to define it.

Visual Basic .NET
Public Class Ball 
C#
public class Ball { 

This line lets the .NET Framework know that you're going to build an object. It works in this manner in its simplest form: accessibility level, class keyword, and class name.

Let's look at accessibility levels first. We are going to touch on only the two contained in this example Public and Private but there are many possible accessibility levels that help you to control how a class or its members (Properties and Methods) are available for use within your applications. The Public and Private accessibility levels can be described as follows:

  • Public. A class or a class member that is available anywhere the class is present.

  • Private. A class or a class member that is available only within that class that it is part of.

So if you look at the code above, you can see that this class is available for creating ball objects.

The only noticeable difference between the Visual Basic .NET code and the C# code is that the C# code has a curly bracket ({) at the end of the line. This is C#'s opening delimiter for a block of code. If you are familiar with JavaScript, this will look familiar because it uses the same character. Both Visual Basic .NET and C# require that you delimit the beginning and end of encapsulated code blocks such as classes, properties, and methods, to mention a few. This is similar to all the two-part tags in HTML, such as the <html></html> tags or <table></table> tags. You must provide a start delimiter and an end delimiter to the block of code.

In Visual Basic .NET, all keywords that need delimiting inherently are the opening delimiter for itself but must be closed with the keyword's proper matching end delimiter:

 Public Class Ball      //Class Code Here  End Class 

C# must have an opening curly bracket and must also have a partner closing curly bracket as well.

 Public Class Ball{      //Class Code Here  } 

So now we've covered the first and last lines of the class and we've also talked about how many members of ASP.NET including classes, properties, and members need to be delimited to work properly. Now it's time to move on to our next juicy morsel.

Class Private Variables

Next it's time to create the variables for the properties. These aren't the properties that you access, but the variables that contain them inside the class. Notice the private access level on these variables. As mentioned earlier, this means they are available to only the class that they are part of. This means you can't directly get the value of _Color or _Motion. This just holds the current value of the objects _Color and _Motion. You get these values through calling the properties.

Visual Basic .NET
Private _Color as String  Private _Motion as String 
C#
private string _Color;  private string _Motion; 

Tip

The underscore that begins the property name in _Color and _Motion is a pretty standard way of naming variables that are private inside a class and are used to store property values with matching names. So _Color is holding the value of the color property and _Motion is holding the value of the motion property in this class. This makes it easy to identify these variables in your code as property value containers.


Let's move on.

Class Constructor

The following is the class constructor code. It is the block of code that is executed during a call to the New() method when you're creating a new instance of the Ball object. It is not a required part of code when you write a class. You need it only if you need to do something when you create each instance of your object.

Visual Basic .NET
Public Sub New()      _Motion = "Still"  End Sub 
C#
public Ball(){      _Motion = "Still";  } 

Follow this…an "object" has a class in the eyes of the .NET Framework and it has a template as well. It is called the Object class. All objects in the .NET Framework get their base structure from the Object class and thus have all of its properties and methods. In that Object class there is a New() constructor by default, so even if you don't insert it into your class code, you can still use the New() constructor because your object will have gotten the constructor from the base Object class.

You need to set a default value of "Still" for the motion property of the ball, so you need the constructor code. You can basically do anything within the constructor code. For instance, you could have called a Roll() method from the constructor if you wanted to be able to create a rolling ball right off the bat.

Class Properties

The next thing to study is the properties.

Visual Basic .NET
Public Property Color as String      Get          Return _Color      End Get      Set          _Color = value      End Set  End Property  Public ReadOnly Property Motion as String      Get          Return _Motion      End Get  End Property 
C#
public string Color{      get {          return _Color;      }      set {          _Color = value;      }  }  public string  Motion {      get {          return _Motion;      }  } 

These are our two properties, Color and Motion, being created in the class. These are two different types of properties. The Color property is something you want to retrieve and be able to set a value for, as well. So this property has a Get function, for retrieving the value of the parameter, and a Set function, for setting the value of the parameter. Pretty self-explanatory! If you want a parameter value, you Get it; if you want to assign it, you Set it.

In the Get function, all you're doing is returning the value of the private variable that matches the parameter in the case of both the Color property and the Motion property. Ask for the value as follows:

Visual Basic .NET
dim strMyBallColor as String  strMyBallColor = objMyBall.Color 
C#
String strMyBallColor;  strMyBallColor = objMyBall.Color; 

You are calling the Get portion of the property and receiving the value of the private variable in return.

If you look at the Color property, you can see an additional function called Set. The Set function is also pretty simple to understand. When you want to change the value of a property, you use code like this, as mentioned before:

Visual Basic .NET
objMyBall.Color = "White" 
C#
objMyBall.Color = "White"; 

With this type of code, you're calling the Set function. Notice that the Motion property doesn't have a Set function. This is because you don't want to give people the ability to set the value of a ball's motion: We're trying to programmatically mirror reality here, and a ball doesn't just start moving. You need to restrict the ability to set a property's value by making it a read-only property. Again the differences in Visual Basic .NET and C# are apparent here. We must tell Visual Basic .NET that a property is read-only by placing "ReadOnly" in the line where you create the property.

C#, on the other hand, figures that if there's no Set property, it must be read only. This makes sense, and again leads to having to type less code than in Visual Basic .NET to accomplish the same thing.

Class Methods

Now on to the method. You want to be able to roll the ball, but the Motion property is read-only so we can't get our ball to move. This example of a method is over-simplified to help give you some basic understanding of how a method is created and what it can do. If we took time to really investigate what happens to a ball when you roll it, how gravity, friction, wind, and other things affect it, we could be here forever writing a gazillion lines of code to accommodate what the ball's Motion property would look like when the ball is rolled. I say all this to point out that it's possible to do so. You could programmatically create these scenarios and affect the ball with these things, but we are only investigating what methods are, not how complex they can get. This is kinda like the whole "fishing/feeding" metaphor, which goes, "Give a man a fish and you feed him for a day; teach him how to fish and you feed him for a lifetime," or something like that. I'm trying to teach you how to fish so that tomorrow you can create your own methods and understand how to do it successfully.

Visual Basic .NET
Public Sub Roll()      _Motion="Rolling"  End Sub 
C#
public void Roll() {          _Motion="Rolling";  } 

When you call the Roll method, you can see it simply sets the private variable _Motion to Rolling. Next time you check the ball's Motion property, it will return a value of "Rolling".

As I mentioned, you can do very complex things in methods and with properties, too, for that matter. In the following, the Roll() method has been adapted to allow you to dictate how hard the ball rolls.

Visual Basic .NET
Public Sub Roll(Strength as String)      If _Motion = "Still" then          If Strength = "Soft" then _Motion = "Rolling Softly"          If Strength = "Medium" then _Motion = "Rolling Medium"          If Strength = "Hard" then _Motion = "Rolling Hard"      End if  End Sub 
C#
public void Roll(string strength) {      if ( _Motion == "Still"){          if (strength == "Soft") _Motion = "Rolling Softly";          if (strength == "Medium")  _Motion = "Rolling Medium";          if (strength == "Hard") _Motion = "Rolling Hard";      }  } 

Now let's say you've edited your page to look like the following. Remember that this code block is running in the page's Page_Load() event and is setting the text attribute of a Label object:

Visual Basic .NET ball_roll_method_strength_vb.aspx
dim objMyBall as New Ball()  dim objYourBall as New Ball()  dim objNewRidersBall as New Ball()  OurLabel.Text += "<u>Before Roll Method</u><br>"  OurLabel.Text += "MyBall: " & objMyBall.Motion & "<br>"  OurLabel.Text += "YourBall: " & objYourBall.Motion & "<br>"  OurLabel.Text += "NewRidersBall: " & objNewRidersBall.Motion & "<br><br>"  objMyBall.Roll("Soft")  objYourBall.Roll("Medium")  objNewRidersBall.Roll("Hard")  OurLabel.Text += "<u>After Roll Method</u><br>"  OurLabel.Text += "MyBall: " & objMyBall.Motion & "<br>"  OurLabel.Text += "YourBall: " & objYourBall.Motion & "<br>"  OurLabel.Text += "NewRidersBall: " & objNewRidersBall.Motion & "<br><br>" 
C# ball_roll_method_strength_cs.aspx
Ball objMyBall = new Ball();  Ball objYourBall = new Ball();  Ball objNewRidersBall = new Ball();  OurLabel.Text += "<u>Before Roll Method</u><br>";  OurLabel.Text += "MyBall: " + objMyBall.Motion + "<br>";  OurLabel.Text += "YourBall: " + objYourBall.Motion + "<br>";  OurLabel.Text += "NewRidersBall: " + objNewRidersBall.Motion + "<br><br>";  objMyBall.Roll("Soft");  objYourBall.Roll("Medium");  objNewRidersBall.Roll("Hard");  OurLabel.Text += "<u>After Roll Method</u><br>";  OurLabel.Text += "MyBall: " + objMyBall.Motion + "<br>";  OurLabel.Text += "YourBall: " + objYourBall.Motion + "<br>";  OurLabel.Text += "NewRidersBall: " + objNewRidersBall.Motion + "<br><br>"; 

This can be seen in Figure 2.3.

Figure 2.3. You can have your method perform multiple tasks, including changing the strength at which roll the ball rolls.
graphics/02fig03.gif

As you can see in Figure 2.3, passing a parameter to the method affects how hard the ball rolls. The method is structured to check how hard you want to roll the ball and then change the Motion property.

One more thing that I would like to touch on is what programmers call "overloading methods," and what Boy scouts call "being prepared." Overloading a method is nothing more than providing a bunch of different potential ways to use a method.

Let's take the Roll() method, for instance. You may want to give people two ways to describe how hard to roll the ball. You might want to leave the ability to pass in "Soft, Medium, or Hard" to the method, but also want to be able to pass in 1, 2, or 3 to affect this method the same way "Soft, Medium, and Hard" do. You would create another Roll() method to accommodate this different situation.

Visual Basic .NET
Public Sub Roll(Strength as String)      If _Motion = "Still" then          If Strength = "Soft" then _Motion = "Rolling Softly"          If Strength = "Medium" then _Motion = "Rolling Medium"          If Strength = "Hard" then _Motion = "Rolling Hard"      End if  End Sub  Public Sub Roll(Strength as Integer)      If _Motion = "Still" then          If Strength = 1 then _Motion = "Rolling Softly"          If Strength = 2 then _Motion = "Rolling Medium"          If Strength = 3 then _Motion = "Rolling Hard"      End if  End Sub 
C#
public void Roll(string strength) {     if ( _Motion == "Still"){         if (strength == "Soft") _Motion = "Rolling Softly";          if (strength == "Medium")  _Motion = "Rolling Medium";          if (strength == "Hard") _Motion = "Rolling Hard";      }  }  public void Roll(int strength) {      if ( _Motion == "Still"){          if (strength == 1) _Motion = "Rolling Softly";          if (strength == 2)  _Motion = "Rolling Medium";          if (strength == 3) _Motion = "Rolling Hard";      }  } 

Again, this is an oversimplified example and methods can contain more than one variable, but it demonstrates what it means to overload a method and "be prepared!"

Warning

Each overloaded method must have a unique footprint or "signature." A method's signature is a combination of the method's name and its parameter types. In the previous example, the first overloaded method has a signature of Roll(string), and the second has a signature of Roll(int). These create two unique signatures so that .NET can know which version of the method you are trying to address. You can't overload a method with two matching signatures no matter how many parameters it has.


With the class dissected, you now have a clearer understanding of what objects are made of and how they work. It's not as complicated as you may have thought, and I'm sure you are feeling a bit more comfortable with objects now.

As I've said before, the .NET Framework provides a boatload of pre-made objects so you won't have to go through this process of creating classes and their properties and methods. A vast majority of typical web function is already covered in classes that come standard with .NET.

"Okay Peter, so a 'boatload' of objects is available. What are they and what they do?" Not as big a deal as you think, and later we'll go through many of them in more detail. The bigger question that needs to be answered is where they are. The answer to this question really provides a platform to answer what they are.

(Fade to black and white)…We will now unveil another one of the .NET mysteries as we enter the "Namespace" zone!!


   
Top


ASP. NET for Web Designers
ASP.NET for Web Designers
ISBN: 073571262X
EAN: 2147483647
Year: 2005
Pages: 94
Authors: Peter Ladka

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net