Thursday, July 29, 2010
Tuesday, April 15, 2008
Visual Basic2005
What Is Visual Basic .NET?
Visual Basic .NET is a programming language designed to create applications that work with Microsoft's .NET Framework. The .NET platform, in turn, addresses many of the limitations of "classic" COM, Microsoft's Component Object Model, which provided one approach toward application and component interoperability. These limitations included type incompatibilities when calling COM components, versioning difficulties when developing and installing new versions of COM components (known as "DLL hell"), and the need for developers to write a certain amount of code (mostly in C++) to handle the COM "plumbing." In contrast to pre-.NET VB, with its reliance on COM, Visual Basic as a .NET language offers a number of new features and advantages. Let's take a look at some of these.
Object Orientation
With the release of Version 4, Visual Basic added support for classes and class modules and, in the process, became an object-oriented programming (OOP) language. Yet the debate persists about whether pre-.NET Visual Basic was a "true" object-oriented language, or whether it only supported limited features of object orientation. Detractors point out that Visual Basic did not support inheritance of a base class's functionality, only of its interface or signature. While Visual Basic still had a solid base of object-oriented features, purists emphasized the very real limitations in VB's OOP implementation.
While the object-oriented character of previous versions of VB may be in doubt, there is no question that .NET is an object-oriented programming platform. In fact, even if Visual Basic .NET is used to write what appears to be procedural code, it is object-oriented "under the hood."
A Common Type System
Traditionally, one of the problems of calling routines written in other languages from Visual Basic, or of calling Visual Basic routines from other languages, is that such inter-language calls presuppose a common type system . This is the case when calling Win32 API functions from Visual Basic, but it also applies to attempts to call methods in a VB COM component from other languages, or to call methods in a non-VB COM component from VB.
For instance, until the addition of the AddressOf operator, which obtained the memory address of a procedure, there was no way to indicate a "callback" function, a requirement of many Win32 API enumeration functions. As another example, it is expected that members of structures passed to Win32 API functions be aligned or padded in specific ways, something that VB programmers had great difficulty accomplishing.
Problems of type compatibility tended to occur most often when scripted applications were used to call and pass arguments to COM components. An excellent example is the attempt to pass an array from a script written in JScript to a COM component. COM sees JScript arrays as a string of comma-delimited values rather than as a COM-compatible array (called a SafeArray). This, and similar problems, caused no end of type-related headaches.
The .NET platform removes these difficulties by providing a Common Type System (CTS). Ultimately, all data types are either classes or structures defined by or inherited from the .NET Base Class Library. Having this Common Type System means that .NET components are truly language-independent, and that a .NET component written in one language will be seamlessly interoperable with .NET components written in any other .NET language. The problem of incompatible types simply disappears.
Access to System Services: The Framework Class Library
Ever since VB added support for calls to the Windows and Win32 APIs, many Visual Basic programmers have come to regard API programming as a kind of black art. Not only was there a confusing and seemingly limitless array of functions that might be called, but the craft of passing parameters to routines and receiving their return values was equally mysterious. Moreover, with the growing emphasis on object-oriented programming, the Win32 API, with its procedural approach to programming, seemed more and more archaic.
A Common Runtime Environment
Although VB had traditionally shielded the developer from many of the intricacies of Windows as an operating system, or of COM as a method for interoperability, some knowledge of how the system worked was still essential to maintain problem-free applications. Programs and components written with one tool did not always work well with code from other tools. Working with the Win32 API often required a more advanced introduction to Windows development concepts than the typical novice Visual Basic programmer was ready to handle. Not all COM components were created equal either. It was quite easy to generate a COM component in C++ that could not be used in VB, and vice versa. Such incompatibilities kept many a programmer from developing and deploying components in their language of choice.
Under .NET, many problems like these are eliminated because of the .NET platform's Common Language Runtime (CLR). The CLR, as its name clearly implies, provides a variety of common services to applications and processes running under the .NET platform, regardless of the language in which they were originally written. These services include memory management and garbage collection. They also include a unified system of exception handling and the ability to use the same set of debugging tools on all code, regardless of the original .NET language used. A common set of data types ensures that data and classes interact easily between the various .NET languages.
Naming Conventions
Although naming conventions are not strictly part of a programming language, most Visual Basic developers had adopted some form of the prefix-based "Hungarian" naming system developed many years ago by Charles Simonyi. With the release of .NET, Microsoft now recommends a new naming system. This system dispenses with the endless lists of type-specific prefixes and instead assigns names to elements (classes, functions, local variables, global constants, etc.) based solely on what they are. So a variable that holds a customer name is no longer sCustName (with "s" for "string) or even lpszCustName (don't ask); you now simply use customerName.
The new conventions include two types of naming: "Pascal Casing" and "Camel Casing." All names are mixed case, with a capital letter appearing at the start of each new word within the name. Pascal Casing also capitalizes the first letter, and it is used for all public class members and global elements. Camel Casing includes a lowercase initial letter, and it is used for private members, procedure arguments, and local variables. There are some additional details to the rules, and some people differ on when to use Pascal Casing and when to use Camel Casing.
Common Language Runtime
The Common Language Runtime (CLR) is an environment that manages code execution and provides application-development services. It provides all of the common features required by all .NET-enabled languages. Visual Basic and other .NET languages are simply wrappers that expose the CLR's functionality. Because the CLR provides all of the core functionality for all .NET languages, components written in different .NET languages can interact with each other immediately, with no language-specific conflicts. Even data types are shared among .NET languages through the CLR's Common Type System (CTS). While data types may have different names in Visual Basic than they do in C#, they will all be based on underlying CLR data types.
The Common Language Specification (CLS) defines the minimal set of .NET features that must be implemented by a .NET-compliant compiler. Components developed to be CLS-compliant may be limited in their ability to interact with applications and components that use a wider range of .NET features.
The output of a .NET compiler includes metadata, which is information that describes the objects that are part of the generated application or library. The metadata describes the following:
-
Data types and their dependencies
-
Objects and their members
-
References to required components
-
Information (including versioning information) about components and resources that were used to build the application or library
Metadata is used by the CLR to support functionality such as:
-
Manage memory allocations
-
Locate and load class instances
-
Resolve method invocations
-
Generate native code
-
Make sure that the application has the correct versions of necessary components and resources
-
Enforce security
By including metadata in a compiled software component, that component becomes "self-describing." This tells the CLR everything it needs to prepare and execute a .NET application, and to allow it to interact with other .NET components.
Managed Code
Code created within the CLR environment is called managed code . Applications and libraries created using non-.NET tools, such as VB 6 applications, and COM and ActiveX components, are not managed code. You can still use unmanaged components in your .NET applications, but they must be referenced through special "interop" conduits to prevent the unmanaged code from having any detrimental impact on the managed side of the application.
Having a central manager of all things .NET like the CLR makes possible some nice centralized functionality. One such feature in .NET is the garbage collection system, which automatically disposes of all variables and data objects when an application is finished with them, reclaiming every byte and releasing all references to the related memory.
Managed execution is the process of running your .NET applications in the context of the CLR, although this process officially starts when writing your first line of .NET source code. There are three simple steps to managed execution .
-
Write code using one or more .NET compilers. Some compilers (like the C++ compiler for .NET) can generate code that is unmanaged or that falls outside the official CLS. Such code cannot easily interact with components from other .NET languages, so avoid it in mixed-language applications.
-
Compile the code. The compiler translates source code to Intermediate Language code (IL), also called Microsoft Intermediate Language (MSIL) or Common Intermediate Language (CIL), and generates the necessary metadata for the application.
-
Run the code. When .NET code is executed, the IL is compiled into CPU-specific native code by a Just In Time (JIT) compiler. The resulting application is run within the context of the CLR.
One benefit of running applications within the CLR-managed environment is that data within the application is kept safe. The CLR keeps errant code and malformed data from interfering with the rest of memory, either in your application or elsewhere in the system.
Namespaces
The notion of a namespace plays a fundamental role in the .NET Framework. In general, a namespace is a logical grouping of types (classes and similar constructs) for the purposes of identification and navigation. There are so many classes and features in .NET that there are bound to be name conflicts. And since third-party libraries can be integrated into the class space just like the Microsoft-supplied libraries, namespaces keep everything neat and orderly.
Imagine that, in a certain business, there is an executive named John Smith, a secretary named John Smith, and a custodian named John Smith. In this case, the name John Smith is ambiguous. When the paymaster stands on a table and calls out the names of people to receive their paychecks, the executive John Smith won't be happy if he rushes to the table when custodian John Smith's paycheck is in the paymaster's hand.
To resolve the naming ambiguity, the business can define three namespaces: Executive, Secretarial, and Custodial. Now the three individuals can be unambiguously referred to by their fully qualified names:
-
Executive.John Smith
-
Secretarial.John Smith
-
Custodial.John Smith
Namespaces in .NET look a lot like these references to John Smith. They are simply names used to group and organize all of the .NET classes into a hierarchy. Namespaces can be nested. Consider the following three possible namespaces.
-
America Namespace
-
America.Washington Namespace
-
America.Washington.Seattle Namespace
Each of these namespaces can include classes (and other types) and additional namespaces. And the same class name can appear in multiple namespaces, even in nested namespaces.
-
America.Demographics Class
-
America.Washington.Demographics Class
-
America.Washington.Seattle.Demographics Class
-
America.Montana.Demographics Class
The .NET Framework Class Library (FCL) consists of several thousand classes and other types (such as interfaces, structures, and enumerations) that are divided into about 200 namespaces. All classes considered to be the "core" language-neutral classes of .NET appear in the System namespace, or in one of the nested namespaces within System. The namespaces supplied with .NET provide basic system services, such as:
-
Basic and advanced data types and exception handling (the System namespace)
-
Data access (the System.Data namespace)
-
User-interface elements for standard Windows applications (the System.Windows.Forms namespace)
-
User-interface elements for web applications (the System.Web.UI namespace)
Many Visual Basic language features are implemented within the classes of the Microsoft.VisualBasic namespace. (The C# and J# languages have corresponding namespaces.)
All classes (and other types) exist in a namespace, even the classes of your application. By default, your project's namespace is at the top of the hierarchy (next to System) and is named after your project's name. You can alter this by using the Namespace statement at the beginning of a code file, or by defining a different project namespace through the Project Properties.
Types and Objects
Pretty much everything in a .NET application is contained in a type. Types include:
-
Classes, which are basically collections of data values, and the related code that manages that data. Usually a class has both data and code, but a particular class might just have either data or code. In Visual Basic, a Module is a variation of a class.
-
Interfaces, which are class "skeletons." Interfaces define the basic structure of a class but without the actual implementation. They are useful for defining a common layout of features to be shared by many related classes.
-
Delegates, which .NET uses to implement its event-driven infrastructure.
-
Enumerations, which are collections of named numeric elements.
-
Value types and reference types. Normally, when you create an object (an in-memory instance of a class), that object sits in memory somewhere, and your object variable contains the memory location of the object block. (It's like a pointer, for those familiar with the C language parlance.) These are reference types. The .NET type system also supports value types. A value type variable stores the actual data value instead of a memory address to the true location of the data.
-
Other similar things. You can subdivide the type system forever, but everything is eventually called a type.
From the Visual Basic point of view, all types are really classes. Of course, all data objects are instances of classes, but even your source codeeven your Sub Main routineis part of a class, and it must be part of a class to be part of a .NET application.
The root of the type hierarchy is the System.Object class. All new classes you design eventually tie back to the System.Object class. This class provides some basic functionality required of all classes and provides a convenient way to generically identify any object in your application.
Assemblies
An assembly is a single .NET executable (EXE file) or library (DLL file). Since these file types existed before .NET was invented, why bother to give them a special name? Well, it's not just the type of file; it's what is in the file that counts. (By the way, a .NET purist will insist that a single assembly can be split into multiple files. While this is true, it rarely happens, especially since it can't be done from within the Visual Studio development environment.)
An assembly is a unit of deployment; that is, it's a file that can be deployed on a user's system. .NET applications are made up of one or more assemblies , all working together for a common goal. Inside of an assembly, you find the following:
-
The executable code of your application. Generally you will have a single primary EXE assembly, plus optional DLL assemblies.
-
Embedded data, such as resources (graphics, strings, etc.).
-
.NET-specific security permissions required for the assembly.
-
The types (classes and so on) used in the assembly, including public classes that can be accessed by other assemblies (applications).
-
Listings of the external types and references needed by the assembly, including references to other assemblies. These references also indicate the specific or minimum version number expected for those external components.
-
Version information for the assembly. Assemblies include a four-part version number (major, minor, revision, and build, as in "2.1.0.25"), and this version number determines how the assembly interacts with other assemblies and components. .NET allows you to install different versions of an assembly on a single machine and have specific versions accessed by other applications. For instance, you may have Versions 1.0 and 2.0 of a spellchecking component installed on a workstation, one for an old word processor (that requires Version 1.0) and one for a newer email system (that uses Version 2.0). Both versions can reside on the same system without conflict. In fact, both versions can be actively running at the same time, a feature known as side-by-side execution.
Much of this information is stored in the assembly's metadata, which was discussed earlier. As a unit, this metadata is known as the assembly's manifest. Although this is somewhat repetitive, the manifest contains at least the following information.
-
The name of the assembly
-
Version information for the assembly
-
Security information for the assembly
-
A list of all files that are part of the assembly
-
Type reference information for the types specified in the assembly
-
A list of other assemblies that are referenced by the assembly
-
Custom information, such as a user-friendly assembly title, description, company name, copyright information, and product information
If your application is split up into multiple assemblies, each assembly is only loaded into memory as it is needed. One interesting side effect of this as-needed access is that you can update an assembly file while the application that uses the file is still running. If you replace a DLL, the application will start using the new DLL the next time it has fully discontinued use of the old DLL. Of course, this generally happens when you exit and restart the application, but in some complex applications, you could perform a live update of an assembly.
The Framework Class Library
Although .NET itself is very powerful and very cool, it doesn't provide much in the way of specific functionality. The .NET Framework provides a generic system for application development, but it's really all plumbing. It's not that different from the old-style C++ or Pascal compilers. If you want to sort a list of strings in reverse order by length, draw a line on the screen, interact with a database, or send a data packet across the Internet, you still have to write all of that functionality yourself. Or do you?
Fortunately, you don't have to do it all by yourself. The .NET Framework includes a library of prewritten features that provide a lot of the functionality you really wanted, but that you didn't want to write yourself. This library uses a layered approach. At the bottom of the library is the Base Class Library (BCL), which defines the central and common features that every .NET language will use, such as:
-
Implementation of all core data types
-
Data structures, such as stacks, queues, and collections
-
Diagnostic and tracking features
-
Basic input and output with various sources, such as files and serial ports
On top of this foundation you find the FCL, which is pretty much everything else that Microsoft thought programmers (including programmers designing the .NET system) would find useful. Among the many library classes are:
-
XML manipulation tools
-
ADO.NET, a collection of generic and platform-specific database interaction components
-
GDI+, the core drawing system for on-screen and printed output
-
Windows Forms, a package for creating desktop applications
-
ASP.NET, a web-based programming system
The .NET Framework and Visual Basic
Visual Basic, as a .NET language, uses all of the core features of the Common Language Runtime, the Common Type System, namespaces, assemblies, types, and all other .NET elements, packaging them up in a nice, neat programming system.
To write a Visual Basic application, you create classes that implement your desired functionality and data manipulation features. All application data is stored in memory using the Common Type System data types that Visual Basic uses for its own basic data types. The application manipulates this data using many of the prewritten classes in the Framework Class Library. All of this code gets organized into namespaces of your choosing and is compiled into one or more assemblies. Your application is now ready to deploy and run.
Principles of Object-Oriented Programming
Object-oriented programming is a software development architecture that uses the objecta "black box" of data and related functionalityas its focus. These objects are built on four main facets of OOP design: abstraction, encapsulation, inheritance, and polymorphism. This section introduces each of these concepts and also the notion of an interface as the means of interaction with the contents of an object's black box.
Objects and Classes
An object is a software-based collection of data elements and related procedures that act on those data elements. Obviously, objects are the central theme of "object-oriented" programming. In Visual Basic and other similar OOP languages, a class is the source code design of an object. An object is an in-memory instance of a class in a running program. Multiple object instances based on a single class can exist in memory at the same time.
Although the terms "class" and "object" have distinct meanings, the terms are used somewhat interchangeably in this chapter, at least in those cases where the distinction is not necessarily important.
Abstraction
An abstraction is a view of an entity that includes only those aspects that are relevant for a particular situation. It takes something from the real worldan employee, a book, a chart of accounts, a galaxy, a grain of sandand breaks it down into individual elements that can be managed with software. Consider a software component that provides services for tracking an employee's information. The first step in designing such a component is to identify the items or features that would be managed by the component. Some of these items may be:
-
Employee full name
-
Employee home address
-
Company ID for the employee
-
Current salary
-
Length of employment
-
Features to adjust the salary based on a rule
This list includes not only basic data values, or properties , but also common actions to be taken on the data, or methods . Properties of the class, such as the employee's full name, are sometimes called fields, and they may have limits on the type or range of data allowed. Methods may require additional information (such as a table of salary adjustment rules for the salary adjustment feature) to work properly. These actions are sometimes referred to as operations or behaviors. Together, the properties and methods are known as members of the abstraction.
The properties and methods of a class are relevant to that class. Although the Employee class could have included properties for IQ or the number of hairs on the employee's head, these data values have no relevance to the purpose of the class. Even though they are part of each employee, they provide no value to the class and are therefore excluded.
In short, the true employee has been abstractedthe class includes only those properties and methods of employees that are relevant to the needs of the class. Once the abstraction is complete, the properties and methods can be built into a software component
Encapsulation
Encapsulation is the process of converting an abstraction into a usable software componentthe black boxand exposing to the public only those portions of the abstraction that are absolutely necessary. The complete logic needed to manage each public property or method is fully contained ("encapsulated") inside the black box.
Encapsulation serves three useful purposes:
-
It permits the protection of these properties and methods from any outside tampering.
-
It allows the inclusion of validation code to help catch errors in the use of the public interface. For instance, the encapsulation can be programmed to prevent a negative number from being used for an employee's salary.
-
It frees the user from having to know (or worry about) the details of how the properties and methods are implemented.
High-level programming languages already perform some encapsulation to simplify the work required by the programmer. For instance, the SByte data type, introduced in Visual Basic 2005, is an 8-bit integer data type that supports a range of numbers from -128 to 127. But how exactly does it record those 128 negative numbers? If you are familiar with binary representation, you know that each bit of the integer number represents a power of 2: the right-most bit (bit 0) represents 20, the bit just to the left of that (bit 1) represents 21, and so on up to the left-most bit (bit 7), which represents 27. Setting each of these bits results in a different number. For instance, the binary number 00100110 sets bits 1, 2, and 5, and the sum of 21, 22, and 25 is 38 (decimal). In unsigned data, the binary number 11111111 equals 255 decimal. But that's all the bits. How do you get a negative number?
Visual Basic uses a system named two's-complement representation to handle negative numbers. Basically, any time the leftmost bit is set to 1, the number is negative. Then there are various rules used to interpret the remaining bits, depending on whether the leftmost bit is set or not.
Do you want to know those rules? Do you really need to know those rule, or how negative values are managed at all? The great answer is: no! In most programming, you don't have to worry about how Visual Basic stores negative numbers at the binary level. Who cares? You only need access to negative numbers, not to the complex rules about how they are processed in the computer. Visual Basic wraps up all of this functionality for you automatically in the SByte data type. This is the essence of encapsulation: just the right amount of visible functionality, all of the messy details hidden from view.
Moreover, encapsulation protects programmers from making errors. For instance, if every programmer had to do the negating by setting each bit manually and following all of the various and sundry rules, some important step would be forgotten. The encapsulated data type takes care of this automatically.
Encapsulation has yet another important feature. Any code written using the exposed interface of the SByte data type remains valid, even if the internal workings of the SByte data type are changed for some reason. If Microsoft decided to have the SByte data type use one's complement representation (another method for managing negative numbers), it wouldn't matter to programs that used SByte, as long as the interface to the data type did not change.
Inheritance
Inheritance makes it possible for OOP code to build classes that extend or restrict features in other existing classes, without the need to fully rewrite the original class. For instance, a class of Pet may have generic data fields such as Name, Age, and Color. This single class could be extended into other, more specific classes through inheritance . A class named Dog that is derived from Pet would automatically include the Name, Age, and Color members, but it may add additional canine-specific members such as Breed and a ShedsHair flag. In this situation, the Dog class inherits from the Pet class.
Inheritance used in this manner certainly reduces duplication of code, since the derived class does not have to rewrite the code for the existing base class's members. But inheritance also makes interactions between these objects easier, since an object of type Dog is also a true object of type Pet. Objects of a derived class are also objects of the base class, and they can be used in code as if they were actually members of the base class. (The reverse is not true; objects of type Pet are not necessarily objects of type Dog).
Some languages allow a class to inherit from multiple base classes at the same time. Visual Basic does not support this feature.
Interfaces
The public members of an object are known as its interface (or public interface). Usually, an object has a single public interface, since its class was designed with a single purpose in mind. But sometimes it is useful for a class to have multiple interfaces . For instance, along with the Pet class, consider another class called House. These two classes have some common aspects and tasks that apply to both, one of which is a cleaning strategy. While you could add distinct CleanNow, CleanserName, and CleaningTimeRequired members to each class, it would be more convenient to have a separate interface, called the Cleaning interface, that could then be applied to both Pet and House. Then your code could call the cleaning-related members on any object that implemented the Cleaning interface.
Interfaces are simply templates of desired functionality. To make these templates a functional reality, they must be implemented through a class. Implementing is a little different from inheriting. With inheritance, the new class receives the existing functionality of the base class; the new class doesn't have to reinvent this functionality. When implementing an interface, the new class is responsible for providing all of the functionality of the interface.
While Visual Basic classes cannot inherit from multiple base classes, a single class can implement multiple interfaces at the same time.
Polymorphism
The term polymorphism means having or passing through many different forms. The Dog class, derived from the Pet class, automatically receives the prewritten members of the Pet class. However, if one or more of these members needs to be extended in a special way to meet the needs of the new derived class (Dog), special Dog-specific versions of those members can be added to the Dog class. Any Dog object that calls these methods will use the Dog-specific versions; any general Pet object will use the default Pet-specific versions. If your code is currently treating a Dog object as a more generic Pet object, it will still use the Dog-specific versions, since the object is still a Dog.
Sound confusing? Welcome to polymorphism. Fortunately, the Visual Basic compiler figures out all of these relationships for you; you just need to write your code to enable the class-specific actions you require.
Overloading
Sometimes it is useful to have more than one way of performing the same action in a single class. For instance, if your Dog class has a TakeForWalk action, you might require several ways of taking this action to mimic real-world actions. For instance, you might want to call TakeForWalk with a time duration ("30 minutes") for a generic time-based walk, or call it with instructions for a specific path-based exercise plan. You would need one version of this action that takes a number (time-based) and one that takes a path plan (path-based), perhaps sent as a string.
When a class includes multiple versions of the same member that differ by their argument signatures (that is, by the parameters and return values of those members), that is overloading . This allows the member to take an action, but with different types of input data. Overloading most often occurs with actions taken on the object's data. The ability to provide differing sets of supporting data to an action can greatly expand the functionality of a class.
New in 2005. The original .NET release of Visual Basic did not include operator overloading . This form of overloading allows you to provide custom meanings to the standard language operator symbols, such as the + (addition) and <> (not equal to) operators.
Class Member Accessibility
Generally, the members of a class constitute that class's public interface. But some members may exist only for the internal use of the class instance itself. Each member of a class includes an access modifier. These special keywords indicate just how visible a particular member is to code outside of the class.1. Public :
Public members are accessible to any code that accesses an instance of the class or structure, or that has access to the module containing the member. If a class has a public member, and an instance of that class is accessed from a separate project, application, or component, the public member is fully accessible to that external code.
2.Protected:
Protected members are accessible within the confines of a class and can be used in any code derived from that class, but they cannot be accessed outside of the class. Protected members only apply to classes; they are not available to structures or modules.
3.Friend:
Friend members are accessible anywhere within the assembly, but no further. Instances of a class with a friend member consumed outside of the assembly hide the member from that external code. Friend members can be used in classes, structures, and modules.
4.Protected Friend:Using Protected and Friend together grants a member all the benefits of both; such members are accessible within the class and all derived classes, and within the assembly, but not outside of it. Protected Friend members can be used in classes, but not in structures or modules.
5.Private:
Private members are accessible anywhere within a class, structure, or module, but not outside. They are also hidden from the custom members of derived classes.
A class itself also has an access modifier, one of Public, Friend, or Private. Public classes can be accessed by another assembly that uses your class' assembly; Friend classes are accessible throughout your assembly, but not outside of it; and Private classes are only accessible within their "declaration context." Generally, Private is similar to Friend, but nested classes can be limited to use only within their parent class by using the Private keyword.Field Members
Variables, constants, and enumerations declared inside of a class, but outside of any class member procedure, are field members. (Enumerations can also be declared outside of classes altogether.) They are simple to declare and use, as done in the Person class earlier.
Private fullName As String
Private currentAge As Short
Public Const MaxAge As Short = 120
Private field members are often used in tandem with member property procedures to provide logic-controlled access to a data field in the class.
Public field members are available through instances of your class.
Dim onePerson As New Person
MsgBox("Maximum allowed age is " & onePerson.MaxAge & ".")
Property Members
Consider the following simple class.
Public Class AnotherPerson
Public Name As String
Public Age As Short
End Class
This class includes some of the functionality of the Person class defined earlier. However, the Age property has some problems. Because it is a simple public field, any instance of the class can have its Age field set to any Short value, whether 25, 87, 3349, or -23. Some of these ages are certainly invalid. How do you keep the user from setting the Age field to an invalid value?
While you could add specialized function members to set and retrieve the age, .NET includes properties that provide a more elegant solution. Within the class, properties look just like specialized functions; to the user of a class, they look like fields. (When a Visual Basic application is compiled, properties actually become method members.) The Person class defined earlier includes a more protected Age property.
Private currentAge As Short
...and later...
Public Property Age() As Short
Get
Return currentAge
End Get
Set(ByVal value As Short)
If (value <> MaxAge) Then
Throw New System.ArgumentException( _
"Age ranges from 0 to " & MAX_AGE & ".", "Age")
Else
currentAge = value
End If
End Set
End Property
The property procedure includes two distinct property accessors, one for setting the hidden tandem value (the Set procedure) and one for retrieving the current value (the Get procedure). You can create a read-only property by supplying only the Get component and adding the ReadOnly keyword to the property definition.
Public ReadOnly Property Age() As ShortThe WriteOnly keyword allows you to similarly define a property with only a Set component.
Get
Return currentAge
End Get
End Property
New in 2005. The 2005 release of Visual Basic allows you to specify different access levels (such as Public and Friend) to the Get and Set accessors.
MyBase, MyClass, and Me
When working with derived classes, there are times when references to a member may be somewhat ambiguous; a member name may exist in both the derived class and the base class. Visual Basic provides special keywords to help alleviate this ambiguity.
The MyBase keyword provides a reference to the base class from within a derived class. If you want to call a member of the base class from within a derived class, you can use the syntax:
MyBase.MemberName
This will resolve any ambiguity if the derived class also has a member of the same name. The MyBase keyword can also be used to create an instance of the base class through its constructor:
MyBase.New(...)
The MyBase keyword cannot be used to access Private members of the base class, as they are inaccessible from derived classes.
If a class is derived from a chain of base and derived classes, MyBase looks first to the closet "parent" class in the chain for a matching member (including a matching signature). If a match is not found, VB continues up the chain until the root class, which is always System.Object.
The keywords Me and MyClass both provide a reference to the local class (the class in which the current code resides), but they exhibit slight differences. Consider a class named BaseClass and another derived from it, named DerivedClass.
Public Class BaseClass
Public Overridable Function WhereAmI() As String
Return "Base"
End Function
Public Sub ShowLocation()
MsgBox(Me.WhereAmI())
MsgBox(MyClass.WhereAmI())
End Sub
End Class
Public Class DerivedClass
Inherits BaseClass
Public Overrides Function WhereAmI() As String
Return "Derived"
End Function
End Class
Now consider the following code that uses these classes:
Dim firstTry As New BaseClass
Dim secondTry As New DerivedClass
Dim useAsBase As BaseClass
useAsBase = firstTry
useAsBase.ShowLocation() ' --> Shows "Base", "Base"
useAsBase = secondTry
useAsBase.ShowLocation() ' --> Shows "Derived", "Base"
The first call to ShowLocation is made using a variable of type BaseClass that refers to an object of type BaseClass. In this case, both of the calls:
Me.WhereAmI()
MyClass.WhereAmI()
return the same value, because they both call WhereAmI in BaseClass.
However, in the second case, the variable of type BaseClass holds a reference to an object of DerivedClass. In this case, Me refers to an object of type DerivedClass (the secondTry reference), whereas MyClass still refers to the base class BaseClass (the useAsBase reference). When using the Me keyword, the actual object as originally instantiated is used; when using MyClass, the class of the variable that is used to make the method call becomes the controlling class.
Shadowing and Overloading MembersVisual Basic provides a few additional features that let you provide even more control over which members are used in your base and derived classes.
Shadowing
Shadowing is similar to overriding, but with some very important differences. Consider two classes, BaseClass and DerivedClass:
Public Class BaseClass
Public simpleField As Integer = 1
Public Overridable Sub TestOverride()
MsgBox("BaseClass:TestOverride")
End Sub
Public Sub TestShadow()
MsgBox("BaseClass:TestShadow")
End Sub
End Class
Public Class DerivedClass
Inherits BaseClass
Public Shadows simpleField As Integer = 2
Public Overrides Sub TestOverride()
MsgBox("DerivedClass:TestOverride")
End Sub
Public Shadows Sub TestShadow()
MsgBox("DerivedClass:TestShadow")
End Sub
End Class
BaseClass has two methods, TestOverride (with the Overridable keyword) and TestShadow. DerivedClass also defines methods with the same names; in this case, TestOverride includes the Overrides keyword, and TestShadow uses the Shadows keyword. Both fields also have a related public Integer field.
The following code tests the derived class:
Dim inUse As DerivedClass = New DerivedClass
inUse.TestOverride()
inUse.TestShadow()
MsgBox("Field = " & inUse.simpleField)
Because the object reference inUse is to an object of DerivedClass, the calls to the TestOverride and TestShadow methods, as well as to the public variable simpleField, all refer to code in DerivedClass; the output messages are as expected:
DerivedClass:TestOverride
DerivedClass:TestShadow
Field = 2
The test of the classes working together, though, is a little more interesting:
Dim inUse As BaseClass = New DerivedClass
inUse.TestOverride()
inUse.TestShadow()
MsgBox("Field = " & inUse.simpleField)
In this case, a variable of type BaseClass refers to an object of type DerivedClass. The output this time is:
DerivedClass:TestOverride
BaseClass:TestShadow
Field = 1
When interacting with base and shadowed members, the type of variable used to reference the members is the deciding factor. In the sample, even though the actual object was of type DerivedClass, the fact that the variable was of type BaseClass caused VB to use the BaseClass version of shadowed features.
Class fields, such as simpleField, can only be shadowed; they cannot be overridden.
One other difference between shadowing and overriding is that a shadow element need not be the same type of element as its base class partner. For instance, the following code is valid.
Public Class BaseClass
Public TheShadowKnows As Integer
End Class
Public Class DerivedClass
Inherits BaseClass
Public Shadows Sub TheShadowKnows()
MsgBox("This code lacks clarity!")
End Sub
End Class
Shadowing only considers the name of the member, not its type or signature. While allowing members of different types to shadow each other seems like a hazardous practice, it actually has its use. In Visual Basic, your code can include a global variable and a local variable of the same name, but of different data types. This ability is possible because the local variable is shadowing its global namesake. In such a case, references to the variable name in the local procedure always refer to the local variable, not the global variable of the same name. This process is known as shadowing by scope.
Overloading
Overloading refers to an item being used in more than one way. Generally, overloading occurs when a class includes multiple methods with the same name but with different signatures. For instance, the Abs function in the System.Math class includes several versions, but each uses different source and return data types.
Overloads Public Shared Function Abs(Decimal) As Decimal
Overloads Public Shared Function Abs(Double) As Double
Overloads Public Shared Function Abs(Int16) As Int16
Overloads Public Shared Function Abs(Int32) As Int32
Overloads Public Shared Function Abs(Int64) As Int64
Overloads Public Shared Function Abs(SByte) As SByte
Overloads Public Shared Function Abs(Single) As Single
Each entry includes the Overloads keyword, which tells VB that this function is overloaded. You can create your own overloaded methods. Consider a function that retrieves a current account balance. The account could be identified either by the customer's account number or driver's license number. The method that retrieves the balance might be defined with two different signatures.
Overloads Function GetBalance(accountNumber As Long) As Decimal
Overloads Function GetBalance(licenseNumber As String) As Decimal
When calling GetBalance, VB decides which version to use based on whether the method is passed a string or a long integer value.
New in 2005. The 2005 release of Visual Basic introduced operator overloading to the language. This feature allows a class to define functionality for the standard VB operators, such as the addition operator (+).
Sardarji Jokes
In India after Every 10 sec a women gives birth to a kid.
A Sardar stands up and says: we must find and stop her !!
Angry Sardar: "Give me 20 cr or else return my 20 Rs back.!
A sardar was drawing money from ATM, the sardar behind him in the line said, "Ha! Ha! Haaa! I've seen ur password. Its 4 asterisks (****). "
The first sardar replies, "Ha! Ha! Haaa! U R wrong, Its 1258"
A teacher told all students in a class to write an essay on a cricket match. All were busy writing except one Sardarji.
He wrote "DUE TO RAIN, NO MATCH!"
Prince Charles & Sardarji were having dinner.
Prince said, "Pass the wine you divine".
Sardar thinks "how poetic"
Sardar says, "pass the custard you bastard".
Wednesday, October 24, 2007
Home based internet jobs free to join & Earn Money
This web site is quite rewarding.It gives you ownership to sign up, invite
friends to join and use the internet normally.So click on the following
and join.
E-processor:
Join the new E-processor account,get $100 as bonus in your account and
get$10 for each referral .Please read the user agreement and terms
before signing up.To sign up click in the following link
http://e2epay.com/?manisunil
http://10dollarswonder.com/?manisunil
Here is a free opportunity to earn good income.There is absolutely no
fee and it is completely free. To join,click the following links