Microsoft.ASP.Dot.NET.Programming.with.Visual.Basic.Dot.NET.Version.1002003.Step.By.Step [Electronic resources] نسخه متنی

اینجــــا یک کتابخانه دیجیتالی است

با بیش از 100000 منبع الکترونیکی رایگان به زبان فارسی ، عربی و انگلیسی

Microsoft.ASP.Dot.NET.Programming.with.Visual.Basic.Dot.NET.Version.1002003.Step.By.Step [Electronic resources] - نسخه متنی

G. Andrew Duthie

| نمايش فراداده ، افزودن یک نقد و بررسی
افزودن به کتابخانه شخصی
ارسال به دوستان
جستجو در متن کتاب
بیشتر
تنظیمات قلم

فونت

اندازه قلم

+ - پیش فرض

حالت نمایش

روز نیمروز شب
جستجو در لغت نامه
بیشتر
توضیحات
افزودن یادداشت جدید






Expressions, Variables, and Constants

Expressions, variables, and constants are some of the most basic building blocksof computer programs, and you’ll use them all extensively in your ASP.NET applications.


Expressions


Expressions are central to virtually all computer programs. Among other capabilities, expressions let you



Compare values to one another



Perform calculations



Manipulate text values



An expression can be as simple as the following:

1+1

An expression like this isn’t very useful by itself, however. Unlike people, who can easily recognize “one plus one” and fill in the blank (“equals two”), computers aren’t capable of that kind of leap of logic. In order for the expression to be useful, it needs to tell a computer not just to add one and one, but to store the result somewhere so that we can make use of it later (either by displaying it to the user or using it in another expression later). This is where variables come in.


Variables


At some point during the execution of most programs, you’ll need to store values of some sort, such as the results of comparisons or mathematical operations (as in the preceding example), or text input accepted from users. Simply put, variables are storage areas for data. This data can be numeric, text, or any one of a number of special data types.


Data Types


The data type of a variable defines the type of data that can be stored in it, as well as the format in which that data is stored (and the amount of memory that the system needs to allocate for the variable). Table 3-1 lists the data types supported by Visual Basic .NET and C#, as well as the Microsoft .NET Framework SDK types to which they map. The data types marked with an asterisk (*) don’t have a native representation, but you can still access these data types by using the appropriate System (or .NET Framework) type when declaring the variable.

The data type of a variable is determined at the time the variable is declared. This will be discussed further in the section entitled “Declaring Variables” later in the chapter.































































Table 3.1: Data Types

C# Data Type


Visual Basic Data Type


.NET Data Type


Size


bool


Boolean


System.Boolean


2 bytes


byte


Byte


System.Byte


1 byte


sbyte


*


System.SByte †


1 byte


char


Char


System.Char


2 bytes


Date


System.DateTime


8 bytes


decimal


Decimal


System.Decimal


16 bytes


double


Double


System.Double


8 bytes


int


Integer


System.Int32


4 bytes


uint


*


System.UInt32 †


4 bytes


long


Long


System.Int64


8 bytes


ulong


*


System.UInt64 †


8 bytes


object


Object


System.Object


4 bytes (plus the size of the object’s data)


short


Short


System.Int16


2 bytes


ushort


*


System.UInt16 †


2 bytes


float


Single


System.Single


4 bytes


string


String


System.String


From 0 to 2 billion Unicode characters


struct


User-Defined Type


System.ValueType (inherited)


Sum of membersizes






Important

ASP.NET contains both framework-specific data types and language-specific data types for specific .NET languages, such as Visual Basic .NET and C#. To take advantage of some of the multilanguage features of the .NET environment, you need to limit your use of data types to those supported by the Common Language Specification (CLS), a subset of the data types supported by the common language runtime (CLR). In the preceding table, data types marked with † are not CLS-compliant. Avoid using them in classes that you want to make available for use with other .NET languages. Data types marked with * do not have a language-specific representation, so if you want to use these types you need to use the .NET Framework type.



Value Types vs. Reference Types


In .NET development, there are two categories of data types: value types and reference types. Although understanding the distinction between these types isn’t absolutely necessary if you want to develop ASP.NET applications, it can help you to better understand how these data types operate and how to deal with error messages resulting from coding errors. (Not that those ever happen, right?)

Value types are data types that store their data directly as values in memory. They include all the numeric types (int32, short, single, and so on), structures (custom data types based on System.ValueType), and enumerations (custom types that represent a defined set of values), as well as boolean, char, and date types. Value types are accessed directly, as in the following example:

'VisualBasic.NETdeclarationforanint32
DimmyIntasInteger
'Expressiontoassignthevalue123directlytothevariable
myInt=123





Tip

The preceding code example uses comments to provide an additional explanation of what the code in the example is used for. Comments are lines (or portions of lines) of code that use a special character that tells the language compiler to ignore them when compiling the code. In Visual Basic .NET, the single quote character (') is used to precede a comment. With the exception of a single quote contained within double quotes (which represents a literal string), everything following a single quote on the same line is ignored by the compiler. This means that you can put comments on the same line as the code they refer to or on their own line, as in the preceding example. For comments that span more than one line, each line must be preceded with the comment character.

Using comments is a good habit to get into because comments make your code easier to read and understand. You should consider using comments even if you’re the only one who’ll ever see the code since comments are very useful when you have to revise code that you wrote months or years before, when it might no longer be clear why you wrote the code the way you did.


Reference types are data types that store a reference to another memory location that contains the data, which is usually based on a class, such as the String class in the .NET Framework. Reference types include Object (which acts as a replacement for Visual Basic’s Variant type, no longer supported in .NET), String, and all Arrays, as well as instances of custom classes. Reference types are accessed through members of the class that the type holds a reference to, as in the following example:

'Defineaclass
ClassmySampleClass
PublicmyIntAsInteger
EndClass
'Createaninstanceoftheclass
DimmyClassInstanceAsNewmySampleClass()
'Expressiontoassignthevalue123tomyClassInstancemembermyInt
myClassInstance.myInt=123


Declaring Variables


Before you can use variables in your programs, you need to declare them.Variable declaration is the process of specifying the characteristics of the variable (name, data type, lifetime, scope, and accessibility) so that the run-time system knows how much storage space to allocate for the variable, which actions to allow on the variable, and who can take those actions. A variable declaration takes the following form in Visual Basic .NET:

'DeclaresavariableoftypeInteger

DimxAsInteger





Tip

The preceding example uses x as the name of the variable. While this is perfectly acceptable as far as the language compilers are concerned, you should consider giving your variables more meaningful names, suchas FirstName (for a string variable holding a first name), LoopCount (for a numeric variable used in a looping structure), or Person (for a reference to a class representing data on a person). This naming convention makes it much easier to remember the purpose of a variable, and it will make your code much easier to maintain. You can find naming guidelines for use in .NET class libraries at http://msdn.microsoft.com/library/en-us/cpgenref/html/cpconnetframeworkdesignguidelines.asp and specifically for Visual Basic .NET at http://msdn.microsoft.com/library/en-us/vbcn7/html/vaconVBNamingRules.asp.


The preceding declaration specifies a variable of type Integer (which maps to the System.Int32 type). In this case, the variable, x, would be accessible only within the module, procedure, or block in which the declaration appeared. In addition to simple declarations like these, you can use the placement of the declarations, as well as Visual Basic .NET keywords, to modify the lifetime, scope, and accessibility of your variables.


Variable Lifetime


Lifetime refers to the span of time from when the variable is declared to when it is destroyed. The lifetime of a variable depends on where it is declared.

For example, the lifetime of a variable declared inside a procedure is limited to the execution of the procedure. Once the procedure has finished executing, the variable is destroyed and the memory it occupied is reclaimed. The following code illustrates a procedure-level declaration:

'VisualBasic.NETSubprocedure
SubHelloWorld()
'Declareprocedure-levelstringvariable
DimHelloStringAsString
HelloString="HelloWorld!"
'WriteHelloStringtobrowser
Response.Write(HelloString)
'LifetimeofHelloStringwillendafternextline
EndSub

When this procedure completes, the variable HelloString no longer exists. Its lifetime has ended. If HelloString had been declared outside the procedure, as shown in the following code example, its lifetime would have lasted until the instance of the class containing it was destroyed.

'Declaremodule-levelstringvariable
DimHelloStringAsString
'VisualBasic.NETSubprocedure
SubHelloWorld()
HelloString="HelloWorld!"
'WriteHelloStringtobrowser
Response.Write(HelloString)
'LifetimeofHelloStringwillnotendafternextline
EndSub








Naming Conventions and Case


The Visual Basic .NET documentation recommends that you use whole words when naming your variables. You should use mixed case, with the first letter of each word capitalized, as in HelloString. This is called Pascal case. This is one of many possible naming conventions you can use for variables and other elements in your programs. Naming conventions are simply agreed-upon standards for how elements will be named in a program. For instance, using an initial lowercase character and capitalizing the first character of each word is called Camel case. The particular naming convention you choose isn’t important, but you should choose one and use it consistently. Doing so will make it easier for you to maintain your code and will help others understand what your code is doing. Consistent use of a variable naming convention is especially important when several developers are working together on the same project.











You can extend the lifetime of a procedure-level variable through the use of the Visual Basic .NET Static keyword in place of the Dim keyword used earlier. (InC#, you would use the static modifier.) In the following example, MyInt is declared within the procedure, but because it’s declared as Static, its lifetime continues until the class or module containing the procedure has finished running:

'VisualBasic.NETSubprocedure
SubAddInt()
'DeclareastaticIntegervariable
StaticMyIntAsInteger
'Add5toMyInt
MyInt+=5
'WriteMyInttobrowser
Response.Write(MyInt.ToString())
'LifetimeofMyIntwillnotendafternextline
EndSub

Because MyInt is declared as Static, each call to AddInt() will result in MyInt being incremented by 5. If MyInt was instead declared using Dim, each call to AddInt() would result in MyInt being set to 5.


Scope


Scope refers to the region of code in which a variable can be accessed. The scope of a variable depends on where the variable is declared, and in Visual Basic .NET it can include the following levels.



Block level Variables declared within statement blocks such asIf… Then, For…Next , or Do… Loop. Although the scope of block-level variables is limited to the block in which they’re declared, their lifetime is that of the procedure in which the block appears.



Procedure level These variables are visible only within the procedure in which they’re declared.



Module level In modules, classes, or structures, any variable declared outside of a procedure is referred to as a module-level variable.



Namespace level Variables declared at module level, but given public accessibility (Public or Friend), are referred to as namespace-level variables. They’re available to any procedure in the same namespace that contains the module in which the variable is declared.





Note

The accessibility of namespace- and module-level variables is determined by any accessibility keywords used in their declaration. (See “Accessibility” later in this chapter.)











Namespaces


A namespace is a container used for scoping. Namespaces can contain classes, structures, enumerations, interfaces, and delegates. By using namespaces, you can have more than one class in a given program with the same name, as long as the classes reside in different namespaces. Using namespaces can help ensure that code created by multiple teams of developers can be combined to create larger systems without name collisions.

Namespaces are declared in Visual Basic .NET using the Namespace…End Namespace syntax, where these statements bracket the classes, structures, and so on to be contained within the namespace. C# uses the namespace {} syntax, where the classes and other types to be contained within the namespace are bracketed by the curly braces.

Namespaces can also be nested within other namespaces, forming a hierarchy. This structure allows you to combine classes into logical groupings, making it easier for those using your namespaces to find the classes they’re looking for.

Effective use of namespaces will make your application more memory-efficient and will make maintaining your code easier.











The important distinction between lifetime and scope is that a variable might be out of scope (that is, unavailable) without having reached the end of its lifetime. The preceding example of a Static variable that’s declared within a procedure is a good illustration of this distinction. In that example, the variable MyInt will continue to exist even after the procedure in which it’s declared has completed, but because it has procedure-level scope, it’s only accessible within the procedure. Here are some good programming practices to follow:



Limit your variables to the narrowest possible scope that will allow you to accomplish your objectives.



Avoid using the same name for variables of different scope within the same module, even where it is allowed. Using the same name in such situations can lead to confusion anderrors.



Since module-level and Static variables all continue to consume memory as long as the class or module is running, use them only when necessary.




Accessibility


The last important concept in variable declaration is accessibility. The accessibility of a variable determines whether it can be accessed from outside the module (or application) in which it’s declared. In Visual Basic .NET, accessibility is determined by declaring your variable with one the following keywords, instead of Dim.



Public Variables declared with the Public keyword are accessible from anywhere in the same module (or class) in which they’re declared, from the namespace containing that module, and from anyother applications that refer to the application in which they’re declared. They can be used only at the module or class level, or within Structures.



Frien Variables declared with the Friend keyword are accessible from anywhere in the same module (or class) in which they’re declared, as well as from the namespace containing that module.



Protected Variables declared with the Protected keyword are accessible only within the class in which they’re declared or within a class that inherits from that class. (See “Using Inheritance” later in this chapter.) The Protected keyword can be combined with the Friend keyword and can be used only to declare classmembers.



Private Variables declared with the Private keyword are accessible only from the module, class, or structure in which they’re declared. In classes or modules, declaring a variable with Dim or Private has the same effect on the variable’s accessibility, but Private makes your intentions more explicit. The Private keyword cannot be used within a procedure.







Note

In C#, all variables must be declared before they can be used. Failure to declare a variable will result in a compiler error. In Visual Basic .NET and some other languages, it’s possible (but not advisable) to use variables without first declaring them. Using variables that have not been explicitly declared is a major source of bugs in Visual Basic programs and should be avoided.

The Visual Basic Option Explicit statement (placed at the top of a module or class) requires that all variables in that module be explicitly declared.

'turnsOptionExpliciton
OptionExplicitOn'turnsOptionExplicitoffOptionExplicitOff

To further protect your code from inadvertent bugs, you can also use the new Option Strict statement. When Option Strict is on, conversions between data types that would result in data loss (also known as narrowing conversions, such as converting a Single containing the value 1.25 to an Integer, which would result in the Integer variable having the value 1) are disallowed, as are conversions between strings and numeric types.

'turnsOptionStricton
OptionStrictOn'turnsOptionStrictoffOptionStrictOff

You can also set Option Explicit and Option Strict in the project properties for the project, in which case they will apply to all classes in the project.

Following these guidelines can help reduce the number of bugs in your code, and more importantly, the time you spend tracking them down.

The Option Strict statement includes all of the restrictions of Option Explicit, so it is not necessary to use both.



Constants


Constants are similar to variables, except for one important detail: Once a constant has been declared and initialized, its value cannot be modified. Constants are very useful when you have a literal value that you want to refer to by name. For example, in a program that calculates shipping weights in pounds and ounces, you might want to create a constant to refer to the number of ounces in a pound:

ConstOuncesInAPoundAsInteger=16

Anywhere within your program (subject to the same scope, lifetime, and accessibility rules as variables) you can use the constant name OuncesInAPound instead of the literal value 16.

Constants are particularly handy in place of literal values used as the arguments to methods of components you might use. For example, in classic Microsoft ActiveX Data Objects (ADO), the data types of stored procedure parameters were represented by numeric values. Trying to remember all of those values would be unrealistic, so the developers of ADO also made it possible to use constants (adInteger, adVarChar, and so on) in place of the literal values.

In other words, constants let you substitute easy-to-remember names for difficult- to-remember literal values. This can make your code easier to write and maintain, since you can update the value in a single location (the constant initialization), rather than having to search your code for every instance of a literal value.


Enumerations


Many constants used with ASP.NET are actually created using enumerations. Using enumerations allows you to define a set of related constants and access them in a type-safe way. For instance, if you have a procedure that accepts numeric values, from 1 to 3, representing a color, it might look like this:

SubSetColor(ByValColorAsInteger)
IfColor=3Then
'Codetoapplycolorsetting3.
EndIf
EndSub

This method will, in fact, happily accept any integer value. To limit the possible values, you could declare an enumeration as follows:

EnumColorTypeAsInteger
Red=1
Green
Blue
EndEnum

By default the first element of an enumeration is equal to 0. In this example, since you want an enumeration that contains 1 through 3, you set the first value in the enumeration to 1, and then the subsequent values are each incremented byone. So, Green is 2 and Blue is 3. Now, rather than the previous procedure declaration, you could use the following:

SubSetColor(ByValColorAsColorType)
IfColor=ColorType.BlueThen
'Codetoapplythecolorsettingblue.
EndIf
EndSub

This procedure will require an instance of the ColorType enumeration to be passed as the parameter, ensuring that the value is a valid member of the enumeration, and thus that the value represents a valid color. The following is an example of calling SetColor with a ColorType enumeration member:

SetColor(ColorType.Blue)

/ 126