IntroductionWelcome| 00:00 |
(music playing)
| | 00:04 |
My name is David Gassner, and this is
| | 00:06 |
Visual Basic Essential Training.
After installing Visual Studio Express
| | 00:10 |
for Windows desktop, I'll show you how to
create a variety of Visual Basic projects
| | 00:14 |
using both Windows forms and Windows
Presentation Foundation.
| | 00:19 |
Then I'll look at the language's
fundamental building blocks including
| | 00:23 |
variables and data types focusing first
on the elementary data types such as
| | 00:28 |
numbers, strings and dates.
I'll then show you how to package
| | 00:32 |
reusable code in functions and
subroutines.
| | 00:35 |
The last part of the course describes the
object-oriented nature of Visual Basic
| | 00:40 |
and shows you how to create custom
classes that have instance fields,
| | 00:44 |
properties and shared members.
Visual Basic can be used to create all
| | 00:48 |
sorts of applications for the web,
desktop, and portable devices.
| | 00:52 |
I hope that this course helps you get
started building your applications for
| | 00:57 |
Microsoft development platforms.
| | 00:59 |
| | Collapse this transcript |
| What you need to know| 00:00 |
This course Visual Basic Essential
Training is designed to teach the most
| | 00:04 |
important parts of the Visual Basic
programming language.
| | 00:08 |
It starts with Visual Basic .Net, a
version of the language that was released
| | 00:13 |
in 2002 with the .Net framework.
And continues through the most recent
| | 00:18 |
version of the language.
As of the time of this recording, Visual
| | 00:22 |
Basic 2012, also known as VB 11.0.
You can use this version of Visual Basic
| | 00:29 |
in a number of different platforms to
build many different types of applications.
| | 00:34 |
For example, you can build desk
applications with the Windows forms or
| | 00:38 |
Windows presentation foundation
frameworks.
| | 00:42 |
You can build Windows store apps for
Windows 8 and Windows RT, Windows phone
| | 00:47 |
apps, web applications with ASP.NET and
web-based services with Windows
| | 00:54 |
communication foundation.
All of these platforms support this
| | 00:58 |
version of Visual Basic.
There are number of programming languages
| | 01:03 |
that are related to this version of
Visual Basic that this course does not teach.
| | 01:08 |
These include an older version of the
language, known as Visual Basic 6 or VB6.
| | 01:14 |
This is an older version of the language
that proceeded the use of the dot frame network.
| | 01:20 |
The term VB6 or Visual Basic 6 refers
both to the language and to the
| | 01:26 |
integrated development environment that
was used to build desktop applications.
| | 01:31 |
There are many similarities between VB6
and Visual Basic .Net, but their
| | 01:36 |
underlying assumptions and the platforms
they run on are very different.
| | 01:40 |
And this course does not deal with this
older version of the language.
| | 01:44 |
The course also doesn't try to teach
Visual Basic for applications.
| | 01:48 |
This is a modified version of the
language that's used in Microsoft Office
| | 01:52 |
applications, and by some third party
software vendors.
| | 01:56 |
And finally, there's a language called VB
Script.
| | 01:59 |
It's an interpretive language similar to
JavaScript in purpose.
| | 02:03 |
What was supported in older versions of
Internet Explorer.
| | 02:07 |
This course is only about Visual Basic
.Net through Visual Basic 2012.
| | 02:12 |
The target audience for this course
includes developers who are brand new to
| | 02:17 |
Visual Basic.
And developers who've been using Visual
| | 02:20 |
Basic, but want to look up or clarify a
language feature.
| | 02:25 |
The course is designed for those who are
brand new to programming.
| | 02:28 |
You don't have to know any software
development terminology.
| | 02:31 |
And along the way, I'll answer a lot of
common questions.
| | 02:35 |
Such as, what is a programming statement,
and what does it look like in Visual Basic?
| | 02:40 |
What's the difference between a variable,
a field, and a property?
| | 02:43 |
What's a method or procedure?
And why do we use those two terms
| | 02:47 |
interchangeably in Visual Basic?
And what's the difference between a
| | 02:50 |
subroutine and a function?
I'll clarify all of these terms along the
| | 02:55 |
way and show you how they're implemented
in this language.
| | 02:58 |
If you're brand new to programming
though, I recommend that you also watch
| | 03:03 |
this course, Foundations of Programming:
Fundamentals.
| | 03:07 |
This course in the Lynda.com library will
help you understand most of the
| | 03:11 |
vocabulary that software developers use
frequently.
| | 03:16 |
And also, Visual Basic 2012 is an
object-oriented language.
| | 03:21 |
It runs on object-oriented platforms,
including the .Net framework and the
| | 03:26 |
Windows run time.
To learn more about object-oriented
| | 03:29 |
programming terminology, watch the course
Foundations of Programming:
| | 03:34 |
Object-Oriented Design.
Between these foundations courses and
| | 03:39 |
this course to help you get started with
Visual Basic.
| | 03:42 |
You should then be able to jump into one
of the platforms or frameworks that help
| | 03:47 |
you build applications with this
programming language.
| | 03:50 |
| | Collapse this transcript |
| Using the exercise files| 00:00 |
This course, Visual Basic Essential
Training, is accompanied by Exercise
| | 00:05 |
Files that you can use to follow along.
I've copied the Exercise Files to my
| | 00:10 |
desktop but you can place them anywhere
on your hard disk.
| | 00:14 |
The exercise files are organized by
chapter with one folder for each chapter.
| | 00:20 |
Within the chapter, you'll find one
folder for each exercise.
| | 00:24 |
And within that folder, there's a project
folder and a solution file.
| | 00:29 |
To open the project in Visual Studio,
double-click to open the Solution file.
| | 00:35 |
If you have more than one edition of
Visual Studio installed, you might be
| | 00:39 |
prompted to select a version.
You should be able to open these projects
| | 00:43 |
in any paid edition of Visual Studio,
that is Professional, Premier or Ultimate.
| | 00:49 |
Or in the free edition that I'm using,
Visual Studio Express for Windows Desktop.
| | 00:55 |
Once you've opened the project, you can
find the visual basic code by going to
| | 00:59 |
the main window.xaml file in the Solution
Explore panel.
| | 01:03 |
Opening up its tree, and then
double-clicking the Visual Basic code
| | 01:08 |
behind file.
The projects have mostly been designed to
| | 01:11 |
open up the default window layout.
But if you ever want to return to the
| | 01:15 |
window layout, go to the Window menu, and
select the appropriate menu choice.
| | 01:20 |
The Visual Basic files don't have any
visual interface.
| | 01:24 |
So when you open them, you always see the
code.
| | 01:27 |
When you open a XAML file though, you'll
sometimes see it open in Code view, and
| | 01:32 |
sometimes in Design view, and sometimes
in Split view.
| | 01:37 |
You can change the orientation of the
panels by clicking the icons on the task
| | 01:41 |
bar above the Code view.
To run any application go to the Menu and
| | 01:47 |
choose Debug, start debugging.
If you want to run without debugging
| | 01:52 |
choose debug, start without debugging.
And if you want to use your keyboard
| | 01:58 |
instead, use the keyboard shortcuts that
are shown on the menu.
| | 02:02 |
F5 for debugging and Ctrl+F5 to start
without debugging.
| | 02:08 |
To stop debugging, if you're in a
debugging session, go to Visual Studio
| | 02:12 |
and press Shift+F5.
So, that's a review of the Exercise Files
| | 02:17 |
that accompany the course.
As you work through the course, I
| | 02:21 |
encourage you to code along with me.
And then at the end of each exercise, do
| | 02:26 |
a few experiments.
Test your knowledge and try a few other
| | 02:30 |
things based on what you've learned so
far.
| | 02:32 |
| | Collapse this transcript |
|
|
1. What Is Visual Basic?Learning the history of Visual Basic| 00:00 |
In computing terms, Visual Basic has a
long history.
| | 00:04 |
It was based on another programming
language simply called BASIC, which was
| | 00:09 |
always spelled in all upper case.
It was designed in 1964, and was
| | 00:14 |
originally an acronym, standing for
Beginners' All-purpose Symbolic
| | 00:19 |
Instruction Code.
It was designed as an educational tool,
| | 00:23 |
to help non-computer science students
learn the art of programming.
| | 00:27 |
The original BASIC, implemented all of
the main elements of programming:
| | 00:32 |
Statements, keywords, variables, values
and expressions.
| | 00:35 |
But, it had a very limited set of data
types.
| | 00:38 |
Strings and numbers, nowhere near the
variety and function that are found in
| | 00:43 |
today's Visual Basic.
Microsoft introduced Visual Basic 1 in 1991.
| | 00:49 |
This was way before the area of .Net
framework.
| | 00:53 |
The original Visual Basic supported drag
and drop form development.
| | 00:57 |
And there were versions available both
for DOS, and for the earliest versions of Windows.
| | 01:02 |
In 2002 Visual Basic.Net came along.
This was an object oriented successor to
| | 01:09 |
the original Visual Basic, which had
continued through version 6.
| | 01:13 |
The .Net framework was introduced as a
platform, where you could choose your own
| | 01:18 |
programming language for development.
The two primary languages were Visual
| | 01:23 |
Basic .Net and C#, a new language that
was inspired by Java and C Syntax.
| | 01:29 |
Visual Basic .Net brought developers into
the world of object oriented programming.
| | 01:36 |
Until the introduction of the Windows
Runtime with window 8, Visual Basic .Net
| | 01:40 |
code ran exclusively on top of the .Net
framework.
| | 01:44 |
And this framework is used to build web
applications with ASP.NET, desktop
| | 01:49 |
applications with WPF, or Windows
presentation foundation, Windows forms or
| | 01:54 |
WinForms, Silverlight, and many other
platforms.
| | 01:58 |
Here's some of the differences between
the older Visual Basic and Visual Basic .Net.
| | 02:04 |
Take a look at these two bits of code.
They both represent event handler methods
| | 02:09 |
or functions, that is code that's
executed when a user clicks a button.
| | 02:15 |
In the code on the left, there's a call
to a function called Message Box, or
| | 02:19 |
MsgBox, and a string is passed to it.
The intent is to show a message box, or a
| | 02:26 |
pop up window, that displays this text.
The equivalent code for .Net is on the right.
| | 02:33 |
You'll see that it's more verbose and
that the syntax is a little bit
| | 02:37 |
different, and here are some of the
differences.
| | 02:40 |
MessageBox on the left is a function,
whereas, the .Net code on the right,
| | 02:45 |
refers to a class named MessageBox and
its method Show.
| | 02:50 |
These bits of code result in essentially
the same display, but the second is a
| | 02:54 |
little bit more verbose, and gives you
many more options.
| | 02:58 |
Here's the sequence of Visual Basic
releases, starting with the first Visual
| | 03:03 |
Basic .NET in 2002.
Starting in that version, Visual Basic
| | 03:08 |
became a language that compiled to byte
code, and then that compiled byte code,
| | 03:13 |
would run on something called the common
language Runtime, or CLR, which was part
| | 03:19 |
of the .Net framework.
A follow up was released the next year,
| | 03:22 |
and then in 2005 the language lost the
.Net extension, and became just Visual
| | 03:28 |
Basic followed by the year of its
release.
| | 03:31 |
Each succeeding version of the Visual
Basic programming language has added more
| | 03:36 |
features, including releases in 2008,
2010 and 2012.
| | 03:42 |
Today, Visual Basic 2012, is supported on
the following versions of Windows,
| | 03:48 |
Windows Vista, Windows 7 and Windows 8.
For Windows XP, the most recent supported
| | 03:55 |
version of the language, is Visual Basic
2010 and you can build apps for all these platforms.
| | 04:02 |
All the different frameworks that are
based on the .NET Framework, including
| | 04:07 |
ASP.net, WPF, WinForms, WCF, Silverlight
and so on, and Windows 8 and Windows RT.
| | 04:16 |
You can also build applications for
Windows Phone, including both 7.5 using
| | 04:21 |
Silverlight, and XNA Game Studio, and
Windows Phone 8, the most recent version
| | 04:26 |
of Windows phone, as of the time of this
recording.
| | 04:29 |
So that's a brief history of the
programming language.
| | 04:33 |
Again, this course deals with the most
recent version of the language, Visual
| | 04:37 |
Basic 2012, but covers details going all
the way back to VB.Net released in 2002.
| | 04:46 |
| | Collapse this transcript |
| Understanding the principles of Visual Basic| 00:00 |
All programming languages are organized
around sets of principles.
| | 00:04 |
Goals that they want to achieve.
Visual Basic follows these principles.
| | 00:09 |
First, it strives to be a simple
language, even while supporting
| | 00:13 |
object-oriented programming.
It's designed to have English-like syntax
| | 00:18 |
to make it easy to use as a first
programming language.
| | 00:22 |
This makes it easy to learn, and it's
non-case sensitive so that it's more
| | 00:26 |
forgiving than C style languages.
Visual Basic is a managed language, that
| | 00:33 |
means that it doesn't compile directly to
native code, but instead can only be
| | 00:37 |
executed by a supporting runtime.
Such as the Common Language Runtime
| | 00:42 |
that's a part of the .NET framework, or
the Windows Runtime that's a part of
| | 00:46 |
Windows 8.
A Visual Basic application never runs on
| | 00:50 |
its own.
It's compiled to bytecode when used in
| | 00:53 |
the .NET framework, and projected to
native code in Windows Runtime.
| | 00:58 |
And Visual Basic supports automatic
memory management and garbage collection
| | 01:02 |
so that you don't have to explicitly
allocate and deallocate memory.
| | 01:07 |
When you use Visual Basic on the .Net
framework, you're building applications
| | 01:11 |
such as web applications for ASP.NET.
Rich internet applications for
| | 01:16 |
Silverlight, desktop applications for
Window forms and Windows presentation
| | 01:20 |
foundation and other platforms.
As I mentioned, your Visual Basic code
| | 01:26 |
compiles to bytecode.
Which is, in theory, cross operating system.
| | 01:31 |
It'll run on any compatible
implementation of the .Net framework.
| | 01:35 |
The .Net framework includes the Common
Language Runtime, or CLR, and here's the
| | 01:40 |
stack of components that are responsible
for running your application.
| | 01:44 |
At the bottom of the stack is the
operating system, and above that, the
| | 01:49 |
Common Language Runtime, or CLR.
The CLR supports the .Net framework in
| | 01:54 |
the form of assemblies and your own
custom objects and libraries.
| | 01:59 |
And finally, your application runs as
compiled byte code.
| | 02:03 |
When you use Visual Basic to build
Windows store apps this stack looks a
| | 02:07 |
little different.
The Windows runtime is a part of Windows
| | 02:10 |
8 and Windows RT.
And in this environment, your Visual
| | 02:14 |
Basic manage code is converted to native
code and executed.
| | 02:21 |
The stack looks like this.
Once again, at the bottom is the
| | 02:24 |
operating system, and then above that a
layer called the Windows Kernel Services.
| | 02:30 |
Then the Windows Runtime APIs, which is
the Windows 8 equivalent of the .Net
| | 02:35 |
framework and above that, compiled native
code.
| | 02:40 |
For Visual Basic developers, who are
moving from the .Net Framework to Windows
| | 02:44 |
Runtime, it's interesting to learn how
that mapping happens.
| | 02:48 |
The compiler uses mapping files, that map
.Net types and methods to native WinRT
| | 02:55 |
types and methods.
The classes and libraries of the window
| | 02:58 |
run time are expressed in managed code
through process known as projection, also
| | 03:04 |
known as language binding.
That can sound intimidating but the
| | 03:08 |
reality is, the only minor differences
between the environments and from your
| | 03:13 |
point of view as the programmer.
Especially when getting started with
| | 03:16 |
Visual Basic, you'll find that your using
pretty much the same coding style in both
| | 03:20 |
development environments.
Finally, one of the most important
| | 03:25 |
choices a developer has to make in the
Microsoft development world is whether to
| | 03:30 |
work with Visual Basic or C#.
If you're watching this course, you've
| | 03:34 |
probably already chosen Visual Basic.
But here are some of the differences
| | 03:38 |
between them.
Both of these languages support all the
| | 03:41 |
Microsoft platforms that I've mentioned,
and they're both object-oriented languages.
| | 03:46 |
But they are important differences in
syntax and style.
| | 03:49 |
C# is a case sensitive language like
other C style languages while Visual
| | 03:56 |
Basic is non-case sensitive.
Visual Basic is designed to look like the
| | 04:01 |
English language, while C# follows the
syntax of C and Java.
| | 04:05 |
Because it used C style syntax, C# used
symbols like double ampersands and double
| | 04:12 |
pipe characters.
Where Visual Basic would use English
| | 04:16 |
words, like and and or.
And finally, C# can be said to be more of
| | 04:21 |
a completely object-oriented platform.
You'll find that there are more built in
| | 04:26 |
functions in the Visual Basic language,
while in C#, everything is a member of a class.
| | 04:32 |
So, that's a look at some of the common
principles that Visual Basic is organized around.
| | 04:36 |
It's simple, it's as easy to learn as any
object-oriented language, and it's
| | 04:41 |
specifically designed for use in
Microsoft development environments.
| | 04:45 |
| | Collapse this transcript |
| Learning Visual Basic syntax| 00:00 |
To get started describing the use of
Visual Basic, I'm going to talk about
| | 00:04 |
some of the common syntax rules and I'll
start with identifiers.
| | 00:08 |
An identifier is essentially a name, you
can assign names or identifiers to
| | 00:14 |
variables, to methods or procedures.
To objects in a visual environment and to
| | 00:20 |
many other items in your programming
environment.
| | 00:24 |
Here are some of the common rules around
all identifiers.
| | 00:26 |
An identifier is a string.
It's made up of alphanumerical
| | 00:28 |
characters, that is A through Z or 0
through 9, and underscore characters.
| | 00:38 |
The first character of an identifier
cannot be a number.
| | 00:42 |
Here's some valid identifiers.
You'll see identifiers spelled sometimes
| | 00:46 |
with camel paps such as the first example
with numbers as a part of the identifier.
| | 00:53 |
With numbers in the middle and with
underscores in the middle.
| | 00:56 |
And here are some invalid identifiers.
The first is invalid because it has a
| | 01:01 |
space in the middle and you can't include
spaces.
| | 01:05 |
The second is invalid because it starts
with a number and you can't do that.
| | 01:10 |
And the third is invalid because the
dollar sign isn't a alpha numeric
| | 01:14 |
character or a number.
Visual Basic is non-case sensitive, so
| | 01:19 |
identifiers are evaluated without regard
to their case.
| | 01:24 |
Here are some identifiers that refer to
exactly the same variable, method or
| | 01:29 |
other object, mystring in all lower case,
MyString in camel case, and MYSTRING in uppercase.
| | 01:37 |
In Visual Basic, these identifiers all
point to the same thing.
| | 01:42 |
And in fact, the compiler will only allow
you to declare one of them in a single
| | 01:47 |
code block.
If you try to declare it again you'll get
| | 01:51 |
a compiler error.
These rules or rather identifiers extend
| | 01:55 |
to elements of the .Net framework and
your own custom classes.
| | 02:00 |
Visual Studio will help standardize your
code, including changing the case through
| | 02:05 |
autocompletion as you type.
But if you force the case to be exactly
| | 02:09 |
what you want, as long as the identifier
points to something valid, it should
| | 02:14 |
compile and run.
The compiler itself doesn't care.
| | 02:18 |
When you declare variables in Visual
Basic, you start with the keyword Dim.
| | 02:23 |
Dim stands for the word dimension.
It's a way of saying allocate memory for
| | 02:29 |
this data.
The Dim keyword or one of its substitutes
| | 02:33 |
is required.
But the next part of creating a variable
| | 02:36 |
is optional.
The keyword As sets the datatype of the variable.
| | 02:42 |
For example, this is a complete Visual
Basic statement.
| | 02:46 |
It says create a variable called
firstName and set its datatype as a string.
| | 02:53 |
Instead of the keyword Dim, you can also
use something called an access modifier.
| | 02:57 |
We'll learn more about access modifiers
late in the course when I talk about
| | 03:03 |
custom classes.
But this is a list of the common access
| | 03:07 |
modifiers, public, protected, friend and
so on.
| | 03:12 |
Each has its own meaning.
When you declare a variable with an
| | 03:16 |
access modifier, you can either use or
not use the Dim keyword.
| | 03:21 |
For example, this code is completely
valid.
| | 03:23 |
Dim Private firstName As String.
Create a private variable called first
| | 03:29 |
name Data typed as the string.
But you can leave the key word Dim out
| | 03:34 |
and it will work just as well.
It means exactly the same thing.
| | 03:39 |
Visual Basic is sensitive to white space.
This makes it different from C-style
| | 03:44 |
languages like Java, JavaScript and C#.
In those languages, each program
| | 03:50 |
statement ends with a semi-colon.
Not all of those languages completely
| | 03:55 |
require a semicolon.
For example, in action script three, a
| | 03:59 |
C-style language that's associated with
Flash, the semicolon is frequently optional.
| | 04:05 |
But in Java, for example, it's required.
Visual Basic in contrast ends each
| | 04:12 |
statement with a line feed.
So for example, in this code, there are
| | 04:17 |
two statements, one that declares a
variable called MyString and one that
| | 04:22 |
sets a property called text on an object
called MyTextBlock.
| | 04:27 |
The two statements are separated from
each other by the line feed at the end of
| | 04:31 |
the first statement.
If you're writing code that's very wide,
| | 04:35 |
and you want to separate a statement onto
more than one line.
| | 04:39 |
You'll need to use the line continuation
character, the underscore.
| | 04:44 |
It means, continue this statement onto
the next line, and ignore the line feed.
| | 04:50 |
This code is doing the same thing as the
original example, creating the variable
| | 04:55 |
and assigning the property.
But each of the two statements are
| | 04:59 |
separated onto two lines.
The continuation character means, keep
| | 05:03 |
reading on the next line.
In recent versions of Visual Basic,
| | 05:08 |
starting with Visual Basic 2010, some
line breaks can be inferred without the
| | 05:13 |
continuation character.
Take a look at the documentation to learn
| | 05:18 |
about which cases are valid.
In this course, I'll always use a
| | 05:22 |
continuation character when I'm
continuing a statement on to the next line.
| | 05:27 |
Finally, let's talk about declaring
values.
| | 05:30 |
In programming, a literal is a way of
describing a value using a string
| | 05:35 |
expression of some kind.
Visual Basic supports many literal types,
| | 05:40 |
including these.
Boolean, integer, floating point,
| | 05:43 |
strings, characters, dates and others.
An inferred literal is a literal where
| | 05:49 |
you simply type the value and the
compiler looks at it and figures out what
| | 05:54 |
the data type is based on the value
itself.
| | 05:57 |
Here's some examples of inferred literals
in visual basic.
| | 06:00 |
29 without any quotes is seen as an
integer.
| | 06:05 |
There is no dot and no values after a dot
so its taken as an integer value.
| | 06:10 |
45.5 in contrast is seen as a double
value because it has a fractional amount.
| | 06:18 |
And the string David wrapped in double
quotes is automatically seen as a string.
| | 06:25 |
You don't have to add any additional
notation into the literal itself when
| | 06:29 |
it's crystal clear exactly what the value
is.
| | 06:32 |
And the word True is clearly a logical
value and in Visual Basic data type
| | 06:37 |
terminology, it's a Boolean value.
With all four of these values, the data
| | 06:43 |
type is infered by the compiler based on
the value it sees.
| | 06:47 |
And you don't need any additional
notation.
| | 06:50 |
There are, however, sometimes where you
need to add some notation to say exactly
| | 06:55 |
what type of literal you want to create.
For characters, you can add a C after the value.
| | 07:02 |
And that means see this as a character,
not as a string.
| | 07:06 |
Date literals can be typed in month date
year format, wrapped in hash marks.
| | 07:13 |
And long values can be marked with an L
to distinguish them from integers.
| | 07:18 |
Single values can be marked with the
exclamation mark.
| | 07:22 |
You can learn more about literal notation
by looking at this URL.
| | 07:26 |
The documentation at this web page
includes this table.
| | 07:30 |
Showing all the different notations
styles that are available.
| | 07:34 |
D or the app character for decimals, R or
the hash mark for doubles, and so on.
| | 07:40 |
So, that's a look at the common syntax
rules for Visual Basic.
| | 07:44 |
With those rules in mind, we're ready to
get started doing some coding.
| | 07:48 |
| | Collapse this transcript |
|
|
2. Getting StartedInstalling Visual Studio 2012 Express for Windows desktop| 00:00 |
You can get a copy of Visual Studio from
this webpage at www.microsoft.com/visualstudio/eng/downloads.
| | 00:12 |
You can use one of the pay-for-license
versions.
| | 00:15 |
That's the professional, premium or
ultimate edition.
| | 00:19 |
Or you can use the free Visual Studio
Express.
| | 00:22 |
Toward the top of the page, click Visual
Studio Express 2012.
| | 00:27 |
There are five additions of Visual Studio
Express 2012.
| | 00:32 |
You'll want this version for this course.
For Windows desktop.
| | 00:36 |
This version of Visual Studio Express
lets you develop with C#, Visual Basic
| | 00:41 |
and C++.
And create desktop applications using
| | 00:45 |
Windows Presentation Foundation, or WPF,
or Windows forms or the Win32 stack.
| | 00:52 |
To install, click this link labeled
Install now.
| | 00:56 |
That will download a small starter
application and you can click Run at the
| | 01:00 |
bottom of the screen.
Once the installer opens, read through
| | 01:05 |
the licence terms and conditions and
check the appropriate check box.
| | 01:08 |
Click Install and follow the rest of the
prompts to complete the installation.
| | 01:13 |
It will take a few minutes to install
Visual Studio...
| | 01:17 |
But once it's done, you'll be able to
start it up and create your first desktop
| | 01:21 |
applications using the Visual Basic
Programming Language.
| | 01:24 |
| | Collapse this transcript |
| Building a simple console application| 00:00 |
To start up Visual Studio Express for the
first time, go to the Start screen on
| | 00:05 |
Windows 8 or the Start menu on Windows 7
and look for the Menu Choice or tile for
| | 00:12 |
Visual Studio Express for desktop.
You'll see that it's named VS Express.
| | 00:19 |
If this is the first time you've started
up Visual Studio on your system, you'll
| | 00:23 |
be asked to register and provide a serial
number.
| | 00:27 |
Follow the prompts and check your email
for the serial number that will be
| | 00:31 |
emailed to you by Microsoft.
Registration is free, but required.
| | 00:36 |
Once you've started it up you'll be able
to create your first project.
| | 00:40 |
To create a project, go to the Menu and
choose File > New Project.
| | 00:46 |
Visual Studio Express for Windows Desktop
lets you create applications using three
| | 00:51 |
programming languages, Visual Basic,
Visual C#, and Visual C++.
| | 00:59 |
Within the Visual Basic section, choose
the Windows category and you'll find a
| | 01:05 |
number of options.
You can build three different types of
| | 01:08 |
applications, a Windows Forms
application, a WPF or Windows
| | 01:14 |
Presentation Foundation application, or a
Console application.
| | 01:19 |
Create a Console Application.
After selecting that option, name the
| | 01:24 |
application Console First App.
I'm placing the application and project
| | 01:30 |
in my exercisefiles02gettingstarted
folder, but you can place it anywhere you like.
| | 01:38 |
A Console App starts off as a simple
Visual Basic file called a module.
| | 01:43 |
And it has a subroutine or a method
called Main.
| | 01:48 |
This Main method will be executed
automatically as the application starts up.
| | 01:53 |
So place the cursor between the sub
declaration and the end sub declaration.
| | 01:57 |
And any code you put there will be
executed.
| | 02:02 |
Our first step is to execute a simple,
hello world, outputting a simple string.
| | 02:08 |
And I'll use an expression that looks
like this.
| | 02:10 |
Console.WriteLine.
In Visual Studio, you can auto complete
| | 02:16 |
code by pressing the Tab key.
So I started typing write and then I
| | 02:22 |
moved the cursor to WriteLine and pressed
Tab.
| | 02:25 |
Now I'll put in an opening parenthesis
and then a simple string of, hello world.
| | 02:31 |
In Visual Basic you don't need to finish
the line with a semi colon or any other punctuation.
| | 02:39 |
All you need is the end of the statement
and in this case that's the closing parenthesis.
| | 02:45 |
I'll save my changes with Ctrl+s, and
then I'll run the application.
| | 02:50 |
When you're working with a console
application, if you run with debugging,
| | 02:54 |
you'll see that the console window flies
by very, very fast, but doesn't stay open.
| | 03:00 |
If all you're doing is outputting content
into the console, run without debugging,
| | 03:05 |
and you can do that by going to the Menu
and choosing Debug > Start Without
| | 03:10 |
Debugging, or pressin Ctrl+F5.
And there is the result.
| | 03:16 |
I see the string, Hello World, and a
prompt, press any key to continue.
| | 03:21 |
And when I press any key the console
window closes.
| | 03:25 |
Now I'll add a few more lines of code.
I'm going to declare a couple of simple variables.
| | 03:31 |
In Visual Basic you declare a variable
using the key word dim.
| | 03:36 |
I'll talk about what that keyword does
and what it means later.
| | 03:40 |
But for now, all you need to know is that
every variable should start with dim.
| | 03:45 |
Then, assign the variable name.
I'll set it as value one and I'll give it
| | 03:51 |
a value of five.
If you already know c style languages,
| | 03:55 |
such as C, C++, or Java, you might be
wondering at this point whether you need
| | 04:00 |
to declare data types.
That is, whether a variable is an
| | 04:04 |
integer, a double, a string, or some
other type.
| | 04:08 |
And the answer is, in Visual Basic, you
don't have to.
| | 04:12 |
You can follow a pattern known as
typeless programming, where you let the
| | 04:16 |
Visual Studio compiler infer the data
types.
| | 04:21 |
In this case, I'm saying that the value
is 5 and the compiler will respond by
| | 04:26 |
saying that the value 1 is an integer.
Next I'll declare a second variable.
| | 04:32 |
I will say Dim value2 equals 20.
You may have noticed that I was prompted
| | 04:38 |
for a keyword called as, but I'm not
going to use that right now.
| | 04:42 |
Finally I will declare a third variable
named total.
| | 04:47 |
And I'll get its value by adding the
first two variable together with this statement.
| | 04:52 |
Dim total equals value one plus value
two.
| | 04:58 |
Just as I did earlier, with
Autocompleting Command, you can also
| | 05:02 |
autocomplete variable names.
For example, if I type in just val.
| | 05:07 |
I'll see a list of all available
identifiers that have that string and I
| | 05:12 |
can choose the one I want and press tab.
Now, I'll output to the console again.
| | 05:18 |
I'll once again use Console.WriteLine and
I'll output a concatenated string.
| | 05:26 |
That's two strings put together.
I'll start with the result is and then
| | 05:32 |
I'll append to that by putting in a plus
operator and then I'll output total.ToString.
| | 05:37 |
That's how you convert a number to a
string.
| | 05:44 |
I'll save my changes, once again with
Ctrl S.
| | 05:48 |
And I'll run with Control F5, and there's
the result.
| | 05:52 |
25.
So that's a look at how to build a very
| | 05:56 |
simple console application in Visual
Studio using the visual basic programming language.
| | 06:03 |
We'll talk a a lot more about this code
and the concept of typeless programming
| | 06:07 |
later on in the course.
And for most of this course I won't be
| | 06:11 |
building console applications.
I'll be building Windows Presentation
| | 06:15 |
Foundation or WPF-based desktop
applications but if you need to use a
| | 06:20 |
console application, this is how you get
started.
| | 06:23 |
| | Collapse this transcript |
| Building a simple desktop application with Windows Forms| 00:00 |
You can use Visual Basic 2012 to build
windowed desktop applications using one
| | 00:06 |
of two architectures.
Either the older Windows Forms architecture.
| | 00:11 |
Or the newer Windows Presentation
Foundation.
| | 00:14 |
I'll be using WPF for most of this
course.
| | 00:17 |
But first I'll show you how to build a
very simple Windows Forms application.
| | 00:23 |
I'll select File > New Project.
I'll choose Visual Basic and Windows, and
| | 00:29 |
then Windows Forms Application, and I'll
set the name of the project to WinFormsFirstApp.
| | 00:40 |
When you create the project it presents a
single empty form.
| | 00:43 |
And you can actually run the application
right away.
| | 00:47 |
I'll click the Start button on the Tool
bar and the application runs.
| | 00:52 |
But it doesn't have anything on it yet.
So I'm going to close the form and return
| | 00:57 |
to Visual Studio.
The first step in creating Windows Forms
| | 01:00 |
application, is typically to set up the
user interface.
| | 01:04 |
And to do that, I'll use the Toolbox
panel, which is on the left side of the screen.
| | 01:10 |
I'll click the Toolbox to open it and
then click the pin icon to pin it open,
| | 01:17 |
and that moves the form over to the
right.
| | 01:19 |
And now I can easily drag and drop visual
controls.
| | 01:24 |
I'm going to place three controls on the
form.
| | 01:28 |
I'll start with a text box; the text box
will allow the user to enter some text.
| | 01:34 |
After dragging and dropping it on to the
form I'll expand its width a bit.
| | 01:39 |
Next, I'll add a button to the form.
I'll click and drag the button.
| | 01:44 |
And I'll place it right next to the text
box.
| | 01:47 |
The button has a label, or a text
property, of button one.
| | 01:52 |
And I'd like to change that to something
that's more informative.
| | 01:56 |
So with the button selected, I'll go over
to the Properties panel.
| | 02:00 |
And I'll locate the text property.
You can find it in a category called Appearance.
| | 02:07 |
And within the category the properties
are sorted alphabetically.
| | 02:11 |
I'll change the text property from button
one to click me.
| | 02:15 |
And it changes visually on the form.
Finally, I'll add a Label.
| | 02:21 |
A Label is sort of like a text box, but
instead of letting the user enter data,
| | 02:25 |
it simply knows how to display text.
So now I have the three controls, and I'm
| | 02:32 |
going to click on the button.
And press the down arrow a few times to
| | 02:35 |
get it better aligned with the text box.
I'm just eyeballing this, and you can
| | 02:40 |
make it look however you like.
I'll save and run the application again.
| | 02:46 |
And now my form has the three controls.
And I'm ready to do a little bit of
| | 02:50 |
programming using Visual Basic.
I'll close the form, and then I'd like to
| | 02:56 |
add a little bit of code that will
execute, when the user clicks on the button.
| | 03:00 |
Visual Studio makes it very easy to
create the code I need.
| | 03:05 |
I'll double-click on the button, and that
results in opening the form in Code view
| | 03:11 |
instead of Design view.
I'll describe later on all the code
| | 03:14 |
you're seeing here, including what it
means when you create a class.
| | 03:19 |
And what a Sub is, and what the word
Private means, and so on.
| | 03:22 |
But all you need to know right now is
that any code you place where the cursor
| | 03:26 |
lands will be executed automatically when
the user clicks the button.
| | 03:31 |
Let's go back to Design mode for a
moment, and I'll show you some things
| | 03:34 |
that happened when I added these
controls.
| | 03:37 |
I'll start with the text box.
I'll click on the text box and then go
| | 03:42 |
over to the Properties panel, and show
right here in bold text, that the text
| | 03:47 |
box control has an ID, or a name, of text
box one.
| | 03:53 |
Then I'll click on the button and show it
has an ID of button one and the label has
| | 03:59 |
an ID of label one.
These are the identifiers for the controls.
| | 04:04 |
And you deal with them in your code in
exactly the same way as you do with the variable.
| | 04:08 |
As long as you know the identifier, you
can work with the control.
| | 04:12 |
So I'm going to go back to the VB window
and then I'm going to expand the window
| | 04:18 |
to full screen.
By holding down the Alt and Shift keys
| | 04:21 |
and pressing Enter and now I'm only
looking at the code.
| | 04:26 |
My first step will be to get the text
that the user entered into the text box
| | 04:31 |
and save it in a variable.
I'll start off with Dim just as I did in
| | 04:36 |
a previous exercise and I'll name the
variable enteredValue, just as before,
| | 04:43 |
I'm prompted with the keyword As.
I'll go ahead and use it this time.
| | 04:48 |
I'll double-click on the keyword As, and
then I'll set that datatype of this
| | 04:54 |
variable as something called As String.
We'll talk about what a string is and
| | 04:59 |
what it means when you explicitly
datatype a variable, as I'm doing here
| | 05:04 |
later on in the course.
But for the moment all I want to do is
| | 05:08 |
set the value of enteredValue to the
value that the user entered.
| | 05:13 |
And to do that I'll put in an Equals
Operator.
| | 05:17 |
Then the identifier of the text box.
That's TextBox1.
| | 05:22 |
And then a property called Text.
That's how you get the value out of the
| | 05:27 |
text box.
Next I'm going to append the value to the variable.
| | 05:33 |
And I'll do it with this syntax.
I'll start with enteredValue equals and
| | 05:39 |
then, You typed.
And notice that I'm putting all the
| | 05:43 |
syntax inside double quotes here.
And then I'll use a plus operator and
| | 05:48 |
then enteredValue.
Finally, I'll output that value using the
| | 05:56 |
identifier for the label, that was
Label1.
| | 06:00 |
And just as with text box, it has a
property called text.
| | 06:04 |
And I'll set its value to enteredValue.
Take a look at all of this code.
| | 06:09 |
First I'm capturing the value that the
user entered.
| | 06:13 |
Then I am prepending or adding a little
bit of text before that value, and then
| | 06:18 |
I'm outputting the value.
I'll save my changes, and I'll run by
| | 06:23 |
pressing Ctrl+F5.
When the form appears, I'll type my name.
| | 06:28 |
And click the button, and I see the
output value.
| | 06:32 |
So that's how you can get started
building a very simple Windows Forms application.
| | 06:37 |
Even though Windows Forms is an older
architecture, many developers find it
| | 06:42 |
perfectly suitable for building business
applications and other utility style applications.
| | 06:49 |
The newer architecture however, Windows
Presentation Foundation, has better
| | 06:54 |
graphical capabilities.
And it's programming model is more
| | 06:58 |
similar to that used in Windows store
apps.
| | 07:01 |
And Windows phone apps.
And is really considered the future of
| | 07:06 |
desktop application programming.
When working with visual basic, so in the
| | 07:10 |
next movie I'll show you how to build
this same application using WPF.
| | 07:16 |
| | Collapse this transcript |
| Building a simple desktop application with WPF| 00:00 |
I've previously described how to build a
very simple console application, and an
| | 00:05 |
application for the desktop using Windows
Forms.
| | 00:08 |
And now, I'll do the same thing for the
desktop using Windows Presentation
| | 00:12 |
Foundation, or WPF.
I've closed all of my projects in Visual
| | 00:16 |
Studio and I'll create another new
project this time using the WPF
| | 00:21 |
application template.
And I'll set the name of the new
| | 00:25 |
application to WPF First App.
A new WPF application has a single empty
| | 00:36 |
form, just like Windows forms.
But in WPF, the form is built from two files.
| | 00:44 |
One built with the XAML language and the
other with Visual Basic.
| | 00:49 |
Let's look first at the XAML file.
XAML stands for Extensible Application
| | 00:54 |
Markup Language.
I'm going to collapse the bottom pane.
| | 00:59 |
And then click on the XAML tab, so I'm
only looking at the XAML code.
| | 01:04 |
XAML is a markup language that's used in
WPF and also in Silverlight, Windows
| | 01:10 |
Phone, and Windows Store Apps to define
the visual appearance of an application.
| | 01:18 |
In WPF, the root element is the window
element.
| | 01:23 |
You'll see differences in the structure
and naming of the elements from one
| | 01:26 |
platform to the next.
The title of the window is set here as
| | 01:31 |
main window, and I'm just going to adjust
it by adding a space.
| | 01:35 |
The MainWindow.xaml file is paired with
what we call a code behind file.
| | 01:42 |
The code behind file could be coded in C
# or C++, but for this application, it's
| | 01:48 |
written in Visual Basic.
The default VB file just has a class declaration.
| | 01:56 |
The name of the class is Main Window.
And it must match the names of these files.
| | 02:01 |
So, you shouldn't put a space there.
Now that I've created the project, my
| | 02:05 |
next step is to create the user
interface.
| | 02:09 |
I'll go to design mode by clicking the
Design tab at the bottom.
| | 02:12 |
And then, I'll click the Toolbox panel
and pin it.
| | 02:16 |
And I'll adjust the location of the form
in this window to make it easier to drag
| | 02:21 |
visual controls into place.
I'll start with the Text box control just
| | 02:27 |
as I did with Windows forms.
And I'll also add a button control and a label.
| | 02:34 |
Notice that I'm not worrying about where
I'm dropping these objects initially.
| | 02:39 |
I'll deal with their position in a
moment.
| | 02:41 |
Now, for each of these controls, I'll
make two big adjustments.
| | 02:44 |
First, I'm going to adjust the font size.
In a new WPF application, the font size
| | 02:52 |
of each of these controls will be pretty
small.
| | 02:55 |
So to make the application a little bit
more readable, I'll increase the font size.
| | 03:00 |
I'll also assign an explicit identifier
to each visual control.
| | 03:05 |
If you worked through the Windows forms
demonstration, you might have noticed
| | 03:09 |
that each of the controls had an
identifier assigned automatically.
| | 03:14 |
In a WPF application, you have to assign
it.
| | 03:18 |
So, I'll make these two adjustments first
for the Text box.
| | 03:21 |
I'll click on the Text box control, and
I'll go to the Properties panel in the
| | 03:26 |
lower right.
And I'll assign a name of MyTextbox.
| | 03:32 |
I'll also get rid of the initial value
that the Text box is displaying.
| | 03:37 |
I'll go to the Common section, and I'll
locate the Text Property.
| | 03:42 |
And I'll just delete that value.
And when I press Enter, it goes away in
| | 03:47 |
Design view as well.
Next, I'll make the same sorts of
| | 03:50 |
adjustments to the label control.
I'll click on the label, I'll give it a
| | 03:55 |
name of my label.
And to get rid of its initial value, I'll
| | 04:00 |
set the content property to a blank
string.
| | 04:04 |
Finally, I'll make the same adjustments
to the button.
| | 04:07 |
I'll click on the button control.
I'll give it a name of MyButton.
| | 04:13 |
I'll set its content to Click Me.
The content for the button is the text
| | 04:18 |
that appears on the button's face.
And I'll go to the text category and
| | 04:24 |
adjust its font size.
I'll make sure I've done the same thing
| | 04:32 |
from the Text box.
And now all the objects are the same size.
| | 04:38 |
Next, I'll move these objects into place.
I'll start with the Text box.
| | 04:43 |
I'll click and drag it so that it's ten
pixels from the left and ten pixels from
| | 04:47 |
the top.
And it snaps into that position.
| | 04:52 |
I'll also adjust the width of the Text
box a little bit.
| | 04:55 |
Then, I'll click and drag the button.
And I'll place it right here right next
| | 04:59 |
to the Text box.
And I'll move it up a little bit by
| | 05:02 |
pressing the up arrow key.
Finally, I'll adjust the position of the label.
| | 05:09 |
Because I removed the initial value, it's
hard to see.
| | 05:12 |
To find it, I'll click anywhere off the
form to deselect everything.
| | 05:18 |
Then, I'll click and drag to select
anything in the center of the form, and
| | 05:22 |
there's my label.
And I'll click and drag and place it so
| | 05:26 |
that it's flush left with Text box.
Now, I'll do a little visual test.
| | 05:32 |
I'll save my changes by pressing control
s and then I'll run the application by
| | 05:38 |
clicking the Start button.
I can click into the Text box, type my
| | 05:43 |
name and click the button, but so far
nothing happens.
| | 05:48 |
Now I'm ready for some Visual Basic code.
Now, close the application and then I'll
| | 05:54 |
create a function that will execute when
the user clicks the button.
| | 05:59 |
And just as I did with Windows forms, I
can generate that function by
| | 06:04 |
double-clicking the button in design
mode.
| | 06:06 |
That then writes the code that I need.
A sub-routine name MyButton_Click.
| | 06:13 |
Notice that includes this clause at the
end, Handles MyButton.Click.
| | 06:20 |
And that's how this code is connected to
that button.
| | 06:23 |
Now, I'll add code and it's going to look
almost exactly the same in Windows forms.
| | 06:30 |
And in fact, that's the purpose of this
exercise, to show you how similar Visual
| | 06:36 |
Basic looks regardless of what
architecture you're using.
| | 06:41 |
I'll expand to full screen with
Alt-Shift-Enter, and I'll create a new
| | 06:45 |
variable that I'll name enteredValue, and
I'll set its data type to String.
| | 06:52 |
I'll set its value by getting a reference
to the text box control, which I named
| | 06:58 |
MyTextBox, and I'll get the value of the
text property.
| | 07:03 |
This code looks almost exactly the same
as it did in Windows forums.
| | 07:07 |
Next, I'll adjust the value of the
variable.
| | 07:12 |
I'll start by assigning its value, enter
value equals.
| | 07:16 |
Then, I'll assign a literal string to its
wrapped in double quotes, and I'll append
| | 07:22 |
to that the existing entered value.
Finally, I'll display the value by
| | 07:29 |
showing it with the label.
I assigned a name of my label, so I'll
| | 07:34 |
look for that.
In Windows forms, the label control had a
| | 07:38 |
text property.
In WPF, it's called the Content Property.
| | 07:43 |
So I'll say MyLabel.Content equals
enteredValue.
| | 07:49 |
I'll save my changes and I'll run the
application with Ctrl+F5.
| | 07:54 |
I'll click into the Text box, I'll type
my name, I'll click the button, and
| | 08:00 |
there's the result.
So if you compare the two bits of code,
| | 08:04 |
the Visual Basic code in the WPF
application with the Visual Basic in
| | 08:09 |
Windows forms, you'll see that its the
same.
| | 08:12 |
Visual Basic the language is the same
language regardless of which architecture
| | 08:18 |
you're working in, and what kind of
application you're building.
| | 08:22 |
You'll find differences in underlying
libraries you're accessing and in the
| | 08:26 |
capabilities of the computer or device
you're coding for.
| | 08:30 |
But the syntax and rules of Visual Basic
are the same.
| | 08:33 |
So, as you learn how to code with Visual
Basic in this course, you'll be able to
| | 08:38 |
apply these lessons across all of the
architectures in which it supported.
| | 08:42 |
| | Collapse this transcript |
| Reviewing the course's code testing application| 00:00 |
The focus of this course is on working
with the Visual BASIC programming language.
| | 00:05 |
For all of the demonstrations, I'll be
using a WPFbased application called Code Runner.
| | 00:12 |
I've delivered a beginning version of the
application in the exercise files, in the
| | 00:16 |
02 Getting Started folder.
Right now there are four folders within
| | 00:21 |
zero two getting started.
The console first app, wind forms first
| | 00:25 |
app, and wpf first app folders are the
projects that I've previously created.
| | 00:31 |
But this folder was a part of the
exercise files all along, code runner.
| | 00:36 |
To open up this project, open the folder
then double click on this solutions file CodeRunner.sln.
| | 00:43 |
If you're prompt into select a version of
Visual Studio choose Visual Studio
| | 00:49 |
Express for Windows desktop.
This application has a single form.
| | 00:55 |
Its name is CodeRunner and it has a
variety of visual controls.
| | 01:00 |
A label.
Two text boxes and two buttons.
| | 01:05 |
I'll look at the code for the form in
XML.
| | 01:07 |
The label displays a string of enter a
value.
| | 01:16 |
A label by definition is read only and it
simply displays text.
| | 01:20 |
The first Text Box has a name of
txtInput, that's the text box controls
| | 01:27 |
identifier and it's how we'll address the
text box in our programming.
| | 01:31 |
The second text box has a name and
identifier of txtOutput, that's the
| | 01:36 |
larger text box and it has properties to
manage its scrolling behavior.
| | 01:41 |
The horizontal scroll bar is disabled and
the vertical scroll bar is set to auto so
| | 01:46 |
that it will appear only when needed.
This text box has an is read only
| | 01:50 |
property of true so it's value can only
be set programatically.
| | 01:54 |
The two buttons have names of btn go and
btn clear.
| | 02:00 |
And they each run a bit of code.
They each have a click event that's
| | 02:05 |
pointing to a sub routine that's a part
of the code behind Visual Basic file for
| | 02:11 |
this forum.
The first button runs a sub routine
| | 02:14 |
called run code.
To get to that code, I'll double click on
| | 02:18 |
the value of the click event.
Then right click and chose Navigate to
| | 02:23 |
even handler.
That opens up the code behind VB file and
| | 02:28 |
shows that the sub routine, Run Code,
doesn't currently have any code in it.
| | 02:33 |
As we test our Visual Basic code, this is
where we'll put it.
| | 02:37 |
There are 2 other sub routines here.
The first is called output, and it will
| | 02:42 |
let us easily output text to the output
text control.
| | 02:47 |
It receives something called an argument.
I'll describe what that is later on,
| | 02:51 |
which is named value.
And then it displays that value in the
| | 02:55 |
output control and appends to that a
value called vbCrLf.
| | 02:59 |
That's a constant.
That's a part of the Visual Basic world
| | 03:05 |
which outputs a carriage return and line
feed.
| | 03:08 |
We'll talk about that constant value when
we talk about strings.
| | 03:12 |
Finally the sub routine clear output
clears the value of the output text control.
| | 03:19 |
So let's add a bit of code to this
testing environment and see how it works.
| | 03:24 |
I'll place the cursor in the RunCode
subroutine and under the comment, I'll
| | 03:26 |
use the subroutine output and output a
string.
| | 03:32 |
I'll type the name of the subroutine and
then type in an opening parenthesis, and
| | 03:39 |
then add a literal string of Hello World.
I'll save with Ctrl+S and run with Ctrl+F5.
| | 03:47 |
That opens the application, and, when I
click the Go button, I see the displayed text.
| | 03:54 |
I can click the Go button as many times
as I want to, and it will keep on adding
| | 03:58 |
text to the output.
Notice the vertical scroll-bar that
| | 04:02 |
appears when it's needed.
Then, to clear the output, I can click
| | 04:06 |
the Clear button.
I'll close the application, and return to
| | 04:09 |
my code.
To capture a value that's typed into the
| | 04:13 |
text input box, declare a variable as a
string.
| | 04:17 |
I'll start with Dim input As String.
And I'll get its value with the
| | 04:23 |
expression txtInput.Text.
Then, I can output that value.
| | 04:28 |
This time, I only want to output that
value, so I'll comment out the line of
| | 04:35 |
code that's outputting Hello world by
adding an apostrophe at the beginning of
| | 04:41 |
the line.
And I'll save and run again.
| | 04:44 |
I'll click into the text input box and
type my name.
| | 04:48 |
And then I'll click Go a number of times
and show that I've successfully captured
| | 04:53 |
the value that's entered.
And that I'm outputting it successfully
| | 04:56 |
in the text output box.
So that's the code testing environment
| | 05:00 |
that I'll be using for most of the
course.
| | 05:03 |
If you preferred you could do the same
sort of code in a console application or
| | 05:08 |
a Windows forms application.
I'm using WPF because it's a little bit
| | 05:13 |
more attractive, and as I mentioned
earlier it represents the future of
| | 05:18 |
Microsoft development...
| | 05:20 |
| | Collapse this transcript |
| Using Visual Basic documentation| 00:00 |
Whenever you learn a programming language
you're going to need to know how to get
| | 00:04 |
to the documentation for the language.
I won't be able to tell you all of the
| | 00:08 |
details of Visual Basic in this course
and so you'll always need to be able to
| | 00:13 |
get to more information.
Here's some tips about navigating the
| | 00:17 |
documentation and help resources that are
available with Visual Studio.
| | 00:22 |
By default, your help resources are
online, and so to get to them while
| | 00:26 |
you're doing your development work,
you'll need an Internet connection.
| | 00:30 |
To get to the primary help resources, go
to the menu and chose Help, View Help.
| | 00:37 |
That will open a browser and take you to
the documentation for Visual Studio 2012.
| | 00:43 |
If you're looking for language
documentation, click on Visual Basic and
| | 00:48 |
Visual C#, and then from there, on Visual
Basic.
| | 00:53 |
From here, you can find conceptual
information, and the complete API
| | 00:57 |
reference for Visual Basic, and for the
.NET or WinRT libraries.
| | 01:03 |
You can also get the context sensitive
help for particular language elements.
| | 01:08 |
For example let's say that you wanted to
learn about the class statement.
| | 01:13 |
This is how you define a software class
in Visual Basic.
| | 01:17 |
To get to the documentation for this
keyword, double click on the keyword to
| | 01:22 |
select it.
Then press F1.
| | 01:24 |
That will open the documentation online,
and you can read the conceptual
| | 01:29 |
information and take a look at the
structure of the command and sometimes
| | 01:34 |
some sample code.
Here's another example.
| | 01:37 |
Let's say you wanted to learn about the
dim statement, the keyword that declares
| | 01:42 |
a variable.
I'll double click and press f1 again.
| | 01:46 |
And that takes me to the documentation
for dim.
| | 01:50 |
You can also use context sensitive help
with zamil.
| | 01:54 |
I'll go to my zamil file in my code
runner application, and I'll double click
| | 01:59 |
on the label element, and press F1.
And that takes me to all the information
| | 02:04 |
I need about the Label class.
If you prefer, you can download
| | 02:10 |
documentation and use it locally.
To do this, go to the menu and choose
| | 02:15 |
Help > Add and Remove Help Content.
That opens an application called Help Viewer.
| | 02:23 |
From here, you can select one or more
documents that you want to download and
| | 02:27 |
use locally.
I'll click the add link for visual basic
| | 02:32 |
and visual c sharp and I see a status of
add pending.
| | 02:37 |
Now, to actually download that
documentation, I'll click the update button.
| | 02:43 |
If you see a user account control
dialogue box at this point, click yes.
| | 02:48 |
It won't always show up.
But once you've gotten to this point,
| | 02:52 |
you'll be downloading the documentation
that you selected.
| | 02:55 |
It'll be merged into your local
documentation.
| | 02:58 |
And it'll be ready to use.
Then to change the way visual studio
| | 03:03 |
behaves when you ask for help, go to the
menu and choose help, set help
| | 03:10 |
preference, launch in health viewer.
Now to test that, I'll go back to my vb window.
| | 03:18 |
I'll once again double click to select
the dim keyword, and I'll press F1.
| | 03:24 |
And now the local documentation opens in
help view.
| | 03:28 |
So if you're going on a trip, you're not
going to have an internet connection, but
| | 03:32 |
you still want to keep on programming,
prepare ahead of time.
| | 03:36 |
Download the documentation that you'll
need, change your options, and you'll be
| | 03:40 |
able to get to all the information you
need when you need it.
| | 03:44 |
For the purpose of this course, I'll be
using the online help, but both of these
| | 03:48 |
documentation sets have the same
information and can help you as you learn
| | 03:53 |
Visual Basic.
| | 03:53 |
| | Collapse this transcript |
|
|
3. Declaring and Using VariablesDeclaring variables and data types| 00:00 |
One of the first things you need to learn
in a new programming language is how to
| | 00:04 |
store data in memory.
We do this using variables.
| | 00:07 |
A variable is a way of referencing data
in memory, and points to either a raw
| | 00:12 |
value or a complex object.
In Visual Basic, each variable has a name
| | 00:17 |
and a data type.
The data type can either be described
| | 00:20 |
explicitly or it can be inferred from the
value that you assign.
| | 00:25 |
The Visual Basic language has a set of
built in data types, and these data types
| | 00:30 |
map to data types that are a part of the
underlying platform.
| | 00:34 |
Either the .NET framework, if you're
working in ASP.net, WPF, Windows forms,
| | 00:39 |
Silverlight, Windows Phone and so on, or
Windows Runtime if you're working in
| | 00:45 |
Windows store applications.
Here are the built in data types in
| | 00:48 |
Visual Basic.
First there are Boolean values.
| | 00:52 |
A Boolean variable can contain a value of
either true or false.
| | 00:56 |
These values are represented in Visual
Basic by the keywords true and false.
| | 01:01 |
Typically, you'll see them spelled with
uppercase initial characters, t and f.
| | 01:06 |
But because Visual Basic is non-case
sensitive, you can spell them in all
| | 01:11 |
lowercase if you prefer.
A Char, or a character, represents a
| | 01:15 |
single alphanumeric character: a, b, c,
and so on, or one, two, and three.
| | 01:20 |
It's represented as raw value of zero to
64k.
| | 01:25 |
A Date value takes 8 bytes of memory.
The range of available dates is shown here.
| | 01:30 |
And a Date value also contains a time
value.
| | 01:33 |
I'll talk about dates extensively in
another movie.
| | 01:36 |
And object can either point to a generic
Visual Basic object, or to an instance of
| | 01:42 |
a class.
And this can be a class that's defined in
| | 01:45 |
the underlying platform, the .NET
framework or Windows Runtime.
| | 01:49 |
Or, it can be an instance of your own
custom class.
| | 01:52 |
The reference to the object takes 8 bytes
of memory, but the object itself takes up
| | 01:57 |
as much space as it needs.
A string is also an object, that is, it's
| | 02:01 |
an instance of a class, but it's
specifically designed to contain a set of
| | 02:06 |
characters in a particular order.
A String can be very long, up to
| | 02:10 |
approximately 2 billion characters,
essentially as long as you need it to be.
| | 02:14 |
And the amount of memory it takes up
depends completely on its length.
| | 02:19 |
Finally, there are numeric values.
Visual Basics supports a number of
| | 02:23 |
different numeric data types, including
integers Bytes, doubles, and more.
| | 02:27 |
You choose the data type you need
depending on the nature of the data you
| | 02:33 |
need to store.
I'll talk about numbers extensively in a
| | 02:36 |
separate movie.
In order to declare a variable, you can
| | 02:39 |
use up to 4 parts in a statement.
The first two parts are required, you
| | 02:44 |
start with the keyword Dim, or something
called an access modifier.
| | 02:48 |
I'll talk about access modifiers later in
the course.
| | 02:51 |
When we talk about object oriented
concepts, like classes, but for simple
| | 02:56 |
variables you'll start with the Dim key
word.
| | 02:59 |
Dim stands for dimension and it tells
Visual Basic to allocate the memory
| | 03:05 |
that's going to be required to store the
data.
| | 03:08 |
The next part of the statement is also
required.
| | 03:10 |
You should name your variables
descriptively, so you can identify them
| | 03:14 |
easily in your programming.
The next part is optional.
| | 03:17 |
You don't have to explicitly state the
datatype in Visual Basic.
| | 03:21 |
If you like, you can follow a model known
as typeless programming, where you let
| | 03:27 |
the Visual Basic compiler infer the
datatypes, depending on the values that
| | 03:31 |
you're assigning.
In most modern Visual Basic programming,
| | 03:35 |
you'll see data types explicitly
declared, because it results in better
| | 03:39 |
performance in many environments.
And finally, there's the initial value.
| | 03:43 |
This is completely optional.
If you know the initial value at the time
| | 03:47 |
of declaring the variable, you can assign
it.
| | 03:49 |
Or you can declare it, and then assign
the value later.
| | 03:53 |
Here's what a variable declaration looks
like.
| | 03:55 |
You start with the keyword Dim, then the
name or identifier, which here is value.
| | 04:01 |
Then the data type, which starts with the
keyword As, and then contains the data type.
| | 04:06 |
Then, if you're assigning a value, you
add the equals operator and the value.
| | 04:11 |
The Dim keyword is the dimension, the
next part is the name, value.
| | 04:16 |
The next part is the data type, and the
final part is the assignment.
| | 04:20 |
In this case, I'm assigning a literal, a
string representation of the value.
| | 04:25 |
But you can also assign it from an
existing variable or from any other kind
| | 04:29 |
of expression.
Most of the time when you want to declare
| | 04:32 |
a complex object variable, you'll declare
it as an instance of a class.
| | 04:37 |
Just like with built-in types, you
declare it with 4 parts, but if you're
| | 04:41 |
using a class you'll frequently use a
class called New.
| | 04:45 |
And then, you'll call a particular
function, also known as a method, known
| | 04:49 |
as the constructor method.
A complex class has these special methods
| | 04:53 |
that create a new instance of the class.
Here's an example.
| | 04:57 |
I'm starting with a array of characters.
The braces around the comma-delimited
| | 05:03 |
list mean, this is an array, a set of
values in a certain order.
| | 05:08 |
This array contains five values, the five
letters in the word Hello.
| | 05:12 |
Then, I'm creating an instance of the
String class by passing that array into
| | 05:17 |
the constructor method.
And because I'm calling the constructor
| | 05:21 |
method, I'm using the new keyword.
I could accomplish pretty much the same
| | 05:25 |
thing using simpler syntax, but by
showing you how to assign a string value
| | 05:29 |
in this way, it demonstrates that classes
work pretty much the same regardless of
| | 05:34 |
whether they're strings or any other kind
of class.
| | 05:37 |
Notice the use of the continuation
character in this example.
| | 05:41 |
Because the code was too wide to fit on
the screen, I broke it into two lines and
| | 05:45 |
added the continuation character, the
underscore at the end of the first line.
| | 05:50 |
You can also declare variables inside
functions or sub-routines.
| | 05:54 |
A function or sub-routine is a bit of
reusable code.
| | 05:57 |
Throughout this course, I'll refer to
functions, or methods, or sub routines,
| | 06:02 |
and sometimes interchange the terms.
There is a distinction between a function
| | 06:06 |
and a sub routine in Visual Basic and
I'll talk about that difference later.
| | 06:10 |
But they're both different kinds of
methods.
| | 06:13 |
When you declare a variable inside of
function, it's local to the function.
| | 06:17 |
That is it is invisible outside the
function.
| | 06:20 |
So, here's an example of a function
called GetFullName.
| | 06:23 |
It's receiving two values or parameters,
also known as arguments, called FName and LName.
| | 06:30 |
And notice that those are both data typed
as strings.
| | 06:33 |
Then, within the function, I'm declaring
a variable called FullName and getting
| | 06:38 |
its value by combining the first name and
last name.
| | 06:41 |
And a literal space, and then returning
the full name value.
| | 06:45 |
The full name variable is local to the
function because it was declared inside
| | 06:50 |
the function.
And when the function is finished
| | 06:52 |
executing, it will no longer be visible
to the rest of the code.
| | 06:56 |
You know it's local to the function
because of where it's declared.
| | 07:00 |
Finally, there are class variables.
When you get into building your own
| | 07:04 |
custom classes, you can declare variables
that are members of the class.
| | 07:08 |
And using object oriented terminology,
these are known as class fields, also
| | 07:14 |
referred to as class variables.
This is an example of a custom class
| | 07:18 |
called Person.
It has 4 class variables, or fields,
| | 07:21 |
called FirstName, LastName, Age, and DOB.
They're marked with an access modifier
| | 07:28 |
called Public.
Which means their publicly visibly to the
| | 07:31 |
rest of the application.
Two of the variables are strings.
| | 07:34 |
One is an integer, and one is a date.
There are many ways to rewrite this code
| | 07:39 |
to make it more efficient and have it
follow better object oriented design patterns.
| | 07:44 |
But this is a very simple example of
declaring variables that are members of a class.
| | 07:49 |
So, that's a look at different ways of
using variables in Visual Basic.
| | 07:53 |
Next, I'll show you some of the details
about working with variables in Visual
| | 07:57 |
Basic in a series of hands-on exercises.
| | 08:00 |
| | Collapse this transcript |
| Working with data types| 00:00 |
For this exercise, I'm going to start by
showing you a few different ways of
| | 00:04 |
declaring variables in your Visual Basic
applications.
| | 00:08 |
I'll work in a project called data types
in the 03 variables chapter.
| | 00:13 |
Within the data types folder, I'll
double-click the data types solution file
| | 00:17 |
and open it in Visual Studio Express for
Windows desktop.
| | 00:21 |
Then, in the Solution Explorer panel,
I'll open the project tree, open
| | 00:24 |
MainWindow.xml, and double-click to open
the Visual Basic file.
| | 00:30 |
And I'll place all the code here in the
RunCode subroutine or method.
| | 00:35 |
I'll start by declaring a simple string.
I'll put in the keyword dim for dimension.
| | 00:41 |
I'll assign a variable name of myString,
and I'll set an explicit data type of As String.
| | 00:48 |
Then I'll assign an initial value of
Hello World.
| | 00:52 |
This declaration includes all four
available parts of a variable declaration.
| | 00:56 |
The dim keyword, the name of the
variable, the data type and the value.
| | 01:02 |
Next I'll output that value to the string
by calling my output method and passing
| | 01:08 |
in myString.
I'll save the change and I'll run the application.
| | 01:11 |
When the application runs, I'll click the
Go button.
| | 01:14 |
And there's the result.
And I can click that button as many times
| | 01:17 |
as I like.
Next, I'll declare variables of a couple
| | 01:21 |
of different data types.
The next variable will be called
| | 01:24 |
myNumber, and I'll set its data type to
Integer.
| | 01:27 |
And I'll give it a value of 42.
Next I'll create a date, and I'll set its
| | 01:34 |
data type to Date.
And for this one, I'll use a function
| | 01:38 |
called DateValue.
The DateValue function receives a string,
| | 01:43 |
and it converts it internally to a
DateTime value.
| | 01:47 |
I'll pass in a value of November 28th,
2013.
| | 01:53 |
So now I have a string, a number, and a
date.
| | 01:57 |
And I'll take this output command, I'll
copy it to the clipboard, and I'll paste
| | 02:02 |
it in a couple of times, and I'll change
the values that I'm outputting to
| | 02:09 |
myNumber and to myDate.
I'll run the application and test the
| | 02:13 |
code, and I'll see that the literal
values that I assigned to the string and
| | 02:17 |
the number, our output exactly as I set
them.
| | 02:20 |
But that the date is output in a
different form.
| | 02:23 |
This is a clue that a date value is being
handled a little bit differently than
| | 02:26 |
strings and numbers.
So now, let's change these references a
| | 02:31 |
little bit.
I'm going to make a copy of these three
| | 02:34 |
declarations, and then paste them in
above the output commands.
| | 02:39 |
And then I'll change the names of these
versions to myString2, myNumber2, and myDate2.
| | 02:45 |
Notice that until I did that, I was
seeing a little squiggly line, telling me
| | 02:49 |
there was an error.
You can only declare each identifier once
| | 02:53 |
within a single scope.
Because I had already used myString, I
| | 02:58 |
couldn't use it again.
Now I'm going to remove the data type
| | 03:02 |
declarations from these second versions.
Programming languages are typically
| | 03:11 |
categorized as static or dynamic
languages.
| | 03:14 |
Java and C-sharp are static languages.
They're languages that require data type declarations.
| | 03:22 |
JavaScript on the other hand, is a
dynamic language.
| | 03:25 |
It infers its data types from values that
are assigned.
| | 03:29 |
In Visual Basic, you can treat the
language as a static language or as a
| | 03:33 |
dynamic language.
These first three declarations are static
| | 03:37 |
declarations, meaning that I'm saying
exactly what the data type is.
| | 03:41 |
These three declarations in contrast are
dynamic declarations.
| | 03:46 |
The data types of the variables are
determined by the values that are being assigned.
| | 03:50 |
But internally, what's really happening,
is that the compiler is examining the
| | 03:55 |
literal values that I'm assigning and
setting the data type without my having
| | 04:00 |
to say it explicitly.
This is called inferred data typing.
| | 04:04 |
Now, you can tell this is happening by
saving your code and then moving the
| | 04:08 |
cursor over the variable name.
And you'll see a little message telling
| | 04:13 |
you that this variable is a string.
I'll do the same thing with the number
| | 04:17 |
and I'm told that it's an integer and the
same thing with the date, and I'm told
| | 04:21 |
that it's a date.
Next, to show how powerful data type
| | 04:25 |
inference is, I'll change the numeric
value from 42 to 42.5.
| | 04:31 |
I'll save the change and move the cursor
over the variable name again, and now I'm
| | 04:35 |
told that it's a double value.
This sort of programming is perfectly
| | 04:39 |
fine in Visual Basic.
As long as you're assigning a literal
| | 04:43 |
value to a variable, you don't have to
put in the ASCII word and the explicit
| | 04:48 |
data type.
But here's how you can get into a little
| | 04:50 |
bit of trouble.
Let's say that I declared a variable
| | 04:53 |
without a data type up at the top of the
code.
| | 04:57 |
I'll place the cursor up here, and I'll
declare a new variable that I'll call unknownType.
| | 05:03 |
When I save my changes, I get a little
squiggly line telling me that there's an
| | 05:07 |
error, and when I move the cursor over
that, I'm told that this is an unused
| | 05:11 |
local variable.
Visual Studio wants me use it, so now
| | 05:16 |
I'll move the cursor down here.
After my explicit variable declarations,
| | 05:20 |
and I'll say unknownType equals myString.
When I save the change, the squiggly line
| | 05:27 |
goes away.
But now, it tells me that the unknownType
| | 05:30 |
variable is declared as something called
an object.
| | 05:34 |
It won't become a string until the
application is running.
| | 05:37 |
And when that happens, the underlying
runtime will have to deallocate the
| | 05:41 |
original memory and allocate new memory.
For this reason, it's recommended in
| | 05:46 |
Visual Basic that you use explicit data
typing whenever possible.
| | 05:51 |
You'll get better performance and better
memory usage.
| | 05:54 |
And in fact, there are options that you
can set in your Visual Basic programs
| | 05:58 |
that turn some of these features off and
make Visual Basic a purely static language.
| | 06:04 |
We'll talk about some of those other
options later in the course.
| | 06:07 |
| | Collapse this transcript |
| Working with numbers and Boolean values| 00:00 |
As I mentioned in a previous movie,
Visual Basic supports a large number of
| | 00:05 |
numeric data types.
When choosing a numeric data type to
| | 00:09 |
represent your numbers, you should take
these factors into account.
| | 00:12 |
There are integral and nonintegral data
types.
| | 00:14 |
An integral data type represents only
integers where as nonintegral data types
| | 00:21 |
can handle fractional values.
Each data type has a range from a low to
| | 00:25 |
a high value and there are both signed
and unsigned data types.
| | 00:30 |
A signed data type supports both negative
and positive numbers while unsigned data
| | 00:35 |
types only support positive numbers.
And you can also take into account the
| | 00:40 |
performance and precision of each of the
data types.
| | 00:44 |
The two most common data types that
you'll see in Visual Basic examples are
| | 00:48 |
called integer and double.
And the integer is what says it is, it
| | 00:53 |
handles integral values.
And integral values in general are faster
| | 00:57 |
than non integral data types.
And the integer is the fastest of them
| | 01:01 |
all when it comes to doing mathematical
operations.
| | 01:05 |
The other common data type that you'll
see is called Double.
| | 01:08 |
It's a non-integral type and it can
handle fractional values and it's faster
| | 01:12 |
than the other non-integral types.
But there are many other data types available.
| | 01:18 |
Here are all the integral data types.
There are both signed and unsigned
| | 01:22 |
integral data types.
Each of these data types has a particular
| | 01:25 |
range and a particular amount of memory
it takes to store.
| | 01:29 |
The S byte and byte are 8 bit values, and
the S byte is signed, the byte is unsigned.
| | 01:35 |
There's Short and UShort, Integer and
UInteger, and Long and ULong.
| | 01:39 |
As I mentioned previously, the most
commonly used of these is the integer value.
| | 01:45 |
And both integer and unsigned integer are
the fastest available types when you're
| | 01:50 |
dealing with mathematical operations.
All things being equal, it's not a bad
| | 01:55 |
strategy just to stick with the integer
and unsigned integer values.
| | 01:59 |
And only to use the byte and short values
when you know for sure that you're
| | 02:04 |
dealing with small small values.
The non integral types are these, Single,
| | 02:08 |
Double and Decimal.
The advantage of the Single datatype is
| | 02:13 |
that it takes less memory to store,
whereas Double takes twice the amount.
| | 02:17 |
And Decimal takes twice the amount of
double.
| | 02:20 |
Here are a few important things to know
about non integral data types.
| | 02:24 |
All of the non integral types are signed.
So they can handle both negative and
| | 02:29 |
positive values.
There's no such thing as an unsigned non
| | 02:34 |
integral data type.
And it's also important to know that the
| | 02:37 |
Double data type is a floating point type
and is subject to rounding.
| | 02:42 |
When you're doing mathematical operations
with fractional values.
| | 02:45 |
The value won't always come out exact.
And so if you're dealing with currency
| | 02:49 |
values and you need to make absolutely
sure you're getting the right value, use decimal.
| | 02:54 |
It takes more memory, it's not quite as
fast as the double data type but, it will
| | 02:59 |
always return exactly the right value.
Let's take a look at some examples of
| | 03:04 |
declaring and outputting numeric values.
I'm working in a version of my code
| | 03:08 |
runner project in the numerics solution,
and I'll add code to the run code sub routine.
| | 03:14 |
I'll declare a new variable called
intvalue and I'll set its data type as integer.
| | 03:21 |
And I'll give it a value of 55.
Then I'll output it using my output
| | 03:27 |
subroutine and I'll pass in the new
variable.
| | 03:31 |
I'll save and run the application.
And click the Go button and there's the result.
| | 03:36 |
So an integer value is exactly that, it
handles an integer.
| | 03:41 |
Watch what happens, though, if I try to
add a fractional value.
| | 03:44 |
I'll add .5.
And when I save and try to run the
| | 03:48 |
application, and click the Go button.
Instead of returning 55.5, it returns 56
| | 03:56 |
because I said it was an integer.
It automatically rounded for me.
| | 04:00 |
I'll go back to the code, and I'll trim
that .5 off.
| | 04:04 |
And now, I'll know that the value I'm
passing into the intValue variable will
| | 04:08 |
retain its original value.
Next, I'll declare a short value.
| | 04:13 |
I'll use Dim, I'll name this variable
shortValue, and I'll set its data type as short.
| | 04:19 |
And I'll give it a value of 5 and I'll
output it.
| | 04:27 |
I'll run the application and click the Go
button and there's the result.
| | 04:32 |
The short and the integer values were
pretty much the same and the only
| | 04:36 |
difference is their range.
And as I mentioned performance because
| | 04:40 |
integers are a bit faster when you're
doing math.
| | 04:43 |
I'll declare a variable named Byte Value.
I'll set it as a byte and I'll give it
| | 04:48 |
its maximum value of 255.
Remember, byte is an unsigned data type.
| | 04:55 |
It can't handle negative values but as a
result you get a higher available
| | 04:59 |
positive value.
And then I'll output it.
| | 05:05 |
And when I run the application, I get the
value.
| | 05:09 |
Now let's see what happens if you try to
exceed the range of a particular data type.
| | 05:14 |
I'll look a this in full screen mode.
And here I'll add 1 to current value of
| | 05:20 |
byte value using the code byteValue += 1.
That adds 1 to the existing value and
| | 05:29 |
then I'll try to output that value.
When I run the application and click Go,
| | 05:35 |
I get a big old error.
Now I've been running the application by
| | 05:38 |
pressing Ctrl+F5, meaning I'm running
without debugging.
| | 05:42 |
So to see what went wrong, I'll close the
program.
| | 05:45 |
And this time I'll press just F5 so that
I'm running in debug mode.
| | 05:50 |
I'll click Go.
I get an exception dialog and I'll click
| | 05:54 |
the Break button.
And that takes me into debug mode.
| | 05:58 |
I'll press Alt+Shift+Enter.
So I can see all of my panels.
| | 06:01 |
And I'll show down here that I'm getting
some events and errors.
| | 06:05 |
The best way of finding out what went
wrong is to wrap this code that's causing
| | 06:09 |
the problem inside something called a
Try/Catch block.
| | 06:13 |
Now I'm jumping a little bit ahead in
terms of code structure.
| | 06:16 |
But it's really useful to understand how
to catch errors and output their messages
| | 06:21 |
at an early phase of your learning.
So I'm going to go back into full screen
| | 06:25 |
mode here.
Now, I'll get rid of this window down
| | 06:28 |
here and I'm going to add a try/catch
block.
| | 06:32 |
If you're still in debug mode, press
Shift+F5 and that'll get you out of debug
| | 06:36 |
mode and you can keep on coding.
I'll type the word Try and press Enter
| | 06:40 |
and that creates three lines of code.
With a try, a catch and an end try.
| | 06:47 |
Now I'll take these two lines of code
that are causing the problem and I'll cut
| | 06:51 |
and paste them after the key word try.
Then in the catch block, I'll use this
| | 06:56 |
code to output the error message.
In the catch block, I'm getting this
| | 07:00 |
variable alt ex, data typed as something
called an exception.
| | 07:05 |
The exception has something called a
message, and that's where I'll get my
| | 07:08 |
error message.
So I'll use my output sub routine, and
| | 07:12 |
I'll pass an ex.message.
I'll run the application again, once
| | 07:17 |
again pressing F5.
I'll click the Go button, and this time I
| | 07:22 |
get the error message arithmetic
operation resulted in an overflow.
| | 07:26 |
This is an important feature of Visual
Basic.
| | 07:29 |
In some programming languages, exceeding
the available range of a numeric data
| | 07:34 |
type, results in wrapping the value
around.
| | 07:36 |
That is to say, instead of going to 256,
it would go to zero.
| | 07:41 |
But in Visual Basic, if you try to exceed
the range of a data type, you'll get an error.
| | 07:46 |
Just don't do it.
So by wrapping the code inside a
| | 07:49 |
try/catch block, I've ensured that I'm
catching the error if it occurs.
| | 07:55 |
So that's a look at how to deal with
common numeric values.
| | 07:59 |
I've described the differences between
different numeric values.
| | 08:02 |
Noted that there are integer and non
integer values, signed and unsigned
| | 08:07 |
values, and data types with faster and
slower performance.
| | 08:12 |
In the next movie, I'll describe the
rules for converting various numeric data
| | 08:16 |
types to each other.
| | 08:17 |
| | Collapse this transcript |
| Converting numeric values| 00:00 |
As I previously described, Visual Basic
has many numeric data types.
| | 00:04 |
And in all sorts of applications, you'll
frequently find that you have to work
| | 00:09 |
with conversions.
Converting numbers to strings, strings to
| | 00:12 |
numbers, and between different numeric
data types.
| | 00:15 |
I'll start with describing how to convert
a numeric value to a string value.
| | 00:20 |
Each of the numeric data type classes
such as integer, double, byte and so on
| | 00:25 |
have a method named ToString, the
ToString method is called from an
| | 00:29 |
instance in the class.
And when you declare a numeric variable
| | 00:33 |
it's an instance of one of these data
type classes.
| | 00:36 |
The ToString method is sometimes called
implicitly, that is, you don't actually
| | 00:40 |
have to write the code.
In this example I've declared a variable
| | 00:43 |
intValue as an integer and assigned it a
literal value of 55, then I simply pass
| | 00:49 |
that value to a variable data typed as a
string.
| | 00:52 |
In this case I don't have to call the
ToString method.
| | 00:55 |
It's called for me.
But there are other cases where you have
| | 00:59 |
to call ToString.
For example, if you want to combine a
| | 01:02 |
string and a number into another string,
you'll need to call ToString explicitly.
| | 01:07 |
In this code, my variable strValue is
created by combining a literal string
| | 01:13 |
value colon space with the value of the
integer, and I'm calling the ToString method.
| | 01:18 |
If I don't call the ToString method in
this case, I'll get a programming exception.
| | 01:23 |
You'll also need to convert strings to
numbers.
| | 01:25 |
For example, if the user is working with
the data entry form and types in a
| | 01:29 |
numeric value, in many cases you'll need
to explicitly convert that for them.
| | 01:33 |
To do this, each of the numeric data-type
classes has a parse method.
| | 01:38 |
You call this method from the class, not
from an instance of the class.
| | 01:42 |
It's what's sometimes known as a static
method.
| | 01:45 |
Use the target data-type class that
represents the kind of number you want.
| | 01:49 |
In this code, I'm starting with a string
value, and I'm passing it into the parse
| | 01:53 |
method of the integer class.
And I get back an integer value that I
| | 01:57 |
assign to the variable.
Make sure that the string you're trying
| | 02:01 |
to convert can be converted, that is that
it represents a valid numeric format and
| | 02:06 |
that the value fits int the range of the
target data type.
| | 02:09 |
If you want to check for numeric
compatibility before you convert call the
| | 02:13 |
IsNumeric function.
You can call this function anywhere.
| | 02:17 |
You pass in a value, and it returns true
if the value can be parsed as numeric and
| | 02:22 |
false if it can't.
You can use IsNumeric on strings, and on
| | 02:26 |
numeric values.
You can also convert numbers to numbers.
| | 02:30 |
If you're converting from a less precise
data type, say an integer.
| | 02:35 |
To a more precise type, such as a double.
We call that widening.
| | 02:39 |
You can widen a value implicitly and
safely, without risking data loss.
| | 02:45 |
In this example, I'm starting off with an
integer and converting it to a double.
| | 02:49 |
Because I'm going from less precise to
more precise, I'm widening, and I don't
| | 02:54 |
need to add any extra conversion code.
This sort of conversion is always safe,
| | 02:59 |
so you typically don't need to wrap the
code inside try catch blocks or do other
| | 03:03 |
error handling.
Going in the other direction though is
| | 03:06 |
another story.
If you're going from a more precise data
| | 03:09 |
type to a less precise type you can lose
data or cause exceptions.
| | 03:15 |
Let's take the example of going from a
double value with a fraction to an integer.
| | 03:19 |
In this case, the number will be rounded
or truncated, if possible.
| | 03:24 |
You'll lose the precision, but you won't
cause a programming exception.
| | 03:28 |
On the other hand, if the result after
the conversion exceeds the range of the
| | 03:32 |
target data type, you will get a
programming exception.
| | 03:35 |
This behavior is different than many
other programming languages.
| | 03:39 |
In java, for example, if you start with a
byte which has a maximum value of 255 and
| | 03:45 |
you add 1, instead of getting 256 it'll
wrap around and become zero.
| | 03:50 |
In visual basic that operation causes an
exception.
| | 03:53 |
So, you need to make absolutely sure you
know what the values are and that they
| | 03:57 |
match the available range.
To convert values when narrowing, there
| | 04:01 |
are two sets of conversion functions
available.
| | 04:04 |
One older set of functions that came from
Visual Basic 6, and has been implemented
| | 04:08 |
in the latest versions of Visual Basic,
and one that was added in Visual Basic .NET.
| | 04:13 |
The older set of conversion functions are
called the built-in conversion functions.
| | 04:18 |
They all start with the letter C for
Convert and then end with a target data
| | 04:22 |
type so you have CInt for integers,
CDouble for doubles and so on.
| | 04:27 |
The newer set of methods are members of a
class called Convert.
| | 04:31 |
They're called toInteger, toDouble and so
on.
| | 04:34 |
In general, you'll get more precise error
messages by using the convert class
| | 04:39 |
methods and they're generally recommended
over the older built-in conversion functions.
| | 04:44 |
Now let's take a look at a little bit of
code.
| | 04:46 |
I'm working in a project called,
Converting Numbers.
| | 04:48 |
And I've already declared four variables,
a byte, an integer, a double and a string.
| | 04:54 |
I'll start with string conversion.
I'm getting the string value from the
| | 04:58 |
text input boxes text property.
So, it will be whatever I type when I run
| | 05:03 |
the application.
Now, I'll create a variable called
| | 05:05 |
intFromString, and I'll data type it as
an integer.
| | 05:10 |
I'll get its value by parsing the string
value.
| | 05:14 |
Calling Integer.Parse and I'll pass in
str1.
| | 05:18 |
Then I'll call my output method and I'll
pass in, You entered, and then a space
| | 05:23 |
and then I'll append to that the new
integer variable and I'll call its two
| | 05:27 |
string method explicitly.
I'll test the code.
| | 05:32 |
And I will type in a numeric value of
1024 and I'll click go.
| | 05:37 |
Now as long as I type in an actual
numeric value, everything's fine, but if
| | 05:41 |
I type in a value that can't be parsed as
a number, I'll get an error.
| | 05:44 |
So, I'm going to get out of debug mode
here and I'm going to wrap this code
| | 05:50 |
inside a Try Catch block and I'll use the
IsNumeric function.
| | 05:53 |
And I'll ask, IsNumeric str1 ?
After typing the keyword, then, I press
| | 06:01 |
Enter, and I get an End If clause, and
then I'll move this code into the if-end
| | 06:07 |
if section.
Now, if the IsNumeric function returns,
| | 06:11 |
True, then everything's good, but if it
returns false, I need to handle that.
| | 06:15 |
So, I will put in a keyword called Else,
and here I will output my own error
| | 06:20 |
message, the value isn't numeric.
I will run the code, I will type in a
| | 06:27 |
numeric value, and I will click go, and I
see a successful result.
| | 06:33 |
Then, once again I will type in a string
value.
| | 06:35 |
And click Go again, and I get back my
error message.
| | 06:39 |
The value isn't numeric.
So that's how you convert from a string
| | 06:42 |
to a number using the parse method, and
from a number to a string using the two
| | 06:47 |
string method.
Now lets do an example of converting from
| | 06:51 |
one numeric data type to another.
I'll move the cursor down below the if
| | 06:55 |
end if section, but still staying within
this subroutine, and I'll add a new bit
| | 06:59 |
of code where I take an integer value and
convert it to a double.
| | 07:03 |
So, I'm going from less precise to more
precise, and I'm widening the value.
| | 07:08 |
I'll create a variable called dbl2, and
I'll set its data type to double.
| | 07:13 |
And I'll simply assign int1, then I'll
output the value, upending it to a label
| | 07:19 |
of the value of double 2 is.
I'll run the code, I'll click the go
| | 07:23 |
button, and I get the value of double 2
is 55, so the value is retained.
| | 07:28 |
And I didn't have to do anything special
to do the conversation because I'm
| | 07:32 |
widening the value.
Now I'll do a narrowing conversion.
| | 07:36 |
I'll declare a variable called byte2 and
I'll set its data type to Byte and I'll
| | 07:41 |
call the method convert.Tobyte, and I'll
pass in the value of int1.
| | 07:46 |
Now as long as the value of the integer
is within the range of the byte, it's
| | 07:50 |
going to work fine.
I'm going to copy and paste this output line.
| | 07:54 |
And I'll change both he label and the
value the I'm converting.
| | 07:58 |
I'll say that the value of byte2 is
byte2.String.
| | 08:02 |
I'll run the code, I'll click the button
and there's the result.
| | 08:05 |
It still works.
But let's see what happens if the
| | 08:08 |
original value of the integer was 256,
one more than the available range of the
| | 08:14 |
byte data type.
Now I would get an error.
| | 08:17 |
So, I'm going to wrap this code inside a
try catch block.
| | 08:20 |
And just as I did before if I get into
the exception section, I'll output the
| | 08:25 |
error message.
But this time I'll use the error message
| | 08:28 |
that's been reported by the convert class
using this expression.
| | 08:32 |
Output ex.Message.
Ex is a variable that's declared in the
| | 08:38 |
catch clause.
I'll run the code.
| | 08:40 |
I'll click the button and I get that the
error message value was either too large
| | 08:45 |
or too small for unsigned byte.
So, that's a look a various ways of doing conversions.
| | 08:51 |
From numbers to strings, from strings to
numbers and between different numeric
| | 08:55 |
data types.
For numeric conversion, use the convert
| | 08:59 |
classes methods rather then the older
built in functions and for strings and
| | 09:03 |
numbers use parse and ToString.
| | 09:06 |
| | Collapse this transcript |
| Working with strings, words, and characters| 00:00 |
The string data type is one of the most
commonly used in your programming code.
| | 00:05 |
When you declare a variable and set the
data type as a string, it can only
| | 00:09 |
contain a string.
I'm working in the project strings; and
| | 00:13 |
within the run code subroutine I'll
declare a new variable named Hello, and
| | 00:18 |
set its new data type as string.
And I'll set a value of Hello from Visual
| | 00:23 |
Basic, then I'll output that value using
the Hello function.
| | 00:28 |
I'll run the application and test, and
there's the result.
| | 00:32 |
When you declare a variable as a string
and you assign a literal string as I'm
| | 00:36 |
doing here, what you're really doing is
creating an instance of the string class.
| | 00:41 |
And you can use alternative notation that
makes that a little bit more clear.
| | 00:46 |
I'll go into full screen mode since I'll
be adding some more code, and I'll add a
| | 00:49 |
new variable called Howdy.
Once again, I'll set its datatype as string.
| | 00:54 |
And this time, I'll use the keyword New
and the constructor method of the String class.
| | 01:00 |
The nature of a constructor method in
object-oriented programming is that it
| | 01:04 |
has the same name as the class it belongs
to, and it returns an instance of that class.
| | 01:09 |
This notation in Visual Studio tells me
that there are three different versions
| | 01:13 |
of the constructor method for this class.
One that receives an array of characters,
| | 01:18 |
one that receives a single character and
then a numeric value.
| | 01:22 |
And it pads the value with multiple
instances of the character, and one that
| | 01:26 |
takes an array of characters and then
parses it using a starting index and a length.
| | 01:31 |
I'm going to use the first constructor
method.
| | 01:33 |
But instead of passing in an explicit
array of characters, I'll simply pass in
| | 01:38 |
another string, Howdy, and then I'll
output the value.
| | 01:44 |
And I'll see that that outputs exactly
the same.
| | 01:46 |
When you use this syntax, your taking a
literal string, converting it to an array
| | 01:51 |
of characters and then back to a string
again.
| | 01:54 |
So essentially, a string is just an array
of characters.
| | 01:57 |
We're getting a little bit ahead of
ourselves right now talking about arrays,
| | 02:01 |
but its important to understand the basic
nature of an array.
| | 02:04 |
An array is an ordered set of data,
whatever order its put it in, it stays in
| | 02:10 |
that order until you the programmer
change it.
| | 02:13 |
And I'm going to break up these strings
into arrays in a couple of different ways.
| | 02:17 |
First, I'll describe how to take a
string, Hello, from Visual Basic and
| | 02:21 |
break it up into an array of words.
You do this using a method of the string
| | 02:26 |
class called split.
I'll declare a new variable named Words,
| | 02:30 |
and set its data type as Array.
And I'll get its value from calling the
| | 02:35 |
Hello variable's Split method.
The Split method by default looks for
| | 02:40 |
spaces, and wherever it finds a space
character, it breaks up the strings.
| | 02:45 |
So, I should get back an array of four
words.
| | 02:48 |
To test this, I'm going to loop through
the array.
| | 02:51 |
And once again, this will be new syntax
that I haven't shown previously.
| | 02:54 |
I'm going to use a statement called, For
Each.
| | 02:58 |
I'll type in For Each, and then I'll
create a new variable called word, and
| | 03:03 |
I'll set an explicit data type as String.
And I'll get the value by using a keyword
| | 03:08 |
called In, and then I'll pass in the
array words.
| | 03:13 |
When I press Enter, the keyword Next is
added.
| | 03:16 |
This is a looping construct.
It'll loop through the array and for each
| | 03:20 |
word it finds, that is for each string it
finds after parsing, it'll execute the
| | 03:25 |
code between the For and Next.
So, I'll use the output method and pass
| | 03:31 |
in the word variable.
Now, when I run the code, I'm breaking up
| | 03:35 |
that original string into four separate
values.
| | 03:39 |
You can also break up a string into
individual characters.
| | 03:42 |
You do this by calling a method of the
string class called To Char Array, and it
| | 03:47 |
looks like this.
I'll create a new variable that I'll call Letters.
| | 03:51 |
And once again I'll set its data type as
an array, but this time I'll be specific.
| | 03:56 |
It's an array of characters.
The notation for this is the data type
| | 04:00 |
followed by a beginning and ending
parenthesis.
| | 04:03 |
And I'll get its value using the Howdy
variable, and I'll call its method ToCharArray.
| | 04:09 |
Just as I did with the words array, I'll
loop through the result and output each
| | 04:14 |
element on a single line.
This time the code will be For Each
| | 04:18 |
letter As Char In letters, and I'll
output the letter.
| | 04:22 |
And here's the result, the letters output
one line at a time.
| | 04:34 |
Finally, I'll show you a little bit about
how to format numeric values.
| | 04:38 |
Visual Basic has a couple of built-in
functions, called format and format
| | 04:43 |
currency that you can use to take strings
or numbers, and apply specific formatting.
| | 04:49 |
I'll create a variable called numeric and
I'll set its data type as decimal, and
| | 04:53 |
I'll give it a value of 45,000.
Notice, when I type in the numeric
| | 04:59 |
literal, I'm not using a comma.
If I try to add a comma it would cause an exception.
| | 05:05 |
A numeric literal can't have any commas
or spaces.
| | 05:09 |
Next, I'll declare a string that I'll
call str\numeric.
| | 05:13 |
And I'll set its value using the format
function.
| | 05:16 |
The format function takes two arguments,
the value you want to format and a style
| | 05:23 |
also known as sometimes as a mask.
I'll type in a value as a string of 0,000.
| | 05:30 |
I'll close the string, and close the
format function.
| | 05:33 |
And then, I'll output the result using
Output(strNumeric).
| | 05:39 |
There's the code, and here's the output.
45,000 with a comma.
| | 05:49 |
Now, you can learn all about the
different styles or masks that you can
| | 05:53 |
use in the format function; but
frequently, you need to output currency values.
| | 05:58 |
And there's actually a special function
for that called Format Currency.
| | 06:03 |
I'll move the cursor down below this
code, and I'll add a new variable called strCurrency.
| | 06:10 |
Once again, it's a string, and I'll get
its value by calling Format Currency and
| | 06:16 |
I'll pass in the numeric value.
I'll output it, I'll run the application
| | 06:27 |
and here is the result, a formatted
currency value.
| | 06:31 |
The strcurrency function can be used for
dollar values such as I'm doing here, or
| | 06:36 |
for other international currency formats.
So that's a brief look at the string class.
| | 06:42 |
to learn more about what you can do with
the string class, look at the documentation.
| | 06:47 |
I'll click into the word string and press
F1, that takes me into my browser to the
| | 06:52 |
string data type.
And here you can learn all about the
| | 06:55 |
different things you can do with strings,
including manipulating, concatenating,
| | 07:00 |
parsing, and otherwise working with them
as you need to in your application.
| | 07:04 |
| | Collapse this transcript |
| Working with dates and times| 00:00 |
I've previously described how to work
with strings and numbers, and now I'll
| | 00:04 |
move to the third most popular data type,
dates.
| | 00:08 |
In Visual Basic, a date value contains
both the date and the time, and there's a
| | 00:13 |
variety of ways of creating date
variables.
| | 00:16 |
I'm working in a project called Dates,
and I'll add some code to the run code method.
| | 00:22 |
I'll declare a new variable and I'll set
its data type as date.
| | 00:27 |
The Visual Basic date data type is an
alias for an underlying data type that's
| | 00:33 |
a part of the run time.
If you're working in the Dot Net
| | 00:36 |
Framework, date means date time, and if
you're working in Windows RT, it
| | 00:41 |
sometimes means date time offset.
But in your Visual Basic code, you can
| | 00:47 |
always use date as your data type.
Here is one way of constructing a new
| | 00:52 |
date value.
I'll create an instance of the date
| | 00:55 |
class, using the key word new, and then,
just as I did in an earlier video for the
| | 01:00 |
string class, I'll use a constructor
method.
| | 01:03 |
The date is stored internally as a
numeric value.
| | 01:07 |
As it shows here, the number of 100
nanosecond intervals since January 1st,
| | 01:13 |
0001 at midnight.
If you know the specific value, you can
| | 01:18 |
pass it into the constructor method.
More commonly, though, you'll want to
| | 01:22 |
work with familiar values like years,
months, dates, hours, minutes, and seconds.
| | 01:28 |
And so the date class provides a number
of different constructor methods.
| | 01:33 |
Here's another one that looks for ticks.
But here's a useful one, a constructor
| | 01:37 |
method that asks for the year, the month,
and the day as integers.
| | 01:41 |
So I'll type in 2012 for the year, 1 for
the month and 13 for the day.
| | 01:48 |
In some programming languages such as
Java, month values are offset so that 0
| | 01:54 |
means January, 1 means February and so
on.
| | 01:58 |
But in Visual Basic, we start counting at
1.
| | 02:00 |
So 1 here means January, and this value
taken together is January 13, 2012.
| | 02:07 |
I'll use the output method and I'll pass
in my date variable, and when I run the
| | 02:14 |
application, I'll see that the value is
correctly created.
| | 02:18 |
1/13/2012.
Here's a second way of creating a new
| | 02:22 |
Date variable.
I'll create another variable, which I'll
| | 02:26 |
call d2.
I'll set its data type, and this time I'm
| | 02:31 |
going to use something called a date
literal.
| | 02:34 |
Date literals are values wrapped in hash
marks or pound signs and they are
| | 02:39 |
strictly formatted date values with the
month and the day and a four digit year,
| | 02:44 |
so if I type in 11/28/1974 that will be
November 28th, 1974.
| | 02:53 |
Once again, I'll output the value, and
there's the result.
| | 02:58 |
Date literals have to be in exactly this
format.
| | 03:01 |
You can't, for example, use a 2 digit
year, and if you try to, Visual Studio
| | 03:06 |
will correct you.
For example, I'll remove the 19, move the
| | 03:10 |
cursor off that line, and Visual Studio
switches it right back again.
| | 03:14 |
Visual Studio follows its own rules for
when to fix this value with 19 or 20.
| | 03:20 |
So for example, if I type in 12 or 13, a
lower number, and then move the cursor
| | 03:26 |
off the line, Visual Studio fixes that
and makes it 20.
| | 03:30 |
I'll switch it back to 1974, using a four
digit year.
| | 03:36 |
Here's a third way of constructing a date
variable.
| | 03:39 |
Using a method of the date class called
Parse.
| | 03:42 |
It looks like this.
I'll create a new variable called D3,
| | 03:47 |
once again I'll set as a date and I'll
call the method date .Parse and I'll pass
| | 03:54 |
in a string.
There are number of different string
| | 03:57 |
formats that are supported but to keep it
simple I'll pass in the simplest sort of string.
| | 04:02 |
Once again, 11/28 and this time 1913.
And I'll output that value.
| | 04:14 |
And there's the result.
One of the advantages of using the parse
| | 04:17 |
method over a date literal is that you
can use a two digit year.
| | 04:22 |
So I'll remove this value and now when I
rerun it the date is evaluated as ten
| | 04:27 |
eleven twenty thirteen.
Now the evaluation of whether to prepend
| | 04:32 |
19 or 20, depends on the run time, not on
Visual Studio.
| | 04:38 |
When you use the parse method, you can
also add in time values.
| | 04:42 |
I'll create another new variable which
I'll call dt1 for date and time, and I'll
| | 04:49 |
set it as a date, and I'll create it
using this syntax date.parse, and I'll
| | 04:55 |
pass a November 28, 2013, 11:10 a.m.
Then I'll output it.
| | 05:04 |
When I run the code and I click Go,
there's the result.
| | 05:07 |
The full date and time.
Even though I'm using the Date class,
| | 05:11 |
rather than the .NET framework's DateTime
class, I'm still storing the entire date
| | 05:17 |
and time value.
Next lets talk about formatting dates.
| | 05:21 |
The format function which I described how
to use in an earlier movie when I was
| | 05:25 |
talking about numeric values can also be
used to format dates.
| | 05:29 |
I'll create a new variable which I'll str
date one and I'll data type it as a string.
| | 05:37 |
I'll set the value of strDate1, using the
format function, and I'll pass in dt1, my
| | 05:43 |
date time object.
And then I'll pass in a style, or a mask,
| | 05:47 |
of MMM.
That's a month value in three characters.
| | 05:52 |
Then dd, yyyy, and then I'll output that
value.
| | 06:04 |
Here is the result, a formatted string.
Take a look at the documentation for the
| | 06:08 |
Format function for different ways that
you can format dates and times.
| | 06:13 |
You can also set a date using properties
of the date class called today and now.
| | 06:19 |
The difference between today and now is
that today returns the current date and
| | 06:23 |
now returns the current date and time.
I'm going to put together a longer
| | 06:28 |
statement here that combines my custom
output method, the use of the today
| | 06:33 |
property of the date class, and a custom
formatting string.
| | 06:38 |
I'll start with Output, then I'll pass in
Format, then Date.Today, and then a
| | 06:44 |
formatting string of simply MMM dd with
no year.
| | 06:51 |
I finish up the statement with a couple
of closing parenthesis and now when I run
| | 06:55 |
the code I get the current date without
the year.
| | 06:58 |
Finally, I'll show how to do a little bit
of date math.
| | 07:03 |
I'll work with my D1 variable, which is
originally set to January 13th.
| | 07:09 |
I'll start by outputting original date,
and then I'll append to that D1 dot 2 string.
| | 07:19 |
The original date shows up now 1/13/2012,
at midnight.
| | 07:24 |
Next, I'm going to do a little bit of
math.
| | 07:27 |
I'm going to add one day and one month to
that date value.
| | 07:31 |
We do this by using methods of the Date
class called AddDays, AddMonths,
| | 07:35 |
AddYears, and so on.
When you call these methods, they'll
| | 07:39 |
return a new instance of the date class.
So to use it, I'll say d1 = d1.AddDays,
| | 07:44 |
now passing a value of 1.
Then I'll do the same thing calling d1.AddMonths.
| | 07:58 |
Then I'll output the value, with a label
of New Date, and there's the result.
| | 08:12 |
The original date was January 13th, and
the new date is February 14th.
| | 08:19 |
So with all these tools available, you'll
find that you can do enormous amounts of
| | 08:23 |
work in Visual Basic.
Working with dates, manipulating them,
| | 08:26 |
formatting, parsing, and otherwise making
them a part of your application.
| | 08:32 |
| | Collapse this transcript |
|
|
4. Exploring Syntax and FlowUsing Visual Basic operators| 00:00 |
Visual Basic supports a variety of
operators.
| | 00:04 |
An operator is a character or a string of
characters that cause a particular
| | 00:08 |
behavior in your programming.
There are many different kinds of
| | 00:11 |
operators listed here, from mathematical
operators, to comparison, to
| | 00:16 |
concatenation assignment and logical.
We'll start with Arithmetic.
| | 00:20 |
Visual Basics arithmetic operators for
the most part are conventional
| | 00:25 |
mathematical symbols.
The plus operator is used for addition,
| | 00:28 |
and as I've shown previously, it's also
used for string concatenation, that is
| | 00:33 |
for putting two or more strings together.
The other simple mathematical symbols are
| | 00:38 |
the dash or the hyphen for subtraction.
The asterisk for multiplication, and the
| | 00:44 |
forward slash for division.
You also can use the carrot symbol for
| | 00:49 |
exponentiation, that is for doing power
operations, and the back slash for
| | 00:54 |
integer division.
In this example, you divide one value by
| | 00:57 |
another, and the return value is the
integer without the remainder.
| | 01:02 |
For modulus operators, use the string
mod, mod.
| | 01:05 |
The modulus operator returns the
remainder of an integer division operation.
| | 01:11 |
To assign values, you always start with
the equals operator.
| | 01:15 |
As I've shown in previous movies, you set
values in a variable by assigning it with
| | 01:20 |
the equals operator and putting the
variable on the left and the value or
| | 01:24 |
expression on the right.
The equals operator works exactly the
| | 01:27 |
same with strings, numbers, dates, and
complex objects.
| | 01:34 |
For more complex assignments you can
combine mathematical or concatenation
| | 01:39 |
operations with the assignment in a
single operator.
| | 01:42 |
For example the plus equals operator is
used for both concatenation and addition
| | 01:48 |
combined with assignment.
In this example I start with a simple
| | 01:52 |
value and then I append another string
value.
| | 01:56 |
Math works pretty much the same way,
start with a numeric value and then add
| | 02:01 |
another value.
When you use mathematical operators and
| | 02:05 |
you're combining two values on either
side of the operator, the two values
| | 02:09 |
should be compatible in terms of type.
That is, add integers to integers,
| | 02:14 |
doubles to doubles, bytes to bytes and so
on.
| | 02:18 |
Visual Basic does not support the
increment operator.
| | 02:21 |
The increment operator is the plus plus
operator, and it's found in most C style
| | 02:27 |
languages like C, C sharp, Java, and
JavaScript.
| | 02:31 |
It looks like this.
Say you started with an integer in one of
| | 02:34 |
these languages.
And it had a value of 15.
| | 02:38 |
And on the next line, the code was x++.
The result would be 16 because ++ means
| | 02:44 |
add one.
Visual Basic doesn't support this operator.
| | 02:49 |
If you try it, you'll get a compiler
error.
| | 02:52 |
So instead, use +=1.
It means exactly the same thing, and
| | 02:57 |
takes exactly one more character to type.
Here are some more mathematical
| | 03:01 |
assignment operators that you can use
that combine mathematical operations with assignment.
| | 03:07 |
I've mentioned plus equals for addition
or concatenation.
| | 03:09 |
And there's also minus equals, times
equals, divide equals and integer divide equals.
| | 03:19 |
As you get into conditional code, that
is, if then statements, you'll need to
| | 03:23 |
put together what we call logical
expressions.
| | 03:26 |
Expressions the evaluate to either true
or false, and it's very common to create
| | 03:31 |
these logical expressions by comparing
two values to each other.
| | 03:35 |
To do this you'll use comparison
operators.
| | 03:38 |
First let's start with the numeric
comparison operators, operators that are
| | 03:43 |
used to compare numbers to each other.
The equals operator, in addition to being
| | 03:48 |
used for a simple assignment, is also
used for equality.
| | 03:52 |
In C style languages the two operators
are different.
| | 03:55 |
A single equals character is for
assignment and two equals characters are
| | 04:00 |
for comparison.
But in Visual Basic they're the same.
| | 04:03 |
For inequality, use a combination of the
less than and the greater than symbol,
| | 04:08 |
once again like the mathematical
operators, we're using a common
| | 04:12 |
mathematical symbol.
You can also use the less than character
| | 04:16 |
and the greater than character, and they
mean exactly what you might expect them
| | 04:20 |
to mean.
And there's also less than or equal and
| | 04:22 |
greater than or equal.
To compare strings to each other you can
| | 04:27 |
use the same numeric comparison
operators.
| | 04:30 |
The equals operator for strict equality,
the less than, greater than, and greater
| | 04:35 |
than or equals and less than or equals
for comparing different strings to each other.
| | 04:40 |
Here's some examples.
If I'm comparing Xyz to Xyz, and they're
| | 04:44 |
the same case, then it's true.
Now I've previously mentioned that Visual
| | 04:49 |
Basic is a non-case sensitive language,
but it's only non-case sensitive in terms
| | 04:53 |
of its own syntax.
When you're comparing string values to
| | 04:57 |
each other, it's absolutely case
sensitive.
| | 04:59 |
So these two values are not the same.
Xyz in mixed case and XYZ in all uppercase.
| | 05:06 |
This comparison returns false.
Similarly when you're comparing strings,
| | 05:10 |
you will always be doing it alpha
numerically and not numerically.
| | 05:14 |
Because these values are wrapped in
quotes, they are evaluated as strings,
| | 05:17 |
and 7 is less than 9.
Therefore the overall comparison "Is 73
| | 05:22 |
less than 9" turns out to be true.
Here's an interesting comparison.
| | 05:27 |
Asking whether abc is less than abcd.
If one value is a substring of the other,
| | 05:34 |
that is the other one starts with the
first one, then the second one is said to
| | 05:38 |
be greater than the first one.
abc has fewer characters, therefore it's
| | 05:43 |
less than abcd.
You can also use an operator called Like
| | 05:48 |
to do pattern based matching with
strings.
| | 05:50 |
Here are the pattern operators that you
can use.
| | 05:53 |
Question mark represents any individual
character and an asterisk means zero or
| | 05:57 |
more characters.
The hash mark or pound sign is any
| | 06:01 |
numeric digit, and you can wrap a
character list inside brackets and it
| | 06:05 |
means any single character in the list.
Or you can prefix the character list with
| | 06:09 |
the exclamation mark and it means any
single character that's not in the list.
| | 06:13 |
Use the Like operator instead of the
Equals operator.
| | 06:16 |
And then put together the string pattern,
and place the list where you need it in
| | 06:20 |
the pattern.
The behavior of string based comparisons
| | 06:23 |
depends on a declaration called Option
Compare.
| | 06:27 |
Check the documentation about this.
It has two options.
| | 06:30 |
Either text based comparisons or binary
based comparisons.
| | 06:34 |
And depending on your comparison, it can
change the behavior.
| | 06:39 |
You can also compare objects to each
other, that is, instance of Visual Basic classes.
| | 06:44 |
The operators are called Is and IsNot,
notice that the IsNot operator does not
| | 06:50 |
have a space in the middle.
Here's an example, I'm creating an object
| | 06:53 |
called Reference1, which is an instance
of the class object.
| | 06:57 |
Then I create another variable and I
point it at Reference1.
| | 07:01 |
In some languages, this would be called a
pointer.
| | 07:04 |
In Visualbasic.net and Visual Basic 2012,
we call it a reference.
| | 07:09 |
Then, to see if these two variables are
pointing at the same object in memory, we
| | 07:14 |
use the Is operator, and this comparison
is true.
| | 07:18 |
If I wanted to find out if they weren't
equal to each other I could change it to IsNot.
| | 07:24 |
You can also evaluate the type of an
object using a combination of the TypeOf
| | 07:29 |
operator and the Is operator.
In this code I'm declaring an instance of
| | 07:34 |
the String class.
Then I'm asking whether the new object or
| | 07:38 |
the new variable is an instance of
System.String.
| | 07:42 |
System.String is the fully qualified name
of the String class.
| | 07:47 |
System is called the assembly and String
is the class name, and if this variable
| | 07:53 |
is an instance of this class then the
type of operator returns true.
| | 07:58 |
Whenever you create a logical expression
that returns true or false, you can
| | 08:02 |
reverse the logic by prefixing the
expression with the Not operator.
| | 08:07 |
For example, this says, if x is not equal
to 5.
| | 08:11 |
This syntax is functionally equivalent to
using the Inequality operator.
| | 08:16 |
That is, the less than and greater than
signs together.
| | 08:19 |
Which one you use is completely up to
you.
| | 08:22 |
You can also use the operators And and Or
to combine logical expressions together.
| | 08:27 |
In this example, I'm asking, if x equals
1 And y equals 2, then do something.
| | 08:34 |
Compared to a C style language, the And
operator is like the double ampersand.
| | 08:39 |
The And and Or operators don't do what we
call short circuiting.
| | 08:45 |
That is to say if the first expression x
equals 1 returns false, Visual Basic will
| | 08:50 |
go on to evaluate the second expression
anyway.
| | 08:53 |
If you don't want that to happen uses the
operators AndElse and OrElse.
| | 08:59 |
Replace And and Or with these and now
you'll short circuit the compound logical expressions.
| | 09:05 |
So that if x equals 1 is false you won't
go on to evaluate the second part of the expression.
| | 09:12 |
So that's a look at at most of the
operators that are available in Visual Basic.
| | 09:16 |
There are others that I haven't mentioned
here, including what are called bitwise
| | 09:20 |
operators that are used in more advanced
programming, but check the documentation
| | 09:24 |
for the details of using any of these
operators.
| | 09:27 |
And now that we have a list of the
available operators, we'll be able to use
| | 09:30 |
them in the rest of the demonstrations in
this course.
| | 09:34 |
| | Collapse this transcript |
| Evaluating conditions code with If, Then, and Else| 00:00 |
In a previous movie, I described how to
use conditional and logical operators to
| | 00:05 |
create logical expressions.
That is, expressions that return a value
| | 00:09 |
of true or false.
Once you know how to create those
| | 00:12 |
expressions, you can then write
conditional code.
| | 00:15 |
That is code that only executes when an
expression returns a value of true or false.
| | 00:20 |
I'll demonstrate this in a project called
IfThenElse.
| | 00:22 |
In this project, my data entry form has a
couple of new controls.
| | 00:28 |
I have one text input box with the name
of txtinput1 and a second text input box
| | 00:34 |
this time that has a name of txtinput2.
There's also a check box called numeric,
| | 00:39 |
and its actual programming name or
identifier is CHK numeric.
| | 00:44 |
Now I'll go to the code that executes
when the user clicks the Go button.
| | 00:48 |
I double clicked the go button and that
opened the VB code behind file.
| | 00:53 |
In the run code subroutine I've declared
three variables, two strings that get
| | 00:58 |
their values from the text input
controls...
| | 01:00 |
And one boolean variable, called
evalNumbers.
| | 01:04 |
It gets its value from the isChecked
property of the checkbox control.
| | 01:08 |
The first bit of code that I'll add will
do a simple string comparison, asking if
| | 01:13 |
two values that the user has entered
match each other.
| | 01:17 |
I'll start with the keyword If.
And then I'll put in a logical expression
| | 01:21 |
of str1 equals str2.
Whenever you use the keyword if, you must
| | 01:27 |
end that statement with then.
Now, when I press enter Visual Studio
| | 01:32 |
automatically adds an End if clause.
The If statement always has to end with
| | 01:38 |
End If, and any code that you put between
the If and the End If will be executed
| | 01:42 |
only if the logical expression is true.
I'll add a call to my Output method, and
| | 01:48 |
I'll output the string Strings match!
I'll run the application and when I click
| | 01:56 |
the Go button the first time, I get the
response strings match.
| | 01:59 |
I haven't entered any text into the two
text boxes, so they both return empty
| | 02:04 |
strings, and therefore they're
equivalent.
| | 02:07 |
Now, I'll type my name into both text
boxes.
| | 02:09 |
I'll clear the response and then click go
again, and once again I get strings match.
| | 02:15 |
The two values match.
But if I change the second value, say
| | 02:20 |
from David to Joe, and then clear my
output and click Go, nothing happens.
| | 02:25 |
That's because I haven't added any code
that will execute in the other condition.
| | 02:31 |
That is when the condition is false.
So I'll go back to Visual Studio and I'll
| | 02:35 |
add a bit more code.
To handle the other condition, the false
| | 02:39 |
condition, use the keyword Else.
Within an if statement, you can have one
| | 02:45 |
else statement, and I'll just do another
bit of output, strings don't match...
| | 02:52 |
Now, if I type two values in and click
the go button, I get the alternative case.
| | 02:59 |
You can also add pauses called ElseIf.
ElseIf's go after an if but before the
| | 03:04 |
else, and you can have as many as you
need.
| | 03:07 |
For example, let's say I wanted to
evaluate the two strings and see if one
| | 03:10 |
was greater than or less than the other.
I'll place the cursor after the first
| | 03:16 |
output, and then I'll add ElseIf.
Notice that elseif is a single word.
| | 03:21 |
It's not two separate words, else space
if.
| | 03:24 |
This is its own conditional statement.
Its syntax is just like if.
| | 03:29 |
You have to follow it with a conditional
expression, and then the keyword then.
| | 03:32 |
And I'll ask the question, ElseIf str1 is
greater than str2, and if that's the case
| | 03:38 |
I'll output string 1 is greater than
string 2.
| | 03:43 |
And I'll change the output in the Else
clause to string 2 is greater than string 1.
| | 03:47 |
Because now, I have three possible
conditions, a match, string 1 greater
| | 03:52 |
than string 2 or string 2 greater than
string 1.
| | 03:57 |
I'll type a value of string 1, and string
2, and click Go.
| | 04:01 |
And I get string 2 is greater than string
1.
| | 04:03 |
Then I'll change the values, and click Go
again.
| | 04:07 |
And there is the response.
Next let's see what happens when you use
| | 04:12 |
if and else statements on numbers.
And also, how you can next if else
| | 04:17 |
statements within each other.
I'll go to my code and place the cursor
| | 04:20 |
after the existing conditional code
block, then I'll add a new code block and
| | 04:25 |
I'll first find out whether the user has
entered valid numbers.
| | 04:29 |
I'll examine evalNumbers.
The evalNumbers variable is already a
| | 04:35 |
Boolean, that is, it's already guaranteed
to return a true or a false value.
| | 04:40 |
So I don't have to compare it to anything
else.
| | 04:42 |
If evalNumbers is true, then I'll ask
another question.
| | 04:47 |
And I'll use the IsNumeric function, that
I described in a previous video.
| | 04:51 |
I'll ask if IsNumeric str1 and is numeric
str2.
| | 05:01 |
If both strings are numeric, then I can
do numeric evaluations on them.
| | 05:06 |
And if they aren't, I can't.
So I'll add an else clause, and output
| | 05:11 |
the message, strings can't be converted
to numbers.
| | 05:15 |
Now, if the values can be converted, I'll
convert them, then compare them.
| | 05:19 |
So inside the If clause, I'll declare a
couple of new variables.
| | 05:24 |
The first one will be called dbl1 and
it'll be a double value.
| | 05:27 |
And I'll get it's value by calling
Double.Parse and I'll parse str1.
| | 05:35 |
Then I'll copy and paste that code and
I'll change the second one so that I'm
| | 05:40 |
creating a new variable called dbl2.
I now have two numeric values I can match
| | 05:46 |
and I'll yet another nested conditional.
I'll ask if dbl1 matches dbl2 and if so
| | 05:54 |
I'll output the message numbers match.
Then, just as I did with strings, I'll
| | 06:05 |
handle the other conditions.
If dbl1 is greater than dbl2, then I'll
| | 06:12 |
output Value 1 is greater than value 2.
In the Else clause, I'll copy and paste
| | 06:18 |
that message, and change it to say that
value 2 is greater than value 1.
| | 06:23 |
I'll scroll down a bit so we can see this
entire conditional block starting with
| | 06:27 |
this if statement and ending with its
matching end if.
| | 06:31 |
So we have three if then statements.
First asking if the user wants us to
| | 06:36 |
evaluate numbers then checking if they've
entered values that can be converted into numbers.
| | 06:42 |
And then, the most deeply nested code,
that's comparing the values, and seeing
| | 06:47 |
whether they match.
I'll run the code, and first, I'll once
| | 06:52 |
again type in values, and check the
numeric checkbox, but I haven't entered
| | 06:56 |
values that can be parsed as numbers.
And I can get the expected message,
| | 07:01 |
strings can't be converted to numbers.
I'll clear the output, and change the
| | 07:05 |
values so that they match.
I'll click Go, and I'll see that the
| | 07:09 |
strings match and the numbers match.
But now, I'll type in values that can be
| | 07:14 |
converted to numbers but don't match and
I'll see the response.
| | 07:18 |
And I'll see that string 2 is greater
than string 1 but value 1 is greater than
| | 07:23 |
value 2.
That's because when we're evaluating
| | 07:26 |
these as numbers, 73 is greater than 9.
But when evaluating as strings, 9 is
| | 07:32 |
greater than 73, because the initial
character 9 is a higher number than 7.
| | 07:37 |
So that's a look at how to use If, Then,
Else and ElseIf.
| | 07:43 |
You can use them in any combination you
need to.
| | 07:45 |
You can nest If statements within each
other, and you can use these statements
| | 07:50 |
to evaluate any logical expression.
| | 07:53 |
| | Collapse this transcript |
| Using the Select...Case statement| 00:00 |
As I previously described, you can write
conditional code using the keywords If,
| | 00:05 |
Then, Else and Elseif, but in some
circumstances you might be better off
| | 00:11 |
with a construct called Select Case.
I'm working in a project called Select
| | 00:15 |
Case and in this version of my form, I've
added a set of radio buttons.
| | 00:20 |
There content or label, r add subtract
multiply and divide, and they each have
| | 00:25 |
an identifier or name starting with opt,
for option.
| | 00:29 |
I'll go to the Visual Basic code behind
file and look at it in full screen and
| | 00:33 |
show that I've added some existing code.
When the user clicks the Go button,
| | 00:39 |
here's what's happening so far.
At the top of the code, I've declared
| | 00:42 |
four variables.
As before, the two strings come from the
| | 00:46 |
text input controls.
And then I've declared two double
| | 00:49 |
variables, but I haven't assigned them
values.
| | 00:52 |
When you initially declare a raw number,
such as a double or an integer, if you
| | 00:56 |
don't initialize its value, it'll have a
default value of 0.
| | 01:01 |
So up to this point dbl1 and dbl2 are
both zero.
| | 01:05 |
On the next line I'm clearing the output
text control.
| | 01:09 |
Then using IsNumeric I'm checking to make
sure that the user has entered numeric
| | 01:14 |
values, and if so I pass those values and
assign then to dbl1 and dbl2.
| | 01:20 |
If the user didn't enter a numeric value
into either of the text controls, I'll
| | 01:25 |
output an error message and then use the
Return statement.
| | 01:29 |
Return means stop executing this
sub-routine, and so I won't continue
| | 01:34 |
executing the rest of the code if that's
the case.
| | 01:36 |
But if I succeed, I now have two numbers
to work with.
| | 01:40 |
The next thing is to find out what the
user wants me to do.
| | 01:43 |
What the operation will be.
And here's where I'll examine which radio
| | 01:47 |
button is selected.
By default none of the radio buttons are
| | 01:51 |
currently selected.
So I declare a variable called operation.
| | 01:54 |
And set it's value to none.
But then I check the radio buttons one at
| | 01:59 |
a time and I"m checking there is checked
properties.
| | 02:02 |
IsChecked is bullion value so I can use
it in an if then statement and for
| | 02:07 |
example of the add button is checked then
I set that operations string to a value
| | 02:12 |
of add.
Notice I'm only declaring the operation
| | 02:15 |
variable once at the top of this block.
If I tried to use dim operation again, I
| | 02:21 |
would get a compiler error.
Within the current scope, you can only
| | 02:24 |
declare the variable once.
So I'm handling all four buttons for
| | 02:29 |
adding subtracting multiplying and
dividing.
| | 02:31 |
And setting the operation variable
appropriately.
| | 02:34 |
And then outputting, to tell the user
what they selected.
| | 02:38 |
I'll try the code so far.
Running the application by pressing F5.
| | 02:41 |
If I simply click the Go button without
entering any values, I get the error
| | 02:47 |
message, Please enter valid numbers!
So, I'll enter valid numbers I'll enter
| | 02:53 |
five and ten and then I'll click the Go
button again, and it tells me that the
| | 02:57 |
selected operation is none.
So then I'll click the Add button and
| | 03:01 |
click Go again, and I see that I've
selected Add, and I'll test one or two of
| | 03:06 |
the other radio buttons.
So that's the code that's in the
| | 03:09 |
application so far.
Now to get to the point of the exercise.
| | 03:13 |
Using the Select Case statement.
You use Select Case when you are
| | 03:17 |
evaluating a variable and it has one of a
number of different possibilities.
| | 03:22 |
I'll place the cursor after this output
call and move the code up a little bit
| | 03:27 |
and I'm going to declare a new variable
called result.
| | 03:31 |
My goal is to execute a mathematical
operation and assign the result to this variable.
| | 03:37 |
Just as before, the default value is
zero.
| | 03:40 |
Next, I'll add the Select Case statement.
I'll type in Select Case, and I'm asked
| | 03:47 |
for the test expression, the variable
that I'm evaluating.
| | 03:50 |
And I'll type in, Operation.
When I press Enter, Visual Studio adds an
| | 03:56 |
end select clause.
Now I can add one or more case statements
| | 04:01 |
within the select.
Each case statement can look for one or
| | 04:05 |
more values.
So for example if I want to look for add
| | 04:09 |
I type Case Add.
The data types that are supported here,
| | 04:14 |
include strings, all of the numeric data
types, such as double, integer, short,
| | 04:20 |
and so on.
And any other built in data types that
| | 04:23 |
are a part of Visual Basic.
Next I'll add one or more lines of code
| | 04:28 |
that I want to be executed, if the value
of operation is app.
| | 04:32 |
And I'll react to that by saying result
equals dbl1 + dbl2.
| | 04:38 |
I can add as many lines of code as I want
here and they'll be executed as long as
| | 04:43 |
they fall before the next Case statement.
Next I'll add another Case statement and
| | 04:48 |
I'll look for the value Subtract.
And this is going to be almost exactly
| | 04:53 |
the same.
I'll just copy this code and paste it
| | 04:56 |
into place and change the operator from a
plus to a hyphen.
| | 05:01 |
And then I'll copy the entire subtract
section and paste that in twice, and I'll
| | 05:06 |
use those for multiplication and
division.
| | 05:10 |
For multiplication I'll use the asterisk
and for division the forward slash.
| | 05:19 |
Now if none of those cases return true,
that means that the user didn't select an operation.
| | 05:27 |
I could look for the word none but I 'd
like to show you how to use Case Else.
| | 05:32 |
Case Else is the catchall.
It's the code that will execute if none
| | 05:37 |
of the cases matched up.
I'll type Case Else and I'll output an
| | 05:42 |
error message.
And then as I did before, I'll use the
| | 05:50 |
return statement.
Again when I call return it means I don't
| | 05:56 |
want to continue executing the rest of
this code.
| | 05:59 |
Now I'm moved down to beyond the end
select and if I get down to this point,
| | 06:04 |
I'll know that a result was found.
So I'll output it and I'll start with a
| | 06:09 |
string of the result is and I'll append
to that result.ToString.
| | 06:16 |
So there's all my logic.
I start by declaring a variable type as a
| | 06:20 |
double, I do a select case and examine
the value of the operation variable and
| | 06:25 |
look for each of the possible values.
Add, subtract, mulitply and divide.
| | 06:30 |
If I get to the Case Else, that means the
user didn't select a valid operation and
| | 06:34 |
I tell them so.
But if I get past the Case Else I can
| | 06:38 |
then assume that a result was found and
output it.
| | 06:42 |
I'll test the application and I'll type
in a value of 20 and a value of ten.
| | 06:48 |
When I click go I get the message, you
didn't select an operation.
| | 06:52 |
So I'll choose an operation and click Go
and there's the result so now I can add,
| | 06:57 |
subtract, multiply and divide.
The Select Case statement can let you
| | 07:04 |
concisely and efficiently evaluate a
single variable and compare it to one of
| | 07:09 |
many options.
There's one more important thing to know
| | 07:13 |
about the Select Case statement in Visual
Basic.
| | 07:16 |
If you've worked in C style languages
such as Java or C # you might be familiar
| | 07:20 |
with the Switch statement.
The structure of Switch is very closely
| | 07:24 |
related to Select Case.
It starts off with Switch instead of
| | 07:28 |
Select Case and then it evaluates
multiple options.
| | 07:31 |
But in the C style languages, when you
get into the code within a case, the code
| | 07:36 |
will continue executing throughout the
rest of the Switch statement, even if the
| | 07:40 |
rest of the case's values don't match.
To stop that from happening, you have to
| | 07:44 |
put in a keyword called, Break, which
means, I'm finished executing this switch statement.
| | 07:50 |
In Visual Basic, that's not required.
Once you have a match with a particular
| | 07:54 |
case Only the code for that case will be
executed.
| | 07:57 |
And when that code is done the flow will
jump to the end select and then continue
| | 08:02 |
executing from there.
So the result is pretty much the same and
| | 08:06 |
the capabilities are the same but the
rules are subtly different.
| | 08:10 |
In Visual Basic only the code for a
single case can be executed, and once
| | 08:15 |
that case has been matched all the others
will be ignored...
| | 08:19 |
| | Collapse this transcript |
| Repeating code blocks with loops| 00:00 |
Looping or iterating through code means
that you create a block of code and then
| | 00:04 |
execute it multiple times.
How many times you execute it depends on
| | 00:09 |
various conditions.
In Visual Basic, you can create looping
| | 00:13 |
constructs using keywords like for,
while, do, for each, and exit.
| | 00:19 |
I'll demonstrate some of these constructs
in the loops project, and I'll start with
| | 00:23 |
the for loop code, which I'll place into
the MainWindow.xml.vb file.
| | 00:28 |
In the beginning file, I've created a
bunch of sections, each with a label
| | 00:31 |
indicating what kind of code I'll be
adding.
| | 00:35 |
I'll look at the code in fullscreen and
scroll down.
| | 00:38 |
And show that I have sections for, for
loops, while loops, do loops, infinite
| | 00:43 |
dos, and for each.
I'll start with the for loop.
| | 00:47 |
You can use the for loop to loop while
watching a counting value.
| | 00:51 |
The syntax looks like this.
Start with the keyword for and then
| | 00:55 |
declare a variable.
Typically, it'll be an integer value, but
| | 00:59 |
you can use any other numeric data type.
I'm going to declare a variable called
| | 01:03 |
forCount, and I'll set its data type As
integer.
| | 01:08 |
The next step is to set beginning and
ending values.
| | 01:11 |
Put in an assignment operator, equals,
and then set the low value, then the
| | 01:17 |
keyword too, and the high value.
When you press Enter, Visual Studio adds
| | 01:22 |
the keyword next.
Now any code that you add between for and
| | 01:26 |
next will be executed.
At the end of the loop, the counter
| | 01:30 |
variable, forCount in this example, will
be incremented by one.
| | 01:34 |
You can change the increment value by
using the keyword step.
| | 01:38 |
For example, step two means increment by
two each time through the loop.
| | 01:43 |
The step keyword is optional though, and
by default, you'll be incrementing by 1.
| | 01:47 |
Now, I'll add just a single line of code
to execute each time through the loop.
| | 01:53 |
I'll use my output sub-routine and I'll
output for value is and I'll append forCount.ToString.
| | 02:02 |
I will test the application and click the
Go button, and there's the result.
| | 02:06 |
I'm looping and displaying the values
three times.
| | 02:10 |
You can also execute loops using the
while keyword.
| | 02:14 |
The while keyword lets you examine any
condition, not just numeric values.
| | 02:19 |
It looks like this.
Start with the keyword while, and then
| | 02:22 |
enter a Boolean condition.
I've declared a variable called
| | 02:26 |
whileCount, and set it to one initially,
and I'll tell the while loop to keep
| | 02:31 |
looping as long as that value is less
than or equal to three.
| | 02:38 |
When you use the while keyword, the
ending clause for the while keyword is
| | 02:43 |
end while.
And Visual Studio will add it
| | 02:45 |
automatically when you press Enter.
Now within the loop, I'll once again do
| | 02:49 |
an output.
And I'll say while count is.
| | 02:53 |
And I'll append the value.
And then, after I've output the value,
| | 02:58 |
I'll increment the value by one.
Unlike the for loop, incrementing doesn't
| | 03:03 |
happen automatically.
In a while loop, you have to do it yourself.
| | 03:07 |
So I'll say while count equals while
count plus one, and when I run the
| | 03:14 |
application and click the Go button, I
once again get the output three times.
| | 03:19 |
The next type of loop I'll take a look
at, is called a do loop.
| | 03:22 |
Like the while loop, the do loop doesn't
have any auto incrementing.
| | 03:25 |
You have to manage all of your conditions
and values yourself.
| | 03:29 |
Start by typing the keyword Do and and
pressing Enter.
| | 03:32 |
The closing clause for the do loop is
called loop.
| | 03:35 |
I'm working with a variable called do
count, which is already declared and set
| | 03:39 |
to one.
Just as I did with the other loops, I'll
| | 03:42 |
do some output, and I'll say do count is,
and I'll output the value.
| | 03:53 |
Then I'll increment the value, with do
count equals do count plus one.
| | 03:57 |
Now, at this point, it's an infinite
loop.
| | 03:59 |
It'll keep on looping because I haven't
set any conditions.
| | 04:03 |
You can set your conditions after the
keyword loop by adding either an until or
| | 04:08 |
a while keyword.
If you use until, it examines the value
| | 04:12 |
and breaks out of the loop when the
condition is matched.
| | 04:15 |
I'll use a condition of greater than
three.
| | 04:17 |
So the first time I hit the output
command, the value will be one.
| | 04:22 |
The second time it'll be two.
The third time it'll be three, but then
| | 04:25 |
after the third output, I'll increment it
to four.
| | 04:28 |
I'll hit this until clause and the
condition will be false, and I'll jump
| | 04:33 |
out of the loop.
And here's the result, once again looping
| | 04:38 |
three times.
You can also use the do key word to do
| | 04:42 |
something called an infinite loop.
I'm going to take this much code and copy
| | 04:46 |
it to the clip board, and then I'll paste
it down here after the redeclaration of
| | 04:50 |
do count.
If you prefer, instead of using until or
| | 04:54 |
while after the loop keyword, you can
instead do your own evaluation within the
| | 04:59 |
loop and then break out of the loop using
the keyword exit.
| | 05:02 |
If you've worked in Java or C-sharp, you
might be familiar with the break statement.
| | 05:07 |
In Visual Basic, exit is very similar.
It will let you jump out of a loop very easily.
| | 05:13 |
Within the do loop, I'll place the cursor
after the code that's incrementing my
| | 05:17 |
value, then I'll add an if statement.
And my condition will be if do count is
| | 05:22 |
greater than three.
So now, to break out of the do loop, I'll
| | 05:29 |
use the keyword exit.
You can use the keyword exit to exit a do
| | 05:33 |
loop or to exit a sub routine.
I'm going to exit the do loop.
| | 05:37 |
Once again, I'll run the app and test it,
and there's the result.
| | 05:43 |
Once again looping three times.
Finally, let's take a look at the for
| | 05:48 |
each loop.
You can use the for each loop to iterate
| | 05:52 |
over the values in a data set, such as an
array.
| | 05:55 |
Here, I've declared an array of integers.
The opening and closing parentheses after
| | 05:59 |
the data type means it's an array, not
just one integer.
| | 06:03 |
And then I'm declaring the array with a
pair of braces wrapped around a comma to
| | 06:07 |
limited list.
Now to loop through those values, I can
| | 06:11 |
use for each, and then I declare an
element or a variable.
| | 06:15 |
I'll just name it i for integer.
I'll set its data type as integer, and
| | 06:21 |
then say that I'm looping in the numbers
array.
| | 06:24 |
The closing keyword for a for each loop
is next, just like the for loop and
| | 06:29 |
within the for each loop, I'll output the
current value.
| | 06:41 |
And there's the result.
Just as in the other examples, I get
| | 06:45 |
three iterations, and that's because
there are three values in the data set.
| | 06:49 |
If I add another value and run the code
again, I'll get four iterations.
| | 06:54 |
So that's a look at all the different
ways that you can loop through code in
| | 06:57 |
Visual Basic.
Choose the version of looping that makes
| | 06:59 |
sense for your programming requirement.
Fors, whiles, dos, for eaches, and exits.
| | 07:06 |
| | Collapse this transcript |
| Reusing values with constants| 00:00 |
A constant is basically a variable whose
value never changes.
| | 00:04 |
You can use constants instead of
variables in conditions where you want to
| | 00:08 |
refer to the same value multiple times
and make sure that you spelled the word correctly.
| | 00:14 |
With simple string values, it's easy to
get it wrong and introduce bugs into your applications.
| | 00:19 |
With constants, it makes the application
more bulletproof.
| | 00:22 |
I'll demonstrate the use of constance in
this project.
| | 00:25 |
Constants, this is an exercise that I did
in a previous movie, where I setup a
| | 00:30 |
simple calculation.
First, I looked at a set of radial
| | 00:34 |
buttons with ID's starting with OPT for
option.
| | 00:37 |
And looked at there IsChecked property.
And then I set a string variable to a
| | 00:41 |
value of add, subtract, multiply, or
divide.
| | 00:45 |
Then, further down in the code, I
examined an operation variable and looked
| | 00:50 |
for one of those four values.
When you use strings in this way in your
| | 00:54 |
internal programming, it's really easy to
get it wrong.
| | 00:57 |
And so, instead of using literal strings
here, I'm going to use constants.
| | 01:02 |
I'll go back to the top of my code, and
I'll add four constant declarations
| | 01:06 |
within the sub routine.
To declare a constant value, use the
| | 01:11 |
keyword Const.
The syntax looks pretty much the same as
| | 01:14 |
a string.
And if you're declaring more than one
| | 01:17 |
constant, you can declare them in a comma
delimited list, which is what I'll do here.
| | 01:21 |
There are varying conventions for how you
name constants in Visual Basic.
| | 01:25 |
But in many other programming languages,
such as C# and Java, constants are always
| | 01:30 |
spelled with all upper case.
So, that's what I'll do here.
| | 01:33 |
I'll declare a constant called add s
string and I'll give it a value of add.
| | 01:39 |
Then after a comma, I'll declare the next
one.
| | 01:41 |
Subtract as string and I'll give it a
value of subtract and then I'll create
| | 01:48 |
one called multiply.
And I'll add one called divide.
| | 02:00 |
Now the literal string values that you
assigned here don't really matter.
| | 02:03 |
They can be anything.
The key here though, is that when you
| | 02:06 |
refer to these values instead of
referring to the literal strings you will
| | 02:10 |
now refer to the constants.
I'm getting the little squiggly line
| | 02:14 |
right now because I'm not using these
constants yet, but I will now.
| | 02:18 |
I'll go back down to my code where I've
used the literal strings previously.
| | 02:22 |
And in each place where I used the
literal string, I'll now use the constant.
| | 02:26 |
I'll change the literal string add to the
constant add.
| | 02:29 |
And notice that now that I've declared
the constant, I can get auto completion
| | 02:33 |
help from Visual Studio.
I'll replace Subtract, Multiply, and
| | 02:38 |
Divide, and then I'll do the same thing
in the section where I'm looking for
| | 02:44 |
these values.
I'll replace all four in exactly the same way.
| | 02:48 |
The great thing about constants is that
if you misspell them in your code.
| | 02:59 |
For example, if I put in divide but I
forget the closing e, I'll get an error
| | 03:09 |
telling me it's not declared.
And you can easily correct it by placing
| | 03:13 |
the cursor at the end and pressing
Ctrl+Space+Enter it'll auto complete.
| | 03:17 |
Now, I'll run the application and test
out its functionality.
| | 03:23 |
I'll put in values of five and ten and
I'll add them, subtract them, multiply
| | 03:29 |
them and divide them.
So, the functionality of the application
| | 03:34 |
is exactly the same.
But with constants, your code is easier
| | 03:38 |
to maintain and less likely to have bugs
that are a result of misspelling string literals.
| | 03:44 |
| | Collapse this transcript |
| Creating reusable code with Sub and Function procedures| 00:00 |
Nearly all programming languages give you
a way of creating reusable code blocks.
| | 00:05 |
The names for these code blocks differ
from one language to another in strongly
| | 00:09 |
object oriented languages like Java or
C#, they're called methods.
| | 00:13 |
In Visual Basic, there's a generic name
for them, procedures, but there are two
| | 00:17 |
different kinds of procedures,
subroutines and functions.
| | 00:21 |
In our current application I'm already
using subroutines.
| | 00:25 |
I'm working in a version of my project
called procedures and in this application
| | 00:29 |
there's a subroutine called Run Code.
This code is executed when the user
| | 00:34 |
clicks the Go button.
There are two other subroutines and there
| | 00:37 |
names are Output and Clear output.
A Visual Basic subroutine is a reasonable
| | 00:42 |
code block that doesn't return a value.
In contrast, a procedure that does return
| | 00:48 |
a value is called a function.
To demonstrate this, I'm going to move
| | 00:52 |
some of the existing code from my run
code subroutine and place it into a
| | 00:56 |
function that returns a value.
I'll take this code, that's doing the
| | 01:00 |
calculation itself.
So let's start by creating a new function
| | 01:04 |
at the bottom of the class.
I'll move the cursor after the existing
| | 01:07 |
subroutines, and type the word function.
Then, I'll give the function a name of calculate.
| | 01:13 |
Subroutines and functions can accept as
many arguments, or parameters as you need.
| | 01:19 |
The output subroutine right now receives
a single string parameter, and clear
| | 01:23 |
output receives two parameters.
My calculate function, will receive three
| | 01:28 |
arguments or parameters.
Just as in run code, the first two will
| | 01:32 |
be the double values.
Dbl1 and Dbl2.
| | 01:35 |
You data type your arguments in the same
way you do variables, with the As keyword.
| | 01:42 |
The third argument will be the operation:
Add, Subtract, Multiply, or Divide.
| | 01:48 |
You can name the arguments anything you
like, and to demonstrate the difference,
| | 01:52 |
I'll name this argument op for operation.
And I'll set its data type to string.
| | 01:59 |
Functions return values, and you should
declare the data type of the returned value.
| | 02:04 |
You do this with the keyword as.
Before I type in the return value I'll
| | 02:08 |
put in a continuation character and go to
the next line.
| | 02:11 |
Then I'll say that the function is
returning a string with As String.
| | 02:15 |
If I press Enter Visual Studio adds end
function.
| | 02:19 |
Now all of the code that's a part of the
function will go between Function and End Function.
| | 02:25 |
I'm going to move some existing code from
run code to calculate.
| | 02:29 |
I'll take this select case statement,
copy it to the clipboard and then paste
| | 02:33 |
it into my new function.
I immediately see that there's some
| | 02:36 |
errors to deal with.
First, I'll deal with the constants: Add,
| | 02:40 |
Subtract, Multiply and Divide.
Visual Studio is telling me that these
| | 02:45 |
constants can't be found, that they're
not declared.
| | 02:48 |
I did declare them, though.
But I declared them in the other procedure.
| | 02:52 |
In the run code subroutine.
To make the constants visible to all of
| | 02:56 |
the procedures in this class, I need to
move the constant declarations.
| | 03:01 |
So I'll go back up to the top of my code
and locate my constants.
| | 03:05 |
And I'll select and cut them from their
current location and I'll place them
| | 03:09 |
outside of side of any of the procedures.
Notice that I'm pasting this code after
| | 03:14 |
the class declaration, but before the
subroutine.
| | 03:19 |
Now I'll scroll back down to my new
function, and I'll see that the errors
| | 03:22 |
for the constants have been cleared.
Next, I'll deal with this error.
| | 03:26 |
It's telling me that there's no such
value as operation, and that's because I
| | 03:31 |
named this argument op.
So I'll correct that by removing the end
| | 03:35 |
of the name and when I move the cursor
off that line visual studio clears the error.
| | 03:40 |
Next I'm being told that there is no
variable called result and that's because
| | 03:45 |
I originally declared that variable in
the run code subroutine.
| | 03:49 |
I'm going to declare it again here so
that I have a version of the variable
| | 03:52 |
that's local to the function.
Remember that when you declare a variable
| | 03:56 |
inside a function it isn't visible to the
rest of the application.
| | 04:00 |
So I'll place the cursor before the
select case statement and declare Dim
| | 04:04 |
result As Double.
And that clears those errors.
| | 04:09 |
Next I'm going to remove some of the
select case statement.
| | 04:13 |
I won't need the case else statement.
I'm going to redesign or re-factor this
| | 04:18 |
code so that I only call the calculate
function when I know I have valid double
| | 04:23 |
values and I have a valid operation.
So I'm going to remove the case else and
| | 04:28 |
then finally I'll return the result.
I'll place the cursor after the End
| | 04:32 |
Select and type in Return result.
And there's my finished function.
| | 04:37 |
You can design your own functions in your
Visual Basic code to do whatever you need.
| | 04:41 |
But again the difference between Function
and a Subroutine is that a function
| | 04:46 |
always returns a value.
Now I'll go back up to my calling code.
| | 04:51 |
I no longer need most of the select case
statement.
| | 04:54 |
I'm going to get rid of the select case
operation and the first four cases, and
| | 04:58 |
I'll also get rid of the return statement
and the End Select.
| | 05:02 |
And I'm left with two outputs, first I'll
deal with the output that says you didn't
| | 05:07 |
select an operation.
I want to output that message if the user
| | 05:11 |
didn't choose an operation, so I'm going
to move it up in my code.
| | 05:15 |
I'll cut and paste it and I'll place it
after the End If, and then I'll wrap it
| | 05:20 |
in its own conditional clause right
before this step.
| | 05:24 |
I checked my buttons to see what was
checked and what wasn't checked, and
| | 05:28 |
remembered that I had originally set
operation to a value of none.
| | 05:32 |
So, I'll check it's value here with If
operation = "None".
| | 05:38 |
And if that's the case, I'll output that
error message and return.
| | 05:43 |
And so I won't go on to do the
calulation.
| | 05:47 |
If I get to the declaration of the result
variable here, then I know that I have
| | 05:51 |
valid numeric values, and I have a valid
operation.
| | 05:55 |
So now all I have to do is say that I
want to set the value of result using my
| | 06:00 |
new calculate function.
With = Calculate, and then I'll pass in
| | 06:05 |
dbl1, dbl2 and operation.
And now I've re-factored the code so that
| | 06:12 |
the complex work, that is the calculation
itself, is in its own function.
| | 06:16 |
And it can be called from anywhere in my
application.
| | 06:20 |
I'll run the application and I'll test
it.
| | 06:23 |
I'll type in numeric values, and first
I'll click Go, and I see that I didn't
| | 06:27 |
get a valid operation.
Then I'll click Add, and I get the result
| | 06:31 |
is 15.
Subtract, multiply and divide.
| | 06:38 |
Your application can include as many
functions as are necessary.
| | 06:42 |
Use Functions and Subroutines to package
up code that you'll be calling multiple
| | 06:47 |
times, or to simply wrap or encapsulate
complex code.
| | 06:52 |
So that your code blocks don't get too
long and your application is more maintainable.
| | 06:57 |
| | Collapse this transcript |
| Building a simple calculator application| 00:00 |
Once you've learned how to work with a
variety of data types, declare variables,
| | 00:04 |
do math and create reasonable code
blocks.
| | 00:07 |
You have enough skills in Visual Basic to
build a very simple application.
| | 00:12 |
This finished application is called the
Simple Calculator.
| | 00:16 |
I'll run the application and show that it
has more of a traditional calculator user
| | 00:20 |
interface than previous exercises.
I'll type in a value of 5.
| | 00:24 |
And another value of 2.5.
And then go through the various operations.
| | 00:29 |
I'll add them together and see a result
of 7.5.
| | 00:33 |
Then I'll subtract and get 2.5 multiply
and divide.
| | 00:38 |
Then I'll change the values so that the
first value is less than the second one.
| | 00:42 |
And subtract and see that I get a result
that's now red showing that it's negative.
| | 00:47 |
And then finally I'll try a divide by
zero.
| | 00:49 |
And I get an expected error message of
divide by zero.
| | 00:52 |
So let's take a look at how all this code
is put together.
| | 00:57 |
This application is similar to a previous
exercise in that it handles four
| | 01:01 |
operations, adding, subtracting,
multiplying and dividing.
| | 01:05 |
In the earlier exercise I defined the
constants in a single statement with
| | 01:10 |
commas to separate them.
In this application I'm declaring each
| | 01:13 |
constant separately.
The functionality is exactly the same.
| | 01:17 |
It's just a difference in coding style.
Next I have a sub-routine called Calculate.
| | 01:22 |
This Calculate sub-routine receives a
single argument named Operation as a string.
| | 01:28 |
Then, within the sub-routine, it declares
four variables.
| | 01:32 |
Two strings and two double values.
The values of the strings comes from the
| | 01:37 |
text input controls in the user
interface.
| | 01:41 |
Next there's some error checking, I check
to make sure that the two strings can be
| | 01:45 |
parsed as numeric values.
And if either of those fails, I display
| | 01:49 |
an error using my own custom sub routine
display error.
| | 01:53 |
I'll get to that sub routine in a moment,
I'll continue code reviewing this sub routine.
| | 01:58 |
Next I do the calculation.
This code looks almost exactly the same
| | 02:02 |
as in the original exercise.
I have simple calculations for adding,
| | 02:07 |
subtracting and multiplying.
But for dividing there's one more error check.
| | 02:11 |
In order to check for divide by zero
errors I'm looking at the result that
| | 02:16 |
comes from the division operation.
Depending on the first value you can
| | 02:20 |
either get something called positive
infinity or negative infinity.
| | 02:24 |
If the first value, the numerator is
positive you'll get positive infinity.
| | 02:29 |
And if the first value is negative you'll
get negative infinity.
| | 02:33 |
Either way it's not the value you're
expecting.
| | 02:35 |
And so I'm checking for either using the
is positive infinity function and the is
| | 02:40 |
negative infinity function of the double
class.
| | 02:43 |
And if either of those are true because
I'm using the or keyword here then I
| | 02:47 |
display the error and return.
And finally if I get to the end of the
| | 02:51 |
calculate function and haven't hit any of
those errors then I once again call DisplayResult.
| | 02:57 |
Now let's take a look at DisplayResult.
It receives a single argument named
| | 03:02 |
result data typed as a double.
Then it displays the value by calling the
| | 03:06 |
ToString function of the result object
and assigning it to the content property
| | 03:11 |
of the label.
Then it's looking at that result value
| | 03:15 |
and asking whether it's greater than or
equal to zero.
| | 03:17 |
And this is where the adjustment of the
color of the message happens.
| | 03:21 |
I'm setting a property of the label
called Foreground and I'm using a class
| | 03:26 |
called brushes, which has constants for
various colors.
| | 03:29 |
And I'm using black and red.
Now this is code that you need to WPF.
| | 03:34 |
It would look the same in Windows 8 store
applications and in other environments
| | 03:39 |
where you use XAML.
If you're working in asp.net, the code
| | 03:43 |
would look different.
But either way, I'm setting the color
| | 03:46 |
using visual basic code.
Next there's a series of four sub routines.
| | 03:51 |
They're each being triggered by clicks of
one of the buttons.
| | 03:54 |
There's a sub routine for subtracting for
adding, for multiplying and for dividing.
| | 04:00 |
There's an interesting difference here in
how the subroutines are being called.
| | 04:04 |
The subtract subroutine is being called
as a result of some code in the XML file.
| | 04:10 |
I'll go to the XML file and look at the
code and go to the subtract button.
| | 04:16 |
It's right here.
And it has a click attribute, which is
| | 04:19 |
pointing to BTN subtract click.
But if I go to some of the other buttons,
| | 04:25 |
such as BTN divide, I don't see that
click attribute.
| | 04:29 |
And instead those subroutines are being
called because of the handles clause in
| | 04:34 |
the subroutine signature.
So here I have a subroutine called BTN
| | 04:38 |
divide click and it handles the click
event of BTN divide.
| | 04:42 |
You can hook up your event handler
subroutines either way.
| | 04:46 |
Either by setting them in the XML file or
in the Visual Basic code here.
| | 04:51 |
Finally there's a subroutine called
Display Error.
| | 04:54 |
And it's doing pretty much the same thing
as the earlier display sub routine.
| | 04:57 |
It's setting a content value and it's
setting a foreground but because it's
| | 05:02 |
always displaying an error, it always
sets the color to red.
| | 05:05 |
So now that we've reviewed the code,
we'll test it one more time.
| | 05:08 |
Now type in a variety of values.
First I'll try clicking one of the
| | 05:12 |
operator buttons without setting values.
And I get not a number.
| | 05:16 |
Then I'll type in values of 5 and 0 and
try dividing.
| | 05:20 |
And then I'll set values of 34 and 43.5
and execute all of the operations one at
| | 05:27 |
a time.
I encourage you to explore this code and
| | 05:30 |
experiment with it.
Add functionality and see what happens.
| | 05:34 |
Use this as a sandbox to test your
knowledge of Visual Basic so far and see
| | 05:39 |
what you can accomplish.
| | 05:42 |
| | Collapse this transcript |
|
|
5. Exception Handling and DebuggingCommon compilation errors| 00:00 |
There are two broad categories of errors
that you'll see in your application as
| | 00:04 |
you program.
Compile time errors and runtime errors.
| | 00:08 |
The difference is that a compile time
error prevents you from building your project.
| | 00:13 |
I'm going to describe three common
compile time errors.
| | 00:17 |
Referring to data types that don't exist,
referring to variables that don't exist
| | 00:21 |
and referring to methods, that is
subroutines and functions that don't exist.
| | 00:25 |
And show you common ways of fixing them,
and I'll start with misspelled data types.
| | 00:30 |
I'm working in a project called Compile
Errors, and it's a version of my
| | 00:35 |
calculator operation that lets me enter
two numeric values and then executive
| | 00:40 |
various mathematical operations.
It's very common in programming to
| | 00:44 |
misspell data types or class names.
Here's an example.
| | 00:48 |
I'll declare a new variable that I'll
call dbl3 and I'll try to set its data
| | 00:53 |
type as something simply called D.
There is no such class or data type as D
| | 00:59 |
in Visual Basic.
And so, when I save my changes, or simply
| | 01:03 |
move the cursor off that line of code,
Visual Studio will give me a visual
| | 01:07 |
indicator that shows me that there is an
error.
| | 01:10 |
Now, if I ignore that error and try to
run the application, I pressed F5, I'll
| | 01:15 |
get this dialogue, telling me that there
were build errors.
| | 01:18 |
If I ignore this dialogue box, and say,
yes, I want to continue, I'll be running
| | 01:23 |
the old version of the application, the
one that existed before the bug was introduced.
| | 01:28 |
That's not what you want to do.
You always want to fix those bugs before
| | 01:32 |
you continue testing.
So, here are some ways you can fix the error.
| | 01:36 |
One approach is to simply recognize that
you've misspelled the data type.
| | 01:40 |
And I'll auto complete this and set the
data type as double, something that I
| | 01:44 |
know exists.
And the error goes away.
| | 01:46 |
But let's say instead that my intent was
to create a new custom data type or a new
| | 01:52 |
custom class.
Visual Studio will help me do that.
| | 01:56 |
I'll change this back to D.
I'll move the cursor off the line to show
| | 01:59 |
the error, then move the cursor over the
error.
| | 02:02 |
I see the error message, and I move the
cursor down a bit, and I see the X icon
| | 02:07 |
with a little down arrow, and when I pull
down the list, I see a list of available options.
| | 02:13 |
I can generate a new class or I can
generate a new type.
| | 02:17 |
I'll go to generate new type, it gives me
more choices.
| | 02:20 |
Because this dialog box let's me generate
a bunch of different types of code,
| | 02:25 |
including classes, delegates, enums, or
enumerators, interfaces and structures.
| | 02:32 |
Some of these are more advanced.
In fact we won't be talking about some of
| | 02:35 |
these at all in this beginning course.
And I'm going to use the simplest version
| | 02:39 |
here, a class.
This dialogue also gives me the option to
| | 02:42 |
define the new class in a new file or in
a existing file.
| | 02:46 |
I'll create a new file called D.vb.
I'll click OK and then show that the new
| | 02:52 |
file was created in the solution
explorer.
| | 02:55 |
It's a very simple file with simply a
class and an end class declaration.
| | 03:00 |
Going back to my main window code, I see
that the compilation error has gone away.
| | 03:04 |
There's still a warning telling me that
this new variable isn't yet being used,
| | 03:09 |
but warnings don't prevent me from
building and running the application.
| | 03:12 |
And so I'll run.
And the application still works.
| | 03:15 |
Now, I'm going to return the code to it's
original state.
| | 03:21 |
I'm going to delete this custom class,
and then remove this line of code.
| | 03:25 |
And go to the next example of a common
compilation error.
| | 03:29 |
The next common compilation error, is
when you refer to a variable that hasn't
| | 03:33 |
been declared.
On this empty line of code, I'll say dbl3
| | 03:37 |
equals 1.
When I move the cursor off that line, I
| | 03:40 |
see the compilation error indicator.
And then, when I look at the error in
| | 03:45 |
detail, I see dbl3 is not declared.
Once again, this could be as simple as a
| | 03:50 |
misspelling you need to fix.
Or your intention might be to create a
| | 03:55 |
new variable.
And Visual Studio gives you two options.
| | 03:58 |
Creating something called a property stub
or generating a field.
| | 04:02 |
We'll talk about properties later in the
course.
| | 04:04 |
When we talk about custom classes.
For now, I'm simply going to generate a
| | 04:09 |
new field.
And as I've described previously, a field
| | 04:12 |
is a variable that belongs to the class
and is defined outside of any subroutines
| | 04:18 |
or functions.
Visual Studio declares the variable and
| | 04:21 |
then guesses at the appropriate data type
based on the value that I assigned, the
| | 04:26 |
value of 1.
There's another possible option, which is
| | 04:30 |
that you want to use Visual Basic as a
very dynamic language, where you don't
| | 04:34 |
have to declare variables ahead of time.
This makes it more similar to languages
| | 04:39 |
like JavaScript, where you can refer to a
variable without first saying that it
| | 04:43 |
exists or assigning a specific data type.
If you want to use Visual Basic in this
| | 04:48 |
way, use something called Option
Explicit.
| | 04:51 |
By default, Option Explicit is on.
Meaning, you need to pre-declare your variables.
| | 04:57 |
But if you don't want to do that, you can
set Option Explicit to off in a couple of ways.
| | 05:02 |
One approach is to add the code, Option
Explicit off, at the top of the current
| | 05:07 |
code module.
It looks like this.
| | 05:11 |
Now, when I move the cursor off that
line, my error goes away where I'm
| | 05:15 |
referring to dbl3.
This sets Option Explicit off, only for
| | 05:20 |
the current code module not for the
entire application, though.
| | 05:23 |
So, if you want to turn it off for the
entire application, remove it from the
| | 05:27 |
current code, then go to the properties
for the current project.
| | 05:32 |
I'll go to my Solution Explore.
I'll right click and I'll choose
| | 05:36 |
Properties and then in the properties
screen I've gone to the Compile category
| | 05:41 |
and I'll set Option Explicit to off.
Notice that there are also settings
| | 05:45 |
available here for Option Strict, Option
Compare, and Option Infer.
| | 05:50 |
Check the documentation for what these
mean.
| | 05:52 |
I'll come back to my code and see that
the error has been cleared, but when I
| | 05:57 |
move this cursor over the variable
reference, I'll see that it's data type
| | 06:01 |
isn't integer.
It's object.
| | 06:03 |
When you allow Visual Basic to work
dynamically in this fashion, there's a
| | 06:08 |
penalty, both in terms of performance and
memory usage.
| | 06:11 |
By explicitly declaring your variables
and their data types, you're optimizing
| | 06:16 |
the use of the runtime.
So, it's generally recommended that you
| | 06:20 |
keep Option Explicit turned on, and that
you explicitly declare all of your
| | 06:24 |
variables and their data types.
I'll come back to the Properties, and
| | 06:29 |
I'll turn it back on, then I'll come back
to my VB file and I'll remove this code.
| | 06:34 |
Finally there are undeclared methods.
Remember that a method is the same thing
| | 06:38 |
as a procedure and there are two kinds of
methods or procedures subroutines and functions.
| | 06:44 |
Let's say that I added a little bit of
code that looks like this, DoSomething.
| | 06:48 |
And I added in an opening and closing
parentheses at the end.
| | 06:52 |
Visual Studio is telling me that this is
an error, and more specifically, that
| | 06:56 |
DoSomething is not declared.
But, because I'm calling this apparently
| | 07:00 |
as a subroutine, Visual Studio offers to
generate what's called a method stub for me.
| | 07:06 |
I'll choose that option, then scroll down
to the bottom of my class, and I'll see
| | 07:10 |
that a new subroutine called DoSomething
has been created.
| | 07:14 |
It has a single line of code, Throw new
NotImplementedException.
| | 07:19 |
NotImplementedException is something
called a runtime exception.
| | 07:23 |
This code won't stop me from building and
testing this application, but if I run
| | 07:27 |
this subroutine, this error will pop up.
So, I'll run the application by pressing
| | 07:32 |
F5 and I'll type in some values and click
one of the operation buttons.
| | 07:37 |
And I get an unhandled exception dialog
box and when I click break I jump to that
| | 07:42 |
line of code.
I'll press Shift+F5 to close down the
| | 07:45 |
application and return to my code.
And I'll come back up here to where I've
| | 07:49 |
been adding my code.
Then I'll add one more bit of code that's
| | 07:53 |
calling a nonexistent function, a method
that returns a value.
| | 07:58 |
I'll declare a new variable that I'll
call dbl3, set its data type to double
| | 08:02 |
and call a function that doesn't exist
called DoSomethingElse, and I'll pass in
| | 08:06 |
dbl1 and dbl2 as arguments.
When I move the cursor off that line of
| | 08:13 |
code I get the error squiggly.
I'll open my options and I see two
| | 08:18 |
possible options, generating a method or
generating a property.
| | 08:22 |
I'll generate a method, scroll downy o
the bottom of the code and see that a new
| | 08:26 |
function has been created that receives
two double arguments and returns a double.
| | 08:31 |
So, these are some of the most common
compile time errors.
| | 08:35 |
Again, compilation errors prevent you
from building your application.
| | 08:39 |
You must fix them before you can build
and continue to test the application, but
| | 08:43 |
Visual Studio offers a lot of options for
helping you fix the code.
| | 08:49 |
| | Collapse this transcript |
| Common runtime errors| 00:00 |
As I've previously described, there are
two broad categories of errors, compile
| | 00:04 |
time and Runtime errors.
A Runtime error is an error that won't
| | 00:08 |
prevent you from building and testing
your application, but can cause the
| | 00:11 |
application to crash depending on the
nature of the application you're working in.
| | 00:17 |
Runtime errors can evolve from lots of
causes.
| | 00:20 |
And I can't describe all the different
kinds of errors that can happen, but I
| | 00:23 |
can show you two common errors here.
I'm working in the project runtime errors
| | 00:28 |
and I'll start by declaring a new
variable data type as a byte.
| | 00:32 |
I'll say Dim b As Byte, and I'll sign an
initial value of 255.
| | 00:40 |
The Byte class is an unassigned data
type.
| | 00:43 |
That is, it can only contain positive
values, and specifically with byte, it
| | 00:49 |
can zero to 255.
I've placed its code into calculate
| | 00:53 |
subroutine, so it'll be called whenever I
click any of the buttons in my calculator app.
| | 00:59 |
I'll run the application, enter some
values, and click a button and
| | 01:04 |
everything's fine but now lets see what
happens when I add one to the value of b.
| | 01:09 |
This will exceed the available range of
the byte data type.
| | 01:13 |
I'll b equals b plus 1, making it 256.
First I'll run the application without
| | 01:20 |
debugging by pressing control F5.
I'll enter some values and click a
| | 01:25 |
button, and I get the mysterious message
that the application has stopped working.
| | 01:33 |
I'll click Cancel, and return to Visual
Studio.
| | 01:36 |
This is what the end-user would see, if
you go ahead and publish the application,
| | 01:40 |
without fixing this error.
To find out more about the nature of the
| | 01:45 |
error, run the application with
debugging.
| | 01:47 |
So this time, I'll press F5.
Once again, I'll enter some values and
| | 01:52 |
click a button.
This time I get the unhandled exception
| | 01:55 |
dialog box.
This dialog box will tell you a little
| | 01:59 |
bit more about the nature of the
exception.
| | 02:01 |
In this case, I get something called
System.OverflowException, and an error
| | 02:06 |
message of Arithmetic operation resulted
in an overflow.
| | 02:10 |
You could click Continue, meaning you
want to ignore the error, but it's better
| | 02:14 |
to click Break.
That will take you back to your code in
| | 02:17 |
Visual Studio and show you which line of
code triggered the runtime exception.
| | 02:23 |
You should see that there were a couple
of panels that you might not have noticed before.
| | 02:26 |
One called Locals and one called Call
Stack.
| | 02:30 |
If you don't see these panels, go to the
menu right now, and choose Window > Reset
| | 02:35 |
Window Layout.
And click Yes, and they should show up.
| | 02:38 |
The Call Stack panel will give you a list
of the functions or subroutines that have
| | 02:42 |
been called to get to this point.
I'm going to drag this up, and then
| | 02:46 |
expand it, and show that I'm in the
calculate subroutine, but that was called
| | 02:50 |
from b, t, n, add click.
Watching the Call Stack, or the order of
| | 02:55 |
the calls, can help you figure out where
your error might be, so you can make fixes.
| | 03:00 |
I'm going to reset my Window Layout
again.
| | 03:02 |
And then, get out of debugging by
pressing Shift+F5.
| | 03:06 |
And I'm going to comment out these two
lines of code, because I'd like to show
| | 03:10 |
you another runtime exception.
In this version of my application in
| | 03:14 |
runtime errors, I've added a new constant
called IntDivide.
| | 03:18 |
And I've added a new button in the XAML
file that has the back slash operator.
| | 03:23 |
That's the integer division operator.
In the XAML file, with the button
| | 03:28 |
selected, I'll go to the Properties panel
and click the little lightening bolt
| | 03:32 |
button to show my event handlers.
And then, that shows me that the click
| | 03:37 |
event for this button is calling a method
called btnIntDivide click.
| | 03:41 |
I'll double-click there and I jump to
that sub routine in my vb file.
| | 03:46 |
Now here's what I want to do.
I want to call the calculate method and
| | 03:50 |
pass in that new constant of IntDivide.
So, I'll say calculate IntDivide.
| | 03:55 |
Next, I'll go to the calculate method.
I'll select it, right-click and go to the definition.
| | 04:03 |
Then, I'll scroll down a ways to my
select case where I'm looking at the
| | 04:07 |
operation, and I'm going to add a new
case statement.
| | 04:11 |
I'll say case IntDivide, and for that
case, I'll recalculate the result and
| | 04:17 |
I'll use the backslash integer division
operator.
| | 04:19 |
Result equals dbl1 \ dbl2.
Now, I'll run the application with
| | 04:26 |
debugging by pressing F5.
And I'll enter a couple of values.
| | 04:30 |
I'll start with values of 13 and 5.
And then, click my integer division
| | 04:35 |
button, and I get 2, the integer value of
the result.
| | 04:39 |
This operation, discards the remainder
and only returns the integer.
| | 04:44 |
But now, watch what happens when I try to
do integer division, and I enter 0.
| | 04:48 |
If I do regular division, I get my error,
Divide by zero.
| | 04:52 |
But integer division gives me an
unhandled exception.
| | 04:56 |
A runtime error.
And the nature of this exception, is a
| | 04:58 |
class called
System.DivideByZeroException.
| | 05:02 |
For some reason in Visual Basic, you'll
only see this exception with integer
| | 05:06 |
division, not with standard division,
which executes the operation and returns
| | 05:11 |
one of the infinity values, as I've
described previously.
| | 05:15 |
But here, I'm getting a runtime
exception, or a runtime error, and the
| | 05:19 |
message is attempted to divide by zero.
So, this is what runtime exceptions look like.
| | 05:24 |
Both when the users running them, when
the application can simply crash or when
| | 05:28 |
you're running them with debugging as the
developer.
| | 05:31 |
Once you figure out that it's possible to
hit a runtime exception, you must fix it
| | 05:36 |
in your code.
And I'll show you some ways of doing that
| | 05:39 |
using the tri-catch architecture in a
later movie.
| | 05:42 |
| | Collapse this transcript |
| Handling exceptions with Try...Catch| 00:01 |
A runtime exception happens when a
particular set of conditions exists.
| | 00:05 |
You might not always find all of your
runtime exception conditions when you're
| | 00:08 |
developing an application.
But as you discover them during
| | 00:11 |
development, or your users report them,
it's up to you, as the developer, to fix them.
| | 00:16 |
One of the best ways to diagnose and then
handle exceptions is with the Try Catch architecture.
| | 00:22 |
Try Catch looks like this.
I'll start with this code in the project
| | 00:26 |
Try Catch where I'm declaring a variable
as a data type and setting it to a value
| | 00:30 |
of 255 then adding one.
Because the byte data type has a top
| | 00:35 |
range of 255, this causes an exception.
I'll remove the comments and then I'll
| | 00:41 |
place the cursor before the line of code
that's causing the exception.
| | 00:45 |
I'll type in try and press Enter.
This creates three lines of code, Try,
| | 00:50 |
Catch ex As Exception, and End Try.
Place the code that might cause the
| | 00:55 |
exception after the word try.
So, I'll take this line and cut and paste it.
| | 01:01 |
Now if that line of code triggers the
exception, the flow will move into the
| | 01:05 |
catch clause.
And you'll get a variable called ex,
| | 01:09 |
which is an instance of something called
an exception class.
| | 01:12 |
Exception is what we call a top level
class or a base class, and it has a whole
| | 01:17 |
bunch of sub classes that are specific
types of exceptions.
| | 01:21 |
One of the best ways of finding out what
happened is to put a return statement
| | 01:25 |
after the cache, and then add a break
point on that line of code.
| | 01:30 |
You can add the break point by clicking
in the gutter on the left side of the screen.
| | 01:34 |
You'll get this background color on the
selected code.
| | 01:38 |
Now I'll run the application by pressing
F5, that means run with debugging, and
| | 01:43 |
then I'll click one of my operation
buttons.
| | 01:46 |
That results in suspending the code and
dropping me in to Visual Studio.
| | 01:50 |
The indicator on the left tells me that
I'm frozen at that line of code.
| | 01:54 |
And I can now inspect all of my current
variables in the Locals panel down here.
| | 01:59 |
As I mentioned previously, if you don't
see the Locals panel, reset your layout.
| | 02:04 |
We have a variable called ex that's
generated by the Catch clause.
| | 02:08 |
And currently, it's data typed as an
exception.
| | 02:11 |
But when I look in the Locals panel and I
open up the tree for ex, I see that ex is
| | 02:17 |
an instance of a class called
System.OverflowException.
| | 02:21 |
And I can learn all about that exception
class by opening up that part of the tree.
| | 02:25 |
And I see the message that's associated
with the exception, a data dictionary and
| | 02:30 |
a lot of other information that might be
useful.
| | 02:32 |
This particular exception is pretty
simple.
| | 02:35 |
All you really get is this message,
arithmetic operation resulted in an overflow.
| | 02:39 |
So to handle that exception, I'll add a
little bit more code.
| | 02:43 |
I'll press Shift+F5 to get out of
debugging, and then I will add a line of
| | 02:47 |
code before my return statement and
output an error message.
| | 02:52 |
I'll use the method display error that I
coded up in an earlier movie, and I'll
| | 02:56 |
start with a string of addition error and
I'll append to that ex.message.
| | 03:01 |
The message property of the ex variable,
the exception object.
| | 03:07 |
I'll save an run the application in debug
mode again, this time I'll put in some numbers.
| | 03:13 |
And I'll click the Plus operation.
When I get dropped into the break point,
| | 03:17 |
this time I'll click Continue, switch
back to the running application, and I
| | 03:22 |
see my error messages displayed.
Another way of handling this exception
| | 03:28 |
would be to correct it on the fly and
simply let the application continue.
| | 03:32 |
So, I'll comment out these two lines of
code, and I'll click over here to remove
| | 03:37 |
the break point.
And instead, I'll simply reset the value
| | 03:40 |
of the variable to a legal value, saying
B equals 255.
| | 03:45 |
I'll run the application in debug mode
again.
| | 03:48 |
I'll enter some values.
And now everything works.
| | 03:51 |
So, I can either let the user know that
there's an error.
| | 03:54 |
If it's something that the user has to
deal with.
| | 03:57 |
Or if it's something I can correct in my
own code, I can add my own code in the
| | 04:01 |
catch section.
Let's handle the other exception that I
| | 04:04 |
introduced into this project in an
earlier movie.
| | 04:07 |
In this application, I'm doing a number
of mathematical operations.
| | 04:11 |
And I introduced this possible exception
when I added integer division to my calculator.
| | 04:17 |
I'm letting the user enter any numeric
value and then doing integer division.
| | 04:21 |
And if they enter zero for the second
number, I'll get a runtime exception.
| | 04:26 |
Just as I did before, I'll add a try
catch block.
| | 04:29 |
And I'll move the code after the word
try.
| | 04:31 |
Then, so I can add a break point, I'll
add the return statement.
| | 04:39 |
And I'll add the break point and run in
debug mode.
| | 04:42 |
To trigger the error, I'll enter a value
of 5 and a value of 0.
| | 04:46 |
And click the Integer button.
That get's me to my break point.
| | 04:50 |
And I can now move the cursor over the
variable.
| | 04:52 |
And this is another way of finding out
what happened.
| | 04:55 |
I see that I'm getting an Exception
called System.DivideByZero Exception.
| | 05:00 |
Now here's another thing that you can do
with Try and Catch.
| | 05:03 |
I'll get out of debugging by pressing
Shift+F5 again and you can make your
| | 05:07 |
Catch clause specific to a particular
exception.
| | 05:11 |
So instead of saying, go into this code
for any exception, I'll instead say, only
| | 05:16 |
execute this code for a divide by zero
exception.
| | 05:21 |
And then, before the return statement,
I'll call my DisplayError method, and
| | 05:25 |
I'll pass in my own custom error message,
divide by zero.
| | 05:29 |
I'll remove the breakpoint, and run the
application again.
| | 05:34 |
Now when I enter values, including a 0
for value 2, and try to do integer
| | 05:38 |
division, I've handled the error and I'm
telling the user what went wrong.
| | 05:43 |
They can then correct the problem by
entering valued values.
| | 05:47 |
For example, I'll enter 13 and 5 and
click again, and I get a good result.
| | 05:52 |
So, that's an introduction to the Try
Catch architecture.
| | 05:55 |
There's lots more to know about error
handling in Visual Basic.
| | 05:59 |
And I encourage you to explore the
documentation for the Try keyword to
| | 06:03 |
learn all about it.
| | 06:04 |
| | Collapse this transcript |
|
|
6. Working with Complex ObjectsUsing the Object data type| 00:00 |
In Visual Basic the elementary or built
in data types all map to classes in the
| | 00:05 |
.NET Framework.
At the top of the class hierarchy you
| | 00:09 |
find a class called object and its the
equivalent of the object data type in
| | 00:14 |
Visual Basic.
You can take any value in Visual Basic
| | 00:17 |
and data type it as an object.
Another way of saying it is that you can
| | 00:21 |
widen any data type to an object.
You can find the documentation for the
| | 00:26 |
object data type here and I'll show you
some examples of how the object data type
| | 00:30 |
in class behave.
I'm working on a project called object
| | 00:34 |
data type, its an empty project that will
let me test some code.
| | 00:38 |
And I'll add the code here in the run
code sub routine.
| | 00:42 |
I'm going to declare a variable called o
and data type it as the object data type
| | 00:48 |
and I'm not initially going to assign it
any value.
| | 00:51 |
With numeric data types such as integer,
double and so on, the default value if
| | 00:56 |
you don't assign a value yourself, is 0.
But with the object data type it's
| | 01:01 |
something called nothing.
Nothing is the equivalent of null in
| | 01:05 |
other programming languages.
I'm not going to initially assign
| | 01:09 |
anything to this variable, I'm just
declaring it.
| | 01:12 |
And then I'll add some conditional code.
And I'll use a function called IsNothing
| | 01:16 |
and pass in the variable o.
If that condition is true, I'll output a
| | 01:21 |
string of No object exists.
I'll run the code and click the button
| | 01:27 |
and I see that the condition is true.
So the IsNothing function is a good way
| | 01:32 |
of testing complex object references to
see if something has been instantiated.
| | 01:37 |
Now I'll change this code and initialize
the object with equals new and then I'll
| | 01:43 |
call the objects class constructor.
You can write this code either with or
| | 01:48 |
without the parentheses.
Then I'll go down to my conditional block
| | 01:55 |
and I'll add an else clause and then I'll
output the following string before
| | 02:00 |
assignment to value.
And then I'm going to use an expression
| | 02:04 |
that outputs the data type of this
variable as a string.
| | 02:08 |
It looks like this.
o.GetType.ToString.
| | 02:13 |
I'll run that code, click the go button
and I see that the object data type is
| | 02:18 |
currently mapped to a class called
System.Object.
| | 02:22 |
Now the nature of this variable because
it's an instance of the object class is
| | 02:26 |
that it can morph at runtime into any
other class.
| | 02:30 |
It makes it highly dynamic.
As I've mentioned previously this
| | 02:33 |
approach won't get you the best
performance in most applications but it
| | 02:37 |
will give you a lot of flexibility.
So now I'm going to add some code down here.
| | 02:42 |
I'll assign the variable o to a value of
1.
| | 02:46 |
Then I'll make a copy of this output
command and I'll paste it in here and
| | 02:53 |
I'll change the label to as number.
Then I'll take these two lines of code
| | 02:59 |
and I'll copy and paste them and I'll
change the assignment this time to my
| | 03:04 |
name as a string.
And then change the label to as string.
| | 03:08 |
So the nature of this variable because I
data typed it as an object is that it can
| | 03:13 |
change from one data type to the next.
And then in the background it's going to
| | 03:17 |
be assigned to instances of different
.NET Framework classes.
| | 03:22 |
I'll run the code and test it again and I
see that it starts off as System.Object
| | 03:27 |
then it morphs into a number, an instance
of a class called System.Into32 and then
| | 03:32 |
into a string as System.String.
And I could continue with this exercise
| | 03:37 |
and show that it can morph into anything.
Finally I'll show an example of taking a
| | 03:42 |
value that's an integer and then taking
another value that's data typed as an
| | 03:46 |
object and assigning them to each other
to see what happens.
| | 03:52 |
At the end of the existing code, I'll
create a new integer variable called src
| | 03:56 |
for source and I'll assign it a value.
Then I'll declare a variable named target
| | 04:02 |
and type it as an object and assign it to
the value of source.
| | 04:06 |
Then I'll output is string of target
value and append to that the value of the
| | 04:13 |
target variable.
I'll run the code and here's the result.
| | 04:17 |
The object variable target receives the
integer value and shows its actual value.
| | 04:23 |
And as I showed previously it will turn
into an instance of the appropriate .NET
| | 04:28 |
Framework class.
The object data type and its underlying
| | 04:31 |
capability of morphing into different
classes gives you enormous dynamic
| | 04:35 |
flexibility in your programming.
It does cost you in terms of performance
| | 04:40 |
but when you need flexibility it can
accomplish that.
| | 04:43 |
| | Collapse this transcript |
| Managing ordered data with arrays| 00:00 |
An array is a collection of data where
the order of the data is fixed.
| | 00:05 |
Visual Basic supports both fixed size
arrays and resizable arrays.
| | 00:08 |
Fixed sized arrays are sometimes called
simple arrays.
| | 00:12 |
And they're a part of the language
itself.
| | 00:14 |
Re-sizable arrays are implemented in a
class called array list.
| | 00:18 |
And I'll demonstrate them both here in a
project called Arrays.
| | 00:22 |
I'll add code to the subroutine RunCode
and show a few different ways of
| | 00:26 |
declaring simple arrays.
I'll start by creating a variable called
| | 00:31 |
fruits and I'll indicate that this is
going to be an array by adding an opening
| | 00:35 |
and closing parentheses after the
variable name.
| | 00:38 |
Then I'll set the data type of the items
in the array as string.
| | 00:43 |
Here's one way of declaring an array
using a simple syntax where you wrap a
| | 00:47 |
(UNKNOWN) limited list of values inside a
pair of braces.
| | 00:53 |
I'll create a set of three strings.
Apple, orange and pear.
| | 00:58 |
Then I'll report the number of items in
the array using a property that's
| | 01:03 |
available on all arrays called length.
I'll use my output subroutine and I'll
| | 01:08 |
output a label of number of fruits.
And I'll append to that the expression fruits.Length.ToString.
| | 01:21 |
I'll run that code and test it and
there's the result.
| | 01:25 |
When I create an array in this way the
number of items is fixed based on the
| | 01:29 |
number of items in the list.
But here's another way of declaring an array.
| | 01:35 |
I'll create another array that I'll call
vegetables and this time I'll pass in a
| | 01:40 |
value of two between the parenthesis.
That means I'm creating the array with
| | 01:44 |
two available slots.
Once again I'll set the datatype of the
| | 01:49 |
items in the array as a string.
Now I have two available slots and I
| | 01:54 |
refer to them by their indexed positions.
The numeric index of the first item in
| | 02:00 |
the array is zero.
The next one will be one and if there
| | 02:03 |
were more they would be two, three and so
on.
| | 02:07 |
In Visual Basics you refer to index
position with parenthesis.
| | 02:10 |
So I'll say that the item in slot zero is
potato.
| | 02:19 |
And that the item in the second slot is
lettuce.
| | 02:22 |
Now I'll show a way of looping through
the array and outputting the values in it.
| | 02:27 |
I'll use a For loop.
I've shown in previous movies that you
| | 02:30 |
can use something called For Each to loop
through an array but you can also do a
| | 02:34 |
loop through an array using a simple
numeric For loop with a counter variable.
| | 02:39 |
I'll create a counter variable called veg
for vegetable and I'll say that it is an integer.
| | 02:44 |
And I'll set its initial value to zero
and then I'll set the upper value to
| | 02:49 |
vegetable.length minus one.
When I press Enter Visual Studio adds the
| | 02:55 |
next keyword and within the loop, I'll
create a new string variable that I'll
| | 02:59 |
call vegName.
That'll be a string and I'll get its
| | 03:02 |
value by passing in the veg counter
variable.
| | 03:05 |
And then I'll output it.
And there's the result.
| | 03:13 |
In Visual Basic simple arrays, the index
value starts counting at zero and then
| | 03:18 |
moves up from there.
And that's the same as in Java, C# and
| | 03:21 |
other C style languages.
Now as I've mentioned simple arrays have
| | 03:26 |
a fixed size.
Once you declare them, you can't add or
| | 03:29 |
remove items completely.
If you need a re-sizeable array, create
| | 03:34 |
an instance of the class array list.
To demonstrate this, I'll declare an
| | 03:38 |
array list.
But, I'll do it outside of any of my procedures.
| | 03:42 |
I'll place the cursor above the RunCode
subroutine and I'll create a new variable
| | 03:46 |
called names that I'll data type as a
ArrayList.
| | 03:50 |
And I'll initialize this using the array
list constructor method and the new keyword.
| | 03:57 |
The array list class has a few different
constructors I'll be using the simple one
| | 04:01 |
with no arguments but you can also pass
in an integer value to set the initial capacity.
| | 04:06 |
This will get you better performance if
you know ahead of time how many items
| | 04:09 |
you're going to put into the array list.
And you can also pass in something called
| | 04:13 |
a collection but I'll just use the simple
constructor method.
| | 04:17 |
Now, each time the user clicks the
button, I'm going to take the value
| | 04:21 |
that's been typed into the input text box
and add it to this array list.
| | 04:26 |
I don't need this code any more so I'm
going to comment it out I'll select it
| | 04:30 |
then choose Edit > Advanced > Comment
selection.
| | 04:34 |
And then down here I'll add the value
from the text input box to the array list.
| | 04:41 |
I'll create a new variable called name,
data type it as string and gets its value
| | 04:46 |
from txtInput.text.
Then, I'll call the add method of the
| | 04:52 |
array list using names.add and I'll pass
in name.
| | 04:56 |
Next I'll clear the output text box with
txtOutput.text equals a blank string.
| | 05:03 |
Finally, I'll loop through the contents
of the array list.
| | 05:07 |
As I have in previous movies, I'll use
the For Each construct and I'll say For
| | 05:12 |
Each name In names.
Now, notice I'm not setting the data type
| | 05:17 |
name here because I've already set it up
here.
| | 05:22 |
And within the for each loop, I'll output
the current name.
| | 05:25 |
Because I declared the array list outside
of any of the subroutines, it will
| | 05:29 |
persist, it'll stay in memory and I'll be
able to keep on adding items as long as
| | 05:34 |
the user keeps on typing values in.
I'll run the code and I'll type in my
| | 05:40 |
name and I'll click Go.
And I see my name appear.
| | 05:43 |
I'll type in somebody else's name and
somebody else's and so on and so forth.
| | 05:49 |
The ArrayList class has an extensive set
of methods that you can use to manage
| | 05:54 |
your ordered data.
I've shown how to use the add method and
| | 05:57 |
they're also methods such as clear,
contains, remove and others.
| | 06:02 |
Use the array list whenever you need a
re-sizable array and use simple arrays
| | 06:07 |
whenever you need a fixed array in you
Visual Basic code.
| | 06:10 |
| | Collapse this transcript |
| Managing unordered data with Collection| 00:00 |
I've previously described how to manage
ordered data using simple arrays and the
| | 00:05 |
array list class.
Now, I'm going to describe how to manage
| | 00:08 |
unordered data using a class called
collection, and I'm working in a project
| | 00:13 |
called Collections.
The collection class can manage both
| | 00:17 |
ordered and unordered data, but it's
mostly used for unordered data, for each
| | 00:21 |
item in the collection has a value and a
key.
| | 00:25 |
The value in a collection item can be any
object, a string, a number, a Boolean, or
| | 00:30 |
any complex object.
Whereas the key must be a string.
| | 00:35 |
In this application, I'm going to declare
an instance of the collection class
| | 00:38 |
outside of any of the methods of the main
window class.
| | 00:42 |
This will cause the data to persist for
the lifetime of the application.
| | 00:46 |
I'll start with Dim, and I'll create a
new variable named states and I'll data
| | 00:50 |
type it As Collection.
Then I'll instantiate it, using the
| | 00:54 |
collection class' constructor method.
There's only one version of this
| | 00:58 |
constructor method.
It doesn't receive any arguments and it
| | 01:01 |
returns an empty collection.
Now, I'll add code to add items to the
| | 01:06 |
collection, and I'll place this code
inside this method, named btnAdd.Click.
| | 01:12 |
This code will be called when the user
clicks the Add button.
| | 01:15 |
First, I'm going to make sure that the
collection is empty.
| | 01:18 |
I'll call states.Clear, and now I know
that I'm starting with an empty data bucket.
| | 01:25 |
Next, I'll add an item to the collection,
using the collection class' add method.
| | 01:31 |
The add method takes one required
argument and three optional arguments.
| | 01:36 |
The first required argument is the value
that you want to store.
| | 01:40 |
It can be any object.
I am going to pass in a string of California.
| | 01:44 |
Then I'll pass in a second argument,
which will be the key.
| | 01:47 |
Later on, if I know the key, I can find
the value.
| | 01:51 |
So I'll pass in an abbreviation of CA.
Now I'm going to copy this line of code
| | 01:57 |
and paste it in a couple of times, and
I'll change the values and abbreviations
| | 02:02 |
for the second and third states to Oregon
and Washington.
| | 02:06 |
So now I have three items in my
collection and I'd like to display them.
| | 02:10 |
And I'm going to do that in the method
that I've already created, called OutputStates.
| | 02:15 |
I'll put in a call to that method here,
then I'll scroll down to that method,
| | 02:19 |
which currently doesn't have any code.
In this method, I'm going to loop through
| | 02:23 |
the contents of the collection and
display each item's value.
| | 02:27 |
I'll do this using a For each loop.
I've used a For each loop in previous movies.
| | 02:31 |
When you use a For each loop, you declare
an element, or a variable, and
| | 02:36 |
optionally, set its data type.
I'm going to create a variable called
| | 02:40 |
state and say that it's a string, because
I know that my collection only contains strings.
| | 02:47 |
And then I'll say that I'm getting that
item from the states collection.
| | 02:50 |
When I press Enter, Visual Studio adds
the next keyword.
| | 02:55 |
Now within the loop, I'll have the value
state which will be the value of the item
| | 02:59 |
that I'm currently iterating on.
So I'll simply output the value state.
| | 03:04 |
Now I'll run the code and click the Add
button, and there's the result.
| | 03:09 |
I'm displaying the three items.
I can also click the Show button and show
| | 03:12 |
the items again, or I can click the Clear
button and clear the output.
| | 03:18 |
Next, I'm going to show how to write code
that retrieves an item from the
| | 03:21 |
collection if you already know the key.
I'll go to the method btnGet.Click.
| | 03:28 |
This code will be executed when the user
clicks the Get button.
| | 03:31 |
The user will type in a state
abbreviation, and I'll use that value and
| | 03:36 |
look for it in my collection.
If I find it, I'll display the item's value.
| | 03:40 |
So first, I'll find out what the user
typed.
| | 03:43 |
I'll create a variable called stateID as
a string.
| | 03:46 |
And I'll get its value from
txtInput.Text.
| | 03:51 |
Txt input is the ID or name of my text
input box.
| | 03:56 |
Next, I'll add some conditional code, and
I'll use a method of the states
| | 04:00 |
collection called Contains.
And I'll pass in the variable stateID.
| | 04:08 |
The contains method looks for an item by
its key.
| | 04:11 |
If it finds it, it returns true, and if
it doesn't, it returns false.
| | 04:15 |
So if I found this state, I'm going to
output the value, using this code.
| | 04:19 |
I'll use my output method, and I'll pass
in a label of You requested, and then
| | 04:26 |
I'll append the value using a method of
the collection class called item.
| | 04:30 |
You pass in the key into the item method,
and it returns the value.
| | 04:34 |
Then I'll add an Else clause, and this
will only happen if the value wasn't
| | 04:38 |
found, and I'll output a string of Not
found.
| | 04:43 |
I'll run that code.
First I'll click the Add button to
| | 04:45 |
populate my data, then I'll type in CA
and click the Get button and show that I
| | 04:51 |
got California.
Then I'll type in OR and click Get again,
| | 04:54 |
and show that I got Oregon.
I'll type in a value of xyz and click Get
| | 04:59 |
and show that I got Not found.
Here's another impressing thing about the
| | 05:04 |
item method.
The keys in the collection class are not
| | 05:07 |
case sensitive.
So if I type ca in lower case and click
| | 05:11 |
Get, I still get back the value, even
though the key was established with all uppercase.
| | 05:17 |
Finally, I'm going to write some code to
remove items from the collection.
| | 05:20 |
I'll go to the method btnRemove_Click.
Now this code will be very similar to
| | 05:25 |
when I found an item, so I'm going to
copy and paste that code.
| | 05:29 |
I'll start with Dim stateID as string and
I'll copy that and paste it into this method.
| | 05:35 |
And this time, if I found the state that
the user typed in, I'm going to remove it
| | 05:40 |
from the collection.
So, I'll get rid of the Output command,
| | 05:48 |
and I'll call states.Remove.
Notice that there are two versions of the
| | 05:52 |
remove method.
One that lets you look for an item by its
| | 05:55 |
position in the collection, an integer,
and one that lets you look for it by a
| | 05:59 |
string-based key.
That's the version I'm using.
| | 06:02 |
Next, I'll tell the user what happened.
I'm going to clear the output with
| | 06:09 |
txtOutput.Text equals a blank string.
Then I'll use my output method, and I'll
| | 06:15 |
start with the stateID, and I'll append
to that the message, removed; here's
| | 06:20 |
what's left.
And then, just as I did before, I'll call
| | 06:23 |
the OutputStates method.
So let's review that code.
| | 06:27 |
First, I find out whether the
abbreviation the user typed in exists as
| | 06:31 |
a key in the collection.
If it does, I remove it.
| | 06:35 |
Then, I tell the user that it was
removed, and then I tell them what's left
| | 06:39 |
in the collection.
I'll run the code, and I'll click the Add button.
| | 06:44 |
I'll type in a known key of OR, and
remove it.
| | 06:47 |
And I see that OR was removed, and I
still have California and Washington.
| | 06:51 |
Next, I'll remove California.
And I'm left with Washington and finally,
| | 06:56 |
I remove Washington, and it's empty.
And I can click the Add button and start
| | 07:01 |
over again.
So that's a look at how to use the
| | 07:03 |
collection class to manage unordered
data.
| | 07:06 |
Each item in the collection class can
have a value of any data type, but the
| | 07:10 |
key is always a string.
And again, you can use the collection
| | 07:14 |
class to manage ordered data, but I
prefer to use array list for that.
| | 07:18 |
Use array list for ordered data, and
resizable arrays.
| | 07:20 |
And collection for unordered data, where
each item has a value and a string-based key.
| | 07:27 |
| | Collapse this transcript |
| Managing statically typed data with Dictionary| 00:00 |
The dictionary class is a part of the
.net framework.
| | 00:03 |
It’s similar to the collection class but
it offers more functionality and lets you
| | 00:08 |
be specific about what type of object
you’re storing in it, and gives you the
| | 00:12 |
flexibility of using something other than
strings as keys.
| | 00:15 |
I’m going to describe how to use the
dictionary class by modifying the
| | 00:20 |
application I previously built with
collection.
| | 00:23 |
The name of this project is dictionaries.
And I'm going to start by changing the
| | 00:27 |
datatype of my states collection.
When you create a dictionary, you declare
| | 00:31 |
what datatype you will be using both for
the values and the keys.
| | 00:36 |
I'll delete collection as the datatype
and instead put in dictionary.
| | 00:40 |
Notice the syntax asks for 2 datatypes.
The key and the value, in that order.
| | 00:45 |
Start with the key word Off, then type in
the data types in a common to limited list.
| | 00:51 |
I'm saying that the items in my
dictionary will have strings for both
| | 00:55 |
their values and keys.
Next, I'll change the constructor method
| | 00:59 |
call, I'll get rid of the constructor
method for the collection and because
| | 01:03 |
this code will get a little wide, I'll
add a new line.
| | 01:06 |
And then I'll use the dictionary classes
constructor method, and just as I did in
| | 01:11 |
the data type, I'll say that it'll have a
string for both the key and the value.
| | 01:16 |
Next there are some changes that I'm
going to need to make.
| | 01:19 |
First, I'll go to the code where I'm
adding values to the dictionary.
| | 01:23 |
The add method for the collection takes
the value as the first argument and the
| | 01:27 |
key for the second argument but for the
dictionary it's reversed.
| | 01:31 |
So for each of these calls to the add
method I'm going to move the key to the
| | 01:34 |
first position.
I'll do it for California, for Oregon,
| | 01:39 |
and for Washington.
Next I'm going to build the application,
| | 01:42 |
and this will help me find some errors
that resulted when I switched from the
| | 01:46 |
collection class to the dictionary.
I'll go to the first error.
| | 01:49 |
The collection class has the method
contains, which always looks for a
| | 01:53 |
particular key.
But with a dictionary, you can look for
| | 01:56 |
the value or the key.
So you have to be specific about what
| | 01:59 |
you're looking for.
I'm going to change from the contains
| | 02:02 |
method call to a method of the dictionary
class called contains key.
| | 02:06 |
And I'll need to make that change in a
couple of places.
| | 02:08 |
I'm making it here, in the get method,
and then I'll double click on the next
| | 02:12 |
error, and that'll take me to the move
method.
| | 02:15 |
And I'll make the change here as well.
Next, I'll go to the output states method.
| | 02:22 |
In this method, I'm assuming that the
value of state is a simple string.
| | 02:25 |
But items that you put into a dictionary
have both a key and a value.
| | 02:30 |
So I'm going to change this expression
from state to state.ToString.
| | 02:35 |
And see what that gets me.
I want to get and build the solution, and
| | 02:40 |
now I get to one more error.
The state won't be a simple string
| | 02:43 |
anymore, so I'm going to remove the data
typing as string.
| | 02:47 |
I'll save again, and now I don't have
anymore errors, and I'll try running the application.
| | 02:54 |
When I click add, I'm sucessfully adding
items to the dictionary, and when I
| | 02:57 |
output them, I'm getting both the key and
the value in a comma de limited list.
| | 03:02 |
I'll test the get and move functionality,
I'll type in ca and click get, and I
| | 03:07 |
sucessfully get California.
Then I'll remove it, and it shows that it
| | 03:12 |
was successfully removed and the other
items are still there.
| | 03:16 |
In addition to providing static typing of
the keys and values of the items in the
| | 03:21 |
dictionary, the dictionary class has a
bunch of additional methods that don't
| | 03:25 |
exist in the collection.
You can get lists of keys, you can
| | 03:28 |
compare values and keys to each other and
do all sorts of other advance
| | 03:33 |
manipulation of your unordered data sets.
You can use the collection class if it
| | 03:38 |
does what you need for your application.
But for more functionality look at the dictionary.
| | 03:42 |
| | Collapse this transcript |
|
|
7. Organizing CodeManaging application logic with modules| 00:00 |
As your applications get larger, you'll
need to organize your code.
| | 00:04 |
And Visual Basic gives you a couple ways
of doing that.
| | 00:07 |
First, I'm going to describe how to use
modules.
| | 00:10 |
I'm working in a solution called Modules,
which has a project SimpleCalc.
| | 00:14 |
And right now, all of the code for
SimpleCalc is in the MainWindow.xaml.vb file.
| | 00:20 |
All of the calculations are nested within
this select case statement.
| | 00:24 |
I'm going to describe how to take these
calculations and move them into a
| | 00:27 |
separate code file.
Call it a module.
| | 00:30 |
I'll go to the Project in the Solution
Explorer, right-click and select Add >
| | 00:35 |
New Item.
And I'll select module as the type of
| | 00:39 |
item I want to create.
Down here, I'll set the name of the
| | 00:42 |
module as calculations.vb.
A module is simply a Visual Basic text file.
| | 00:49 |
It starts with the keyword Module, then
has the name of the Module and ends with
| | 00:54 |
End Module.
You can add any procedures you like to
| | 00:57 |
the module, and they'll all become
available to your application.
| | 01:01 |
Within the module, I'll create some new
functions.
| | 01:03 |
I'll start with the keyword Public, then
the word Function, and then create a new
| | 01:10 |
function called AddValues.
It will accept two arguments, dbl1 and
| | 01:15 |
dbl2, and it will return a double value.
When I press Enter, Visual Studio adds
| | 01:21 |
the End Function clause.
Because I'm saying this is a function, I
| | 01:25 |
need to return a value.
So, I'll type Return and then do the
| | 01:29 |
calculation of dbl1 plus dbl2.
As with any function, if you want to be
| | 01:36 |
specific about the data types it accepts,
you can add data typing to the arguments.
| | 01:41 |
I'll do that here.
Saying that both arguments are double values.
| | 01:44 |
I'll save those changes, and then go back
to my Visual Basic file for the main form.
| | 01:51 |
I'll remove the calculation from this
line, where I'm doing the addition of
| | 01:54 |
dbl1 and dbl2.
And I'll replace it with a call to my new
| | 01:59 |
function, AddValues.
Notice that Visual Studio already knows
| | 02:03 |
that the function exists.
I'll pass in the two values that I have
| | 02:06 |
available, dbl1 and dbl2.
Move the cursor off the line to confirm
| | 02:11 |
that no errors happen, and then run the
application and test it.
| | 02:16 |
I'll type in some numeric values, click
the plus operator button, and see that
| | 02:21 |
the functionality still works.
I'll come back to Visual Studio and add
| | 02:25 |
three more methods to my module.
I'll select and copy this function, add
| | 02:30 |
values, and then I'll copy and paste it
in three times.
| | 02:34 |
I'll go to each of the new functions and
change their names.
| | 02:37 |
This one will be subtract values.
The next one will be multiply values.
| | 02:43 |
And the last one will be divide values.
And then, I'll adjust their operators.
| | 02:48 |
Subtract will have the hyphen, multiply
will be the asterisk and divide will be
| | 02:55 |
the forward slash.
I'll save changes to that file and come
| | 02:59 |
back to my Main Window file.
I'll expand to full screen to make this a
| | 03:03 |
little bit easier.
And I'll replace each of these
| | 03:06 |
calculations with calls to the
appropriate functions calling subtract
| | 03:10 |
values, multiply values, and divide
values.
| | 03:15 |
I'll run the application again.
Enter some values, and then test all four operations.
| | 03:36 |
And I'll see that the calculator's
functionality still works.
| | 03:40 |
So, modules simply give you a way of
reorganizing your code, putting related
| | 03:45 |
functions together.
But in a way that makes them available to
| | 03:48 |
the entire application.
| | 03:50 |
| | Collapse this transcript |
| Defining a custom class with shared procedures| 00:00 |
I've previously described how to organize
functions in modules, but there's another
| | 00:05 |
more object oriented approached where you
create something called a custom class.
| | 00:10 |
A custom class can manage shared
functions in the same way that a module
| | 00:14 |
does, but it can also store data.
I'll start in this exercise by showing
| | 00:18 |
how to create the custom class, and I'll
move my shared functions from the module
| | 00:23 |
to the class.
I'm working in a solution called Custom
| | 00:26 |
Classes that has the same project, Simple
Calc, that I've worked on before.
| | 00:30 |
I'll go to the project, right click, and
choose add new item.
| | 00:35 |
This time, I'll choose class and I'll
name the class calc utility, just as with
| | 00:42 |
modules a class is created in a vb file.
I'll click add and that creates the new
| | 00:48 |
Visual Basic file.
The default syntax for a new class is to
| | 00:52 |
start off with the keyword public and
access modifier, then the word class and
| | 00:57 |
then the name of the class...
In contrast to module names, where the
| | 01:01 |
name of the module doesn't really matter
that much, the name of a class absolutely
| | 01:05 |
matters because in order to access any of
the code within the class, you have to
| | 01:10 |
know the name.
In Visual Basic, the name of the class
| | 01:13 |
does not have to match the name of the
file in which it's defined.
| | 01:16 |
That makes it different from some other
programming languages like Java.
| | 01:20 |
The next step is to copy those functions
form the module to the new class.
| | 01:25 |
I'll go to my module, and I'll select all
the functions within the module, copy
| | 01:30 |
them to the clipboard, come back to the
new class and paste them in.
| | 01:35 |
then I'll go back to the solution
explorer and I'm going to get rid of the module.
| | 01:39 |
I'll select it, press delete and then
click Okay.
| | 01:42 |
I'll save those changes, then come back
to my main window VB file and see that as
| | 01:47 |
expected, I have some errors now.
Because I've moved the functions into a
| | 01:52 |
class and out of a module they are no
longer automatically available to my application.
| | 01:57 |
I now have to say where they are coming
from.
| | 02:00 |
To do that, add the name of the class as
a prefix to the name of the function and
| | 02:05 |
separate the name of the class from the
name of the function with a period.
| | 02:09 |
It will look like this,
Calcutility.addvalues.
| | 02:13 |
I'll save those changes, but see that I
still have an error.
| | 02:16 |
And I see this message.
Reference to a non-shared member requires
| | 02:20 |
an object reference.
Here's what's going on.
| | 02:23 |
A class can have both what are called
instance members, that is, members of an
| | 02:28 |
object that's an instance of the class,
Or it can have shared members, members
| | 02:33 |
that are available from the class itself
without having to create an instance of
| | 02:37 |
the class.
That might sound complex at first, and
| | 02:40 |
that's because you're moving into the
world of object oriented programming.
| | 02:44 |
For now, what you need to know is that in
order to call the function in this way,
| | 02:48 |
it has to be shared.
And to make it shared, you go back to the
| | 02:52 |
class and add the key word shared.
Place it after the key word public and
| | 02:57 |
before function.
I'll save those changes and come back to
| | 03:01 |
the main window and see that that error
has gone away.
| | 03:04 |
So now I'll fix the calls to the other 3
functions.
| | 03:07 |
I'll select and copy CalcUtily dot, and
then paste it before the other 3 function calls.
| | 03:15 |
Then I'll go back to the class Calc
Utility and I'll select and copy the
| | 03:19 |
keyword shared and paste it before the
word function in the other 3 function signatures.
| | 03:28 |
I'll save all my changes and run the
application.
| | 03:32 |
Type in some values and test all of my
operations, and see that they all still
| | 03:37 |
work as expected.
So one way of thinking about a custom
| | 03:42 |
class is just as another way of grouping
your code together.
| | 03:45 |
One advantage of using a class over a
module, is that when you look at your
| | 03:50 |
code in a calling scope, you know exactly
where the function is defined.
| | 03:54 |
In contrast, when you use modules, you
can look at the function but it's not
| | 03:58 |
immediately apparent where you're getting
it from.
| | 04:00 |
But the more important thing is that by
using custom classes, you've opened up a
| | 04:05 |
whole level of functionality that's
available in object-oriented programming,
| | 04:09 |
ways of storing functions and data
together so that they can operate on each other.
| | 04:14 |
And we'll get to some of that sort of
functionality in the next movie.
| | 04:18 |
| | Collapse this transcript |
| Organizing classes with namespaces| 00:00 |
As an application gets larger you might
find yourself creating many files and you
| | 00:05 |
might want another way of organizing
them.
| | 00:07 |
Visual Basic provides an architecture
known as Namespaces.
| | 00:12 |
When you create a class you can place it
into its own namespace and you could have
| | 00:17 |
multiple classes in the same namespace.
This way if you have classes where there
| | 00:22 |
are naming collisions, that is two or
more classes that share the same name,
| | 00:26 |
you can distinguish them from each other
by putting them in different name spaces.
| | 00:30 |
To add a namespace to a class wrap the
class declaration in a namespace declaration.
| | 00:36 |
I'm working in the namespaces solution in
a version of my simple calc project.
| | 00:41 |
I'll place the cursor at the top of the
code, and make some space.
| | 00:46 |
Then type in Namespace.
You can add any identifier for the namespace.
| | 00:51 |
I'll call my namespace Utilities.
When I press Enter, Visual Studio adds
| | 00:57 |
the end Namespace clause.
Now to make my class a part of that
| | 01:01 |
namespace, I'll cut and paste all of that
code.
| | 01:05 |
Starting with the class declaration and
including everything through the end
| | 01:09 |
class the calcutility class is now a
member of the Utilities Namespace.
| | 01:15 |
I'll save those changes and then go back
to my main window code.
| | 01:19 |
I'll scroll down to the code where I'm
trying to call those functions and see
| | 01:23 |
that I have some new errors.
Each time I refer to CalcUtility, the
| | 01:27 |
name of the class, I'm now being told
that the class is not declared.
| | 01:32 |
That's because when you take a custom
class, and you put it into a namespace
| | 01:36 |
that's different than the calling scope,
you have to tell the compiler where the
| | 01:41 |
class is.
There are a whole bunch of available
| | 01:43 |
quick fixes here.
I'm going to show you what happens if you
| | 01:46 |
try this one, change CalcUtility to
Utilities.CalcUtility, that will work for
| | 01:52 |
this call.
I'll select it and then scroll back down
| | 01:55 |
and look at the change that Visual Studio
made.
| | 01:58 |
Now it's calling the class and including
the namespace before it.
| | 02:02 |
That'll work but the problem is that I
have to do that for every time I call the
| | 02:06 |
class, it's overly verbose and can become
cumbersome, that fixes this line but I
| | 02:12 |
still have errors on the other three
lines.
| | 02:15 |
So, I'm going to fix this in a different
way, I'm instead going to import the
| | 02:20 |
CalcUtility class into the current class.
You do this with the import statement,
| | 02:26 |
I'll let visual studio do it for me.
I'll move the cursor off that line to
| | 02:30 |
redisplay the error, then look at my
correction options and this time I'll
| | 02:34 |
choose ImportCodeRunner.Utilities.
That adds this line at the top of the
| | 02:41 |
class, ImportsCodeRunner.Utilities, and
in the calls to the classes, all of the
| | 02:46 |
errors have gone away.
I'll save and run the application, and
| | 02:51 |
I'll exercise all of the operations, and
see that everything's working fine.
| | 02:57 |
Now you might be thinking I know where
the Utilities Namespace comes from.
| | 03:01 |
That's what I just put into my Calc
Utility Class right here.
| | 03:06 |
But where does CodeRunner come from?
Why is it a prefix as a part of this Namespace?
| | 03:11 |
And the answer is that, that's the
Namespace that was added to this project
| | 03:16 |
when it was first created.
You can change the root name space for a
| | 03:20 |
project by going to the project
properties.
| | 03:23 |
I'll go to the Project in the solution
explorer, right click, and choose Properties.
| | 03:27 |
And I see two values.
The Assembly Name and the Root Namespace.
| | 03:33 |
The Assembly is a physical file that will
store all of the code for this project,
| | 03:38 |
but a project can have multiple
Namespaces.
| | 03:40 |
The Root Namespace is the namespace that
is assigned for any code file that
| | 03:45 |
doesn't have an explicit namespace.
I'm going to change the root namespace
| | 03:50 |
for this project from Code Runner to
simple Calc.
| | 03:53 |
I'll save that change with Ctrl S then go
back to the main Window VB file and see
| | 03:59 |
that Visual Studio has updated my import
statement.
| | 04:03 |
Correcting it to include the new root
namespace.
| | 04:06 |
This import statement is only good for
the current code file and if you want to
| | 04:11 |
use these functions from any other code
file, you will need to add the important
| | 04:15 |
statement there, as well, or take that
code file and make it a member of the
| | 04:19 |
same namespace as CalcUtility.
Namespaces are similar to Packages in
| | 04:25 |
Java but they differ in an important
respect.
| | 04:28 |
In Java, a package maps to a physical
folder on disk.
| | 04:33 |
So if this were Java I would have a
folder called Utilities.
| | 04:36 |
That was underneath the project root.
You can mimic that behavior in Visual
| | 04:41 |
Basic simply by moving your files around.
And many developers do this, matching up
| | 04:46 |
the folder names with their namespaces.
I'll go back to my project in the
| | 04:50 |
Solution Explorer, right-click, choose
Add and then select New Folder.
| | 04:55 |
And I'll call it Utilities.
Then, I'll click and drag my class file
| | 05:01 |
into the new folder.
Because Visual Basic doesn't
| | 05:05 |
automatically map name spaces to physical
folders, that doesn't cause any changes
| | 05:10 |
in the code.
As long as the compiler knows where the
| | 05:13 |
Visual Basic file is and Visual Studio
manages all the for you, the namespaces,
| | 05:18 |
classes, and functions will be found.
I'll test the application one last time.
| | 05:23 |
And see that everything is still working
just fine.
| | 05:27 |
Use namespaces, sub folders of your
projects, and classes to organize your code.
| | 05:35 |
And then no matter how large your
application becomes, you'll still be able
| | 05:39 |
to find your code easily to maintain it.
| | 05:41 |
| | Collapse this transcript |
| Storing data with instance fields| 00:00 |
In the terminology of object oriented
programming, a field is a variable that's
| | 00:06 |
a member of a class.
And a field that's only available from an
| | 00:10 |
instance of the class is called an
instance field.
| | 00:14 |
Visual Basics supports the use of
instance fields and they're valuable when
| | 00:18 |
you want to wrap both data and
functionality in a custom class.
| | 00:22 |
I'll show how to do this in the solution
instance fields, in a version of my
| | 00:25 |
simple calculator.
I've open my calc utility class that I
| | 00:29 |
created in a previous movie.
This class currently has shared
| | 00:33 |
functions, a shared function is the
equivalent in Java of a static method.
| | 00:38 |
It's available from the class itself,
without having to instantiate the class.
| | 00:43 |
But if you want to work with instance
fields you have to turn these functions
| | 00:47 |
into instance functions and you do that
by removing the keyword shared.
| | 00:52 |
So I'm going to start this exercise by
removing the keyword shared from all of
| | 00:56 |
these functions.
I'll do it for the add, subtract,
| | 01:00 |
multiply, and divide functions and then
I'll go back to my Main Window Visual
| | 01:06 |
Basic file.
MainWindow.xzamel.vb and I'll add code
| | 01:11 |
that creates an instance of that class
and then calls the methods from that instance.
| | 01:16 |
Right here, before the select case
statement, I'll add a bit of space, and
| | 01:21 |
I'll create a new variable called calc
and I'll set its data type as an instance
| | 01:27 |
of my calc utility class.
Then I'll instantiate it with this syntax.
| | 01:33 |
New calc utility.
I'm calling something called a
| | 01:37 |
constructor method.
In Visual Basic, if you create a class
| | 01:41 |
and you don't define a constructor
method, the compiler adds a constuctor
| | 01:46 |
method for you.
It's called a no arguments constructor
| | 01:49 |
method and it simply returns an instance
of the class.
| | 01:52 |
So this is the call to the constructor
method and it returns the instance of the
| | 01:56 |
class and calc is the variable that's
pointing to that instance.
| | 02:00 |
We call this a reference variable.
It's referring to the object in memory.
| | 02:04 |
Now, I'll change the way that I'm calling
these methods.
| | 02:08 |
Instead of using the name of the class,
I'll use the instance variable, calc, and
| | 02:12 |
I'll make that change to all four method
calls.
| | 02:19 |
After making those changes, all of the
error indicators go away.
| | 02:23 |
And I'll run the application and do a
quick test.
| | 02:28 |
And all of my operations still work.
Now, I'm ready to add instance fields to
| | 02:33 |
the class.
I'll go back to calcutility.vb and open
| | 02:38 |
up to full screen.
You declare instance fields as members of
| | 02:42 |
the class by declaring them inside the
class declaration but outside of any
| | 02:46 |
functions or subroutines.
I'll place this new code here.
| | 02:50 |
I'm going to declare two instance fields.
I'll start with the keyword public.
| | 02:55 |
Then the name of the field.
And I'll call it value 1.
| | 02:58 |
And set it's data type to double.
Then I'll do the same thing and create a
| | 03:02 |
second instance field called value 2.
Also data typed as double.
| | 03:07 |
Next, I'll go through each of the
functions and change them so that instead
| | 03:11 |
of receiving arguments, they'll operate
on the two instance fields.
| | 03:16 |
So I'll remove the arguments from
AddValues, SubtractValues and so on.
| | 03:20 |
Then in the return statements for each
function I'll change dbl to value.
| | 03:25 |
And I'll do that with a little bit of
searching and replacing.
| | 03:29 |
I'll go to Edit, Find and Replace, Quick
Replace, I'll type in dbl and replace
| | 03:36 |
with value.
And then I'll click Replace All and the
| | 03:41 |
changes have been made.
Those are all the changes to the class,
| | 03:45 |
each of the operations now operates on
the two instance fields value 1 and value
| | 03:50 |
2, so it's up to the calling scope of the
applcation to set these values and then
| | 03:55 |
call a method.
I'll save those changes.
| | 03:59 |
And go back to my calling scope.
After I've created the instance of the
| | 04:03 |
class named calc I'll assign values to
its instance fields with this code,
| | 04:08 |
calc.value1 equals dbl1 and calc.value2
equals dbl2.
| | 04:14 |
I only have to do this once before I get
into the select case statement.
| | 04:20 |
And now that those values are set I don't
have to pass them into the functions
| | 04:23 |
which no longer accept them anyway so
I'll remove them from the calls to the
| | 04:28 |
four functions.
When I save my changes all of the error
| | 04:38 |
indicators have gone away, so now the
architecture of my application is a
| | 04:42 |
little bit different.
Instead of passing in these values to
| | 04:45 |
each of the four functions I"m setting
them as values that are a part of the
| | 04:49 |
object, the calculator utility object.
And then calling the appropriate method.
| | 04:55 |
I'll run the application and test it with
a couple of values and see that all of
| | 05:00 |
the operations still work.
So I've now shown three ways of
| | 05:08 |
organizing your code starting with
modules, where you simply are sharing
| | 05:12 |
functions with the rest of the
application.
| | 05:15 |
Then going to classes that have their own
shared functions and now showing a class
| | 05:19 |
that's designed to be instantiated and
can store data and operate on that data.
| | 05:24 |
It's your choice as developer which
architecture you choose for your application.
| | 05:29 |
As you get deeper into the use of object
oriented techniques in your own programming.
| | 05:34 |
You might decide as I have that this
approach makes your code easier to
| | 05:38 |
maintain for the long run.
| | 05:39 |
| | Collapse this transcript |
| Controlling member visibility with access modifiers| 00:00 |
In Visual Basic, you're working in an
object oriented programming environment,
| | 00:05 |
and this sort of environment depends
greatly on providing access from one part
| | 00:09 |
of an application to another.
When you define your own custom classes,
| | 00:14 |
you have to say what parts of the
application are allowed to use those
| | 00:17 |
classes, and what parts of the
application can use field, properties,
| | 00:22 |
methods, and other members of the class.
You define this using what we call access
| | 00:27 |
levels, and you indicate what kind of
access level you want to assign, with
| | 00:32 |
keywords called access modifiers.
The most common access modifiers that
| | 00:37 |
you'll see in Visual Basic, are Public,
Protected, Friend and Private, but there
| | 00:43 |
are many others.
Here's what the most common modifiers mean.
| | 00:47 |
The Public Access Modifier is assigned to
classes, fields, or properties, where you
| | 00:53 |
want that code to be available from
anywhere in the application.
| | 00:56 |
When you create a brand new class in
Visual Studio, it automatically adds the
| | 01:00 |
Access Modifier Public to the class,
assuming that you want to make it broadly available.
| | 01:06 |
If you want to narrow the access, you can
do so by removing the Access Modifier, or
| | 01:11 |
changing to another one.
The Protected Access Modifier can be
| | 01:15 |
assigned to methods, properties, or
fields of a class.
| | 01:18 |
And it means that those members of the
class are available both to the current
| | 01:22 |
class, and to any class that is derived
from or inherited from that super class.
| | 01:28 |
The Friend Access Modifier, has to do
with multiple assemblies.
| | 01:32 |
In the .NET framework an assembly is a
physical file, when you create just a
| | 01:37 |
simple application in Visual Basic, its
compiled into a single assembly.
| | 01:42 |
So Friend and Public are pretty
interchangeable, when you're talking
| | 01:45 |
about a single assembly application.
But if you start breaking down your
| | 01:49 |
application into multiple assemblies, say
with a top level application, and then a
| | 01:54 |
library containing common functions, you
can control what code is available to the
| | 01:59 |
application, or just to the code within
the library, by using the Friend Access Modifier.
| | 02:05 |
The Access Modifier Private is pretty
self explanatory.
| | 02:08 |
It means only code within the current
class or in the same source code file,
| | 02:13 |
can access it.
And there's an Access Modifier called
| | 02:16 |
Protective Friend, which means that the
code is available to the same class, or
| | 02:21 |
classes in the same assembly, or in any
class derived from that class.
| | 02:26 |
When you create a brand new class, if you
declare without any Access Modifier it
| | 02:31 |
defaults to friend.
Meaning that it's available to the
| | 02:34 |
current code module, or anywhere within
the current assembly.
| | 02:37 |
And again, in an application that only
exist in a single assembly, that's the
| | 02:42 |
same thing as Public.
If you declare instance field without any
| | 02:46 |
Access Modifier, using just the keyword
Dim, those default to private.
| | 02:51 |
There are many other Access Modifiers
available in Visual Basic.
| | 02:55 |
Here is some of the modifiers you will
see sometimes, but less frequently then
| | 02:58 |
those I've already discussed.
Shadows has to do with inheritance.
| | 03:02 |
You can use the Shadows Access Modifier
to re-declare and then hide an
| | 03:07 |
identically named element, such as a
field or a property in a base class.
| | 03:12 |
And the Read Only Access Modifier defines
a field or property that can be read, but
| | 03:17 |
not written to.
There are also Access Modifiers to
| | 03:20 |
control inheritance including Inherits,
MustInherit, MustOverride,
| | 03:23 |
NotInheritable, NotOverridable, Overloads
and many other.
| | 03:26 |
Take a look at the Visual Basic
documentation and search for Access Modifiers.
| | 03:35 |
You'll find clear definitions of each
Access Modifier, and a discussion of when
| | 03:40 |
it should be used.
| | 03:41 |
| | Collapse this transcript |
| Using properties with getter and setter methods| 00:00 |
There's a common recommendation that
you'll encounter in object oriented programming.
| | 00:04 |
That instance fields, that is fields that
members of an instances of class should
| | 00:09 |
only be made available to the rest of the
application in a controlled way.
| | 00:14 |
When you declare an instance field and
mark it as public, you're allowing
| | 00:17 |
uncontrolled access to that value.
In Visual Basic, you can control access
| | 00:22 |
to that value with properties.
Typically, the model goes like this.
| | 00:26 |
You'll create the field as a private
field.
| | 00:30 |
Instead of using the public access
modifier, use the keyword Private.
| | 00:34 |
There's a common coding convention that
the identifiers or names of private
| | 00:38 |
fields always start with an underscore
character.
| | 00:41 |
That's not required but you'll see it
done frequently.
| | 00:44 |
Now that I've marked these fields as
private, they're not available to the
| | 00:48 |
rest of the application.
If I go over to my main file I see errors
| | 00:52 |
have appeared where I'm trying to refer
to the values and that will be the case
| | 00:57 |
even if I put the underscore in.
Those fields are not available because
| | 01:00 |
they're marked private.
I'm going to make them available though
| | 01:04 |
through properties.
I'll return that code to the way it was
| | 01:07 |
looking for an identifier of value one,
and I'll return to my utility class.
| | 01:13 |
I've declared the two fields as private.
Now I'm going to provide access through
| | 01:17 |
properties that have methods called
getters and setters.
| | 01:21 |
I'll start with value1.
I'll declare a property, which I'll name
| | 01:26 |
value1, and as I would with a field, I'll
set its data type.
| | 01:30 |
On the next line, I'll type End Property.
On its own, the property and End Property
| | 01:35 |
clauses define the value, but don't
define a way of setting and getting its value.
| | 01:40 |
So, I see an error, and when I pull down
the menu of fixes it offers to insert a
| | 01:45 |
missing Get and Set I'll select that
option.
| | 01:49 |
And I see two new pairs of keywords, Get
and End Get and Set and End Set.
| | 01:55 |
These are the getter and setter methods
for the property.
| | 01:58 |
Now I'll add code to pass the data back
and forth.
| | 02:02 |
When the calling code refers to value1,
to get a value that will result in
| | 02:07 |
calling the getter method.
And I'll return underscore value1.
| | 02:11 |
And when it tries to set the value, it'll
pass it in as this named argument, named value.
| | 02:16 |
And I'll take that value, and pass it to
my private field, with _value1 equals value.
| | 02:21 |
I'll save that change, and go back to my
calling VB file, and see that the error
| | 02:28 |
has gone away.
Now, when I refer to .value1, I'm
| | 02:32 |
referring to the property, and when I
retrieve the value, the getter will be
| | 02:36 |
called, and when I pass it in, it'll call
the setter method.
| | 02:39 |
I'll make the same change for the value2
property.
| | 02:42 |
Because most of this code is pretty much
the same, I'm just going to copy and
| | 02:46 |
paste it.
I'll select everything from Property to
| | 02:49 |
End Property.
And copy and paste.
| | 02:52 |
For the second one I'll change all the
references from value1 to value2.
| | 03:00 |
(SOUND) I'll come back to my calling
scope and see that the error has gone
| | 03:06 |
away there too.
And then I'll test the application, enter
| | 03:10 |
some values and click the various
operator buttons and see that everything
| | 03:14 |
is working fine.
Once you've implemented properties with
| | 03:19 |
getters and setters you have places where
you can add code, to validate the
| | 03:23 |
request, modify data before you return it
and otherwise control how the data is accessed.
| | 03:30 |
To follow good object oriented
programming standards.
| | 03:33 |
It's recommended that you always set your
fields as private and then provide access
| | 03:37 |
to them through properties.
| | 03:39 |
| | Collapse this transcript |
| Using constructor methods| 00:00 |
In object or indi terminology, a
constructor method is a procedure that
| | 00:05 |
returns an instance of a class.
In some languages you define constructor
| | 00:09 |
methods using the same name as the class.
In Visual Basic you create a subroutine
| | 00:15 |
with the name new.
I'm working with the class CalcUtility
| | 00:18 |
with a version of my project called
Constructors.
| | 00:22 |
When you define a new class and you don't
define an explicit constructor method one
| | 00:26 |
is created for you by the compiler and
right now I'm instantiating my
| | 00:31 |
calcUtility class by calling the
automatically generated no arguments constructor.
| | 00:37 |
I'm going to change this class so that
its one and only constructor method
| | 00:41 |
requires two arguments.
The two values that I'm passing in.
| | 00:45 |
And I'll then be able to change the way
I'm coding so that instead of
| | 00:48 |
instantiating and then passing the values
in, I'll pass them in at the same time as
| | 00:53 |
I construct the object.
I'll go to my utility class and I'll
| | 00:57 |
place the cursor after my properties but
before any of the existing functions.
| | 01:03 |
And I'll create a new subroutine that
I'll call New.
| | 01:06 |
I'll pass in two values dbl1 As Double
and dbl2 As Double.
| | 01:12 |
When I instantiate the class and I pass
two values in that will create the new
| | 01:17 |
object and I can assign the values as
needed.
| | 01:20 |
And I'll assign then by referring to the
properties.
| | 01:22 |
I'll say value1 equals dbl1, and value2
equals dbl2.
| | 01:28 |
I'll save those changes and go back to
the calling scope, my MainWindow.xaml.vb file.
| | 01:35 |
And I now see an error indicator has
appeared.
| | 01:38 |
That's because I've defined an explicit
constructor method and the rules are that
| | 01:43 |
once you've defined an explicit
constructor method the compiler won't
| | 01:46 |
create a no arguments constructor method
for you.
| | 01:49 |
If you want that no arguments constructor
method, you can define it.
| | 01:53 |
Visual Basic does let you overload or
create multiple versions of a particular
| | 01:58 |
method but for my purposes this is the
only constructor method I need.
| | 02:02 |
The one that receives two arguments.
As I call the constructor method I'll
| | 02:07 |
pass the methods in as dbl1 and dbl2.
Now those values have been set, and I no
| | 02:14 |
longer need to set them in separate
statements.
| | 02:17 |
So, I'll select these two lines of code
and comment them out.
| | 02:22 |
So, let's review the code.
I'm now calling the constructor method
| | 02:25 |
with two arguments.
It's defined in the utility class.
| | 02:30 |
And the constructor method is named New
as its called it takes the values that
| | 02:34 |
are being passed in and saves them
through the properties to the private fields.
| | 02:39 |
I'll run the application and test and
make sure that everything works the way
| | 02:43 |
it did before.
Contructor methods are a critical part of
| | 02:49 |
object oriented programming practices.
The most important thing to remember
| | 02:56 |
about Visual Basic, and what makes it
different from C style languages, is that
| | 03:00 |
the constructor methods don't share the
name of the class itself, as they do in
| | 03:03 |
the other languages.
The most important thing to remember
| | 03:08 |
about Visual Basic and it's constructor
method syntax is that the name of the
| | 03:12 |
constructor method is always the same,
New.
| | 03:15 |
And it is not the same as the name of the
class as it is in C style languages.
| | 03:20 |
| | Collapse this transcript |
| Defining shared values as class fields| 00:00 |
In an application with many functions,
it's a good idea to organize your code,
| | 00:05 |
to group both methods and values
together, and object-oriented programming
| | 00:09 |
architectures help you do that.
In a previous movie, I described how to
| | 00:14 |
create shared functions, using either
modules or classes, and now I'm going to
| | 00:18 |
describe how to move fields into classes
as shared fields.
| | 00:23 |
I'm working in a version of my solution,
called shared fields.
| | 00:26 |
And in the current version, there is a
set of constants in the main class named
| | 00:31 |
add, subtract, multiply, and divide.
These constants are related to the
| | 00:36 |
calculation functions, and so it makes
sense to move them into the utility class
| | 00:40 |
that's executing those functions.
I'll start in the main window VB file and
| | 00:46 |
I'll copy these constants to the
clipboard.
| | 00:48 |
Then I'll go to my CalcUItility VB file
and I'll place the cursor after the class
| | 00:53 |
declaration and before the private field
declarations and paste the constants into place.
| | 00:59 |
Next, I'm going to change the way these
constants are declared so that instead of
| | 01:03 |
being constants, they're shared fields.
That means they'll be available from the
| | 01:08 |
CalcUtility class.
I'll go to the first one and take out the
| | 01:13 |
keyword const and replace it with public
shared.
| | 01:16 |
Then, I'll get rid of the other constant
declarations and add commas after the end
| | 01:24 |
of the first three lines.
I'll select these three lines and tab
| | 01:29 |
them in to make clear that this is a part
of the same declaration.
| | 01:33 |
And now it's clear that Add, Subtract,
Multiply and Divide are all public,
| | 01:38 |
shared values of the Calc Utility class.
Now I'll go back to the main window class
| | 01:43 |
and I'm going to get rid of the constants
in the main window.
| | 01:46 |
I'll just comment them out.
Then I'll build the application and find
| | 01:54 |
all of my errors.
An error will occur in each place where
| | 01:59 |
I'm referring to the constant that used
to be declared in the main window class.
| | 02:03 |
Because it's now a member of the
CalcUtility class I need to add that
| | 02:07 |
class name as a prefix.
I'll do that for the Add Constant here,
| | 02:14 |
then I'll select and copy the name of the
class and the period.
| | 02:18 |
And paste it on all the other
occurrences.
| | 02:23 |
As I do this, the errors are going away.
I'll double-click on the next error to
| | 02:27 |
get me to the next problem, I'll paste it
here, and here, and I'm almost done with
| | 02:33 |
this operation and there's the last one.
So now those values, add, subtract, and
| | 02:39 |
so on, are declared as part of the
utility class that makes the most use of them.
| | 02:44 |
| | Collapse this transcript |
| Sharing data from classes with read-only properties| 00:00 |
One of the purposes of object-oriented
design patterns is to hide complex
| | 00:05 |
operations inside classes.
And then, only expose the results,
| | 00:09 |
without showing how the work is being
done.
| | 00:11 |
One of the tools that Visual Basic
provides for this purpose is a read only property.
| | 00:16 |
A property that can be set from within
the class, but then only read from
| | 00:20 |
outside it.
I'll show how to create a read only
| | 00:23 |
property, and then complete this exercise
by moving all the complex functionality
| | 00:27 |
of doing calculations into my calculation
utility class.
| | 00:31 |
I'm looking in the read only solution,
and I'll start in the CalUtility.vb file.
| | 00:40 |
Currently, I have the four functions,
AddValues, SubtractValues and so on,
| | 00:43 |
which are returning values directly from
the functions.
| | 00:46 |
I'm going to change this code so that
instead of returning values, they're
| | 00:52 |
simply setting a value.
I'll add a new private field that I'll
| | 00:56 |
call result with an underscore prefix.
And as with the other fields, I'll set
| | 01:01 |
the data type to double.
Next, I'll declare a property named result.
| | 01:06 |
Once again, data type is double.
And as before, I'll add the end property clause.
| | 01:12 |
Now, I'm going to mark the property as
read only.
| | 01:16 |
I'll add the keyword Readonly before the
Property keyword.
| | 01:21 |
After I've added it, I see a little
squiggly line telling me that there's an
| | 01:24 |
error, so I'll pull down the last of
available fixes.
| | 01:27 |
And see that Visual Studio is offering to
insert a missing get method.
| | 01:32 |
When you mark a property as read only,
you must have a getter method.
| | 01:36 |
So I'll click that option, and that
creates my Get and End Get keywords, and
| | 01:41 |
I'll add the code Return_result.
So now the class has a Result property,
| | 01:47 |
and here's what I'm going to do with it.
I'll go down to all the functions at the
| | 01:51 |
bottom, AddValues, SubtractValues,
Multiply and Divide.
| | 01:54 |
And I'm going to change them from
functions into subroutines.
| | 01:59 |
I'll select that much code, then I'll
select Edit, Find and Replace, Quick Replace.
| | 02:05 |
I'll look for the word function and
change it to sub.
| | 02:08 |
And I'll click on Replace All.
Next, I'll look for all the return
| | 02:14 |
statements in this section, and I'll
change them to _results equals.
| | 02:18 |
And now instead of returning a value from
the function, I'm simply using a
| | 02:23 |
subroutine and setting the private field
value.
| | 02:26 |
I'll make that change to all four
operations.
| | 02:37 |
So far, so good.
I now have a read-only property named
| | 02:40 |
result that can be read by the calling
scope.
| | 02:42 |
And it's returning the value of the
private field, which in turn is being set
| | 02:46 |
by these subroutines.
Now, I'll make some fixes to my main
| | 02:50 |
window code.
In the select case operation, I'm looking
| | 02:55 |
at each of the possible values for the
operation, add, subtract, and so on, and
| | 02:59 |
calling the appropriate procedure.
But right now, I'm expecting the
| | 03:03 |
procedure to return a value, and it
doesn't anymore.
| | 03:06 |
So, I'm going to change this code to
simply call the procedure, but not expect
| | 03:10 |
return value.
Next, I'll take this conditional code
| | 03:16 |
that's in the divide section and I'm
going to move it outside of the select
| | 03:20 |
case statement.
And now instead of referring to a local
| | 03:28 |
variable called Result, which is
currently declared here.
| | 03:31 |
I'm going to be referring to the result
property of the utility class.
| | 03:35 |
So, I'll get rid of that declaration, and
then go down to the conditional code
| | 03:39 |
where I'm looking at the result and
change it to calc.result.
| | 03:43 |
Looking at the result property of the
instance of the utility class, and I'll
| | 03:49 |
do the same thing in the call to display
result.
| | 03:53 |
I'll get out of full screen mode and look
for any errors.
| | 03:57 |
In the utility class, when I changed
these functions to subroutines I
| | 04:01 |
neglected to take off the declaration of
their return values.
| | 04:05 |
So, I'll get rid of those, removing the
as double clause fro the end of each declaration.
| | 04:16 |
To completely test the application, I'll
build it, see that I don't have any
| | 04:21 |
errors and I'm ready to test again.
I'll run the application, type in some
| | 04:26 |
values and test all four operations and
see that they all still work.
| | 04:32 |
So, this is just a different coding
style.
| | 04:34 |
Instead of using functions that return
values within my utility class, I'm
| | 04:39 |
exposing the return value as a read-only
property.
| | 04:43 |
I don't think there is any particular
advantage of this approach over the other one.
| | 04:46 |
They're both available in Visual Basic as
coding styles for object-oriented programming.
| | 04:52 |
But the important thing here is that
you're able to declare these read only
| | 04:56 |
properties and make them available for
reading in the rest of your application.
| | 05:00 |
But reserve the ability to write these
values only from within the current class.
| | 05:05 |
| | Collapse this transcript |
|
|
ConclusionNext steps| 00:00 |
Thanks for watching this course, Visual
Basic Essential Training.
| | 00:04 |
You can use the most recent version of
Visual Basic to build many different
| | 00:08 |
types of applications.
To learn more, check out these lynda.com courses.
| | 00:13 |
To learn more about working in Visual
Studio, watch Visual Studio 2012
| | 00:17 |
Essential Training.
For web applications, you can watch
| | 00:21 |
ASP.NET Essential Training, or ASP.NET
MVC 4 Essential Training.
| | 00:26 |
And there are also courses available
showing you how to build Windows Store
| | 00:30 |
apps for Windows 8, and Windows RT, and
apps for Windows phone.
| | 00:34 |
Regardless of which type of applications
you want to build I hope that this course
| | 00:38 |
has helped you get started.
| | 00:39 |
| | Collapse this transcript |
|
|