July 31, 2014
Hot Topics:
RSS RSS feed Download our iPhone app

New JScript .NET Data Types

  • January 7, 2002
  • By Essam Ahmed
  • Send Email »
  • More Articles »

Creating a custom data type using JScript .NET

JScript .NET addresses the above issues by allowing you to create your own data types using the class keyword. Consider the following code:

class Person
{
  public var firstName : String;
  public var lastName : String;
  private var emailAddress : String;
  // rest of class follows later in this article...

The listing defines a new person class with three member variables, just as the HTML page did in the previous example. The differences here are that each of the variables is bound to a specific type (String), and two of the three variables are public while one is private. public variables are just like regular variables - you can directly access and modify them. A private variable, in contrast, is not accessible to any code that resides outside of the class that defines the variable. The class in this example makes the emailAddress variable private since it controls access to it through special functions, called accessors. Accessor functions behave like variables but are actually functions that reside within a class, allowing developers a high degree of control over what actions other code can take on a class's variables.

The emailAddress variable is important since its contents must conform to a specific format; as a result, the class restricts access to it through functions that validate the format of the variable's content, as shown in the following listing:

// This function verifies the format of the email
// address on assignment
function set eMail(theAddress:String)
{
  emailAddress=theAddress;
  if(!this.isEmailValid)
    throw(new Exception("Invalid Email address format"));
}
   
// This function does not attempt to verify
// the format of the email address since it 
// simply returns the current value
function get eMail() : String 
{
  return emailAddress;
}

// This is a read-only class property (since
// only the get function has been defined) that
// returns true if the current email address is
// valid. This function is used in one of  the class's
// constructors and in the set eMail function.
function get isEmailValid() : Boolean
{
  var emailReg = "^[\\w-_\.]*[\\w-_\.]\@[\\w]\.+[\\w]+[\\w]$";
  var regex = new RegExp(emailReg);

  if (!regex.test(this.emailAddress)) 
  {
    emailAddress="";
    return false;
  
  }
  return true;
}

The listing demonstrates three accessor functions: set and get eMail and get isEmailValid. The comments in the listing provide details on the role of each function. The class verifies the email address's format using a regular expression that returns true for email addresses like tom@somedomain.tld, and essam.ahmed@my.domain.tld.

The class makes it easy to create new Person objects since it has two constructors. A constructor is analogous to the Person_Create function in the previous example: a constructor usually sets a class's initial state. The Person class has two constructors: a default constructor that initializes the class to an empty state, and a constructor that allows developers to create a Person initialized with a first and last name, and email address. The listing that follows demonstrates how to create both types of constructors:

// Default constructor
function Person()
{
  firstName=new String("");
  lastName=new String("");
  emailAddress=new String("");
}

// Constructor that initializes the Person based on
// names and email address
function Person(fName:String,lName:String,eMail:String)
{
  firstName=new String(fName);
  lastName=new String(lName);
  emailAddress=new String();
  emailAddress=eMail;
}

The sample Windows Forms application demonstrates how to use the Person class. A form similar to the one shown in Figure 4 appears when you start the application; the form looks very similar to the one in Figure 2.

Figure 4 - Windows Forms application that demonstrates how to use custom data types in JScript .NET

When you click on the Ok button, the application creates a new instance of the Person class using the following code:

var aPerson : Person;
aPerson = new Person(firstName.Text,lastName.Text,emailAddress.Text);

Each parameter that the Person constructor receives is based on the values that appear in the form - the Text property of each is similar to the HTML input element's value property.

The class allows developers to check the validity of the email address through the isEmailValid property (the get isEmailValid accessor function). There are cases when it is more appropriate to check the validity of the email address when the Person object initializes, as opposed to requiring that developers check the value of a class's property. The sample code also demonstrates how to validate the email address in the Person class constructor - the constructor reports an invalid email address using an exception. Although it is possible to throw exceptions from a constructor, it is generally not a good practice to follow and I provide it here for demonstration only. Use the directions that follow at the end of this section to build compile the application to report email validation exceptions when the Person object is created.

Regardless of what the state of the email address is, if you're using the application's default build, the application pops up a message box that echoes the values in the fields and an assessment of the email address's validity, as shown in Figure 5.

Figure 5 - Output of the sample Windows Forms application

The advantages that a JScript .NET class provides over a JScript object are many. The include:

  • The ability to specify what code can access member variables and functions through the public, protected, and private keywords
  • The ability to directly associate member functions with a specific, user-defined data type
  • A high degree of control over what other code can do with your class and its members
  • A high degree of encapsulation, offering the potential for better reuse across applications, potentially reducing the effort you spend on creating new applications.

Directions for downloading and building the sample application

These directions assume that the systems you use these directions on have version Beta 2 of the .NET Framework installed.

  1. Download the sample using this link
  2. Extract the contents of the ZIP file into a new folder
  3. Start a Visual Studio .NET Command Prompt as described earlier in this article and type the command buildPerson to compile the sample code. If the sample compiles successfully, you'll see a form on the screen that asks you to fill in a name and email address. If the sample does not compile successfully ensure that you can execute jsc, the JScript .NET compiler, from the command prompt.

Compile the alternate version of the application, described in the article, using the command:

buildPerson alt

When you run the application, change the value of the email address field to an invalid email address format and click on the Ok button. You should see an error about the email address being invalid - refer to the sample code for details.

Note that there seems to be a bug in the version of the .NET Framework I have installed on my system that inconsistently reports an email address as valid when it is actually not valid. If this happens on your system, change the value of the email address field and try again - it usually works after one or two tries (even if you remove a single character each try).

Summary

This article described the new JScript .NET data types, how they map to Common Type System data types, and how to use data types to perform compile time and run time checks to assist in your debugging efforts and improve the quality of your code. This article also demonstrated how to create your own data types using JScript .NET in the context of comparing the process with JScript. The next article in this series goes into more detail about the class statement in addition to the const, enum, package and import statements.


Essam Ahmed is the author of "JScript .NET Programming" (ISBN 0764548689, Published by Hungry Minds September 2001), many articles (including some at CodeGuru.com) and book reviews (also available at CodeGuru.com). Contact Essam at essam@designs2solutions.com, or at his Web site

# # #





Page 3 of 3



Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Sitemap | Contact Us

Rocket Fuel