November 27, 2014
Hot Topics:

New JScript .NET Data Types

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

Understanding automatic type conversions

While JScript .NET encourages developers to declare variables and assign specific data types to them, JScript .NET remains backwards compatible with JScript and JavaScript. For example, you can successfully compile and run the second snippet of code shown in this article (with a minor modification), as shown below:

// save this as test01.js
// compile using the command: jsc test01.js
a = 1;
b = "1";
a += b; 
print (a); // prints 11 - the string "11"

If you have trouble compiling the application using jsc, the JScript .NET compiler, start a Visual Studio .NET Command Prompt and try again (from the Start menu, select: Start - Programs - Visual Studio .NET - Visual Studio .NET Tools - Visual Studio .NET Command Prompt).

What's happening in the above listing is exactly what happens when you execute the code in the second snippet in Internet Explorer or Windows Scripting Host: JScript converts the value of a into a String and concatenates the value of b to it. If you modify the listing by adding the following statement to the beginning of the listing, the program will still successfully compile and run:

var b : String;

The reason it works is that JScript .NET is using the same rules that JScript and JavaScript use to convert data types at run time. JScript .NET applies JScript's and JavaScript's type conversion rules only for variables that you don't declare or declare a type for. In addition, you'll run into problems when you start using language features like package and class, since they require you to declare all variables.

If you declare variable a as an int, the program will not compile. The JScript .NET compiler will complain about the types being mismatched ("Type mismatch" error) and will not produce an executable version of your program. This brings us to the next benefit of using variables: compile time checking.

Understanding compile time checking

As I described in the previous article, a compiler produces two outputs: a list of errors and warnings, and an executable program. JScript .NET is no different from other compilers: as it compiles your code, it keeps track of errors and warnings, and if it encounters any critical errors it will not produce an executable version of your code. This feature is useful a variety of scenarios, since it makes it easy to detect and locate common programming mistakes like assigning inappropriate values to variables.

Consider the following listing:

var a : sbyte;
a=200;

The code won't compile because the JScript .NET compiler knows that an sbyte type can manage values between -128 and +127, and assigning 200 to it is clearly an error. The JScript .NET compiler is able to clearly determine the value of a since it does not change in the above listing (there isn't any code that changes the value of a at runtime); as a result, the compiler generates a "Type mismatch" error and does not produce an executable version of the code.

Compile time checks can also ensure that you assign types that are compatible with each other. For example, consider the following listing:

var a : char; // range is 0 to 65,535
var b : byte; // range is 0 to 255 

a = b; // Ok

This is legal JScript .NET code since the byte data type's range falls within the char data type. This obviously wouldn't work if you attempt to assign a to b (since the range of a byte is smaller than a char data type).

When the compiler cannot definitively determine the value of a variable at compile time, the compiler produces an executable image and relies on runtime checks to detect errors.

Understanding data type constraints

Consider the following listing:

import System;

var a : sbyte;

try 
{
  a = 100;
  a += 100;
}
catch ( e : Exception) 
{
  print( e.Message );
  // prints: "Exception of type System.OverflowException was thrown"
}

The code declares an sbyte variable, assigns the value 100 to it, and attempts to add 100 to it using the += operator. The above code successfully compiles since the JScript .NET compiler cannot establish what the value of a will be unless it executes the code. Since the compiler's job is not to execute code, it creates an executable image, allowing you to execute the program. The code encapsulates the attempt to add 100 to a within a try/catch block since the program must rely on run time checks to detect assignment errors. When the code executes, the .NET Class Library throws an Overflow exception because the result, 200, exceeds the capacity of the sbyte data type. The .NET Class Library throws the exception because the JScript .NET sbyte type transparently maps to the Common Type System System.Sbyte data type, as shown in Table 1.

The Common Type System enforces data type constraints at runtime using exceptions. In fact, the.NET Class Library makes extensive use of exceptions to report errors or exceptional conditions. As a result, you should become exception-aware since seemingly simple operations can cause your applications to unexpectedly terminate. A future article in this series is dedicated to errors, exceptions and becoming exception-aware.

Creating your own data types

There are scenarios when isolated variables are too simple to express your designs. For example, suppose that you're creating an application that collects information about visitors to your site. The information that your site collects includes a visitor's first and last name, and their email address. This information is useful throughout your application and simple string variables quickly become awkward. A solution to this problem would be to encapsulate all of a visitor's details within an object, making it easier to manage and easier to add methods that, for example, validate the user's email address's format.

JScript and JavaScript provide some support for creating your own objects, as shown in the following listing:

function Person()
{
  this.firstName = "";
  this.lastName = "";
  this.email = "";
  this.create=Person_Create;
}

function Person_Create(first,last,emailAddress)
{
  this.firstName=first;
  this.lastName=last;
  this.email=emailAddress;
  this.isValidEmail=Person_isValidEmail;
  Person.prototype.toString=Person_toString;
}
    
function Person_toString()
{
  return this.lastName + ", " + this.firstName + " : " +
             this.email + "\nEmail address " + 
    (this.isValidEmail() ? "is" : "is not") +  " valid";
}

var  aPerson;
aPerson = new Person;
aPerson.create("Essam","Ahmed","essam@designs2solutions.com");
alert(aPerson);

The listing defines a Person object and associates a create, isValidEmail (not shown - refer to the sample code), and toString method with it. This code appears in a sample page, which you can experiment with (use your borwser's "view source" feature to review the source code). The sample page is shown in Figure 2 and the output is in Figure 3.

Figure 2 - Creating a custom data type using JScript in Internet Explorer

Figure 3 - Output of custom data type page

While the solution seems to work, it is messy since the Person object really doesn't exist as a first class object. The Person object seems to exist because it takes advantage of JScript's late binding features - there's no way of binding the Person_Create function to the Person type, nor is there any means of controlling access to a Person's variables.





Page 2 of 3



Comment and Contribute

 


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

 

 


Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.

Sitemap | Contact Us

Rocket Fuel