 Hi, I'm Bob Tabor with Developer University and I welcome you to this course covering the fundamentals of the visual basic programming language. And we're going to talk about programming topics in general. This is designed specifically for absolute beginners to programming. Now, if you're already an experienced software developer coming from another software development platform or programming language, then frankly this series of lessons might move much too slowly for you. You might be better served finding another resource to use as a starting point, one that has you the experienced beginner to visual basic in mind. Microsoft Virtual Academy has many great courses designed for people at all skill levels. So I recommend that you start your search for the level of course that's right for you at Microsoft Virtual Academy. However, if you are completely new to programming and you're new to the visual basic programming language and you're new to building applications on the Windows platform, then this perhaps is the best place for you to start. Not only will you and I work together to learn the syntax of visual basic, but I'm going to take the time to walk through everything that we do together. One other quick caveat before we get started here. This flavor of visual basic is not for creating macros in Excel or other Microsoft Office tools. That's actually an entirely different tool called visual basic for applications or VBA. Yes, visual basic and visual basic for applications will look similar in some ways, but what you can do with them is extremely different. So if automating Microsoft Office applications is your end goal, then I strongly recommend that you research on Microsoft Virtual Academy for courses related to visual basic for applications or VBA. I'm sure you'll find what you're looking for there. But assuming that you know that you want to work in visual basic proper and build .NET applications, then you're in the right place. I'll explain what we're doing, but more importantly, I'm going to explain why we're doing it, the thought process behind what we're doing. I'm going to try to anticipate the questions that you might have, anticipate the problems that you might run into as you're typing your very first lines of code into the code editor and visual studio or as you're working through some of the exercises that we're going to work through together. Now I've literally taught hundreds of thousands of people visual basic over the past 14 years. That's actually no exaggeration. This includes children as young as eight years old and as young as 80 years old from virtually every corner of the world. They've all learned from a version of the very course that you're watching right now, a previous version of this course. And I know that you can use this course to learn too. In fact, this is the sixth iteration of this course that I'm teaching dating all the way back to 2005. And over the years, I've incorporated the feedback from thousands of students feedback and suggestions on how to improve the course. And I've incorporated those in the in the effort of putting forth the very best course that I possibly could to help you get started and get your feet wet in visual basic. So I only make one real assumption as we begin this course and that's that you already have some version and addition of visual studio installed on your local computer and that you're ready to write your very first lines of code. So if you don't already have visual studio installed, then please, by all means, visit visual studio.com where you're going to learn about many of the free and commercial versions of visual studio that are available and what the differences are. Now personally, in this course and what I use when I'm not recording videos is the visual studio 2015 community edition. It's one of the free versions that you'll find on visual studio.com. You can see it in this particular version of their website right here with this green button you can get started downloading community 2015. But I want to emphasize that you can use any addition and any version of visual basic with the lessons that I'm going to teach. There might be tiny user interface differences between what you see on my screen and what you see on your screen. However, I think you're going to find that as you work through the videos, there's really no difference in the language itself. I'm not going to be focusing on any of the specific features of visual studio. So hopefully that won't prevent you from following along no matter what. Now there will be other courses on Microsoft Virtual Academy that will demonstrate the power of visual studio proper. All the features that visual studio has to offer how you can improve your workflow with visual studio videos that explain the differences between the various versions and additions. But I'm not going to focus on that in this course. I'm going to focus specifically on the basics of the visual basic programming language itself. And what I want to demonstrate will be true no matter which version or addition of visual basic that you choose to use. And that's great news because as long as there's a visual basic, these lessons should still be valid and useful no matter what. Now to get the best or the most out of this or any course that you'll find online, you should become what I call an active learner. That takes several different forms. First of all, you should attempt to follow along as closely as possible and do what I'm doing in the video inside your own copy of visual studio. I call this getting your hands dirty in the code actually writing the code that I'm writing on screen. You're writing it, I'm writing it, we're working together to actually work through these lessons. There's no better way to learn to code than to actually write the code yourself, not just watch the video on screen. It's like suggesting that somebody learned how to play guitar, but only by watching videos, not by actually holding a guitar in their own hands and strumming the chords. And if I were to say, well, here I'm going to teach you guitar, but don't touch the guitar, you say, well, that's virtually impossible. The same is true with code to some extent. You want to build muscle memory by typing in the code on your own. Typing in the code yourself will give you insights that merely watching the video will not give you. So do this, pause the video, rewind the video, rewatch portions of the videos if you need to. I'm going to make the code available that I type in. You'll be able to download it from wherever you're currently streaming this video on Microsoft, Microsoft Virtual Academy. And you should only use that to compare the code that I wrote versus the code that you wrote, not to just open the code up and run it and see what I wrote. Write it yourself. That's important. You should be typing everything in your own copy of Visual Studio, running on your own local desktop or laptop. Also, don't feel compelled to rush through this course. If something doesn't make sense, again, pause the video, rewind the video, rewatch those portions that don't make sense at first because after rewatching them and seeing the nuances or understanding, hearing me more completely might help unlock things in your mind. Sometimes a second or third viewing, focusing specifically on what's going around the screen in all the corners of the screen and on the words that I'm actually saying can help a lot. So being an active learner also means that you're taking control of the learning process. So if I say something or do something that really doesn't make sense, then by all means, find a second or a third resource online that can help you out. Maybe it's an article out on msdn.microsoft.com or maybe it's other videos on Channel 9 or Microsoft Virtual Academy, but life has more than one teacher. So if something I say doesn't make complete sense to you and you need to hear it from somebody else by all means, find some additional resources that can help you. Make sure you search out those resources that resonate well for you personally. If you're interested in a more comprehensive version of this course, except for the C-Shar programming language, well, that's something that I can help you out with on my own website, devu.com at www.devu.com. I have a course that spans 30 hours that has coding challenges, 30 hours of video instruction, also quizzes and cheat sheets and a lot more. So please visit me at devu.com. You're also going to find many other interesting training courses on my website that I've created specifically to help you become a professional software developer someday. So if that's what your goal is, then maybe I can help. And then furthermore, over time as we go through this course and as I begin to field some questions about it online, I might add some additional study resources and additional free content available for you here on this website. So make sure that you visit frequently. And like I said earlier, if you're new to programming, this is a resource that can help you out. I'm really excited for you if you are just getting started. Learning to write applications is one of my life's passions. It's extremely gratifying to breathe life into your imagination and to watch your creations actually come to life and watch other people actually than using your applications. And Visual Basic holds a special place in my heart. I learned the basic programming language when I was 12 years old. That's like 34 years ago. And I did it on my very first computer, Commodore 64. Then after college, I found Visual Basic and I realized that I already knew the language part and the visual part was really easy to pick up. It was one of the first applications of its kind that allowed you to visually design forms on screen by dragging and dropping components from a toolbox onto a form designer. Now the basic language is actually an acronym for, as you can see here on Wikipedia, Beginners All Purpose Symbolic Instruction Code. It's a more human readable programming language than other programming languages, but that readability, that human readability comes at a price. It's a little bit more verbose, meaning that you have to use more keystrokes to build your code instructions. Some other programming languages like C-sharp require that you type in less instructions to accomplish the same thing. And primarily for this reason, some professional software developers prefer other languages like C-sharp over Visual Basic. However, there's virtually no difference between applications that are created using C-sharp and applications that are created using Visual Basic because they both end up creating a .NET assembly whenever you compile your source code that you wrote into an executable. Or rather, a .NET assembly. Now I'll explain the technical details around that a little bit later in this course, but if you're just learning to code, in my opinion, go ahead, use whatever tool that helps you understand the concepts and helps you get your feet wet in software development. Later on, you can graduate to other languages because frankly, many of the concepts that you learn in Visual Basic, they're going to transfer almost directly over to C-sharp. And there's very little that you'll have to learn additionally in order to make that transition. It'll just be shortened forms of some things, okay? So when you're getting started, you're embarking on a really exciting journey that's immersive and it's personally and professionally rewarding. And best of all, I know you can do this. Again, I've seen so many people start off where you are right now assuming that you're just getting started. And they've worked through the lessons and they've worked nights and weekends to teach themselves how to code. And now they're working professionally writing code for a living or building real applications that are being sold in apps like in app stores like the Windows Store. So if you've ever gotten stuck in the past trying to learn how to program, I promise that if you put the time in and you put the effort in and you work along with me, as you and I work together, we're going to build your knowledge of Visual Basic and you'll be well equipped to take on more advanced tutorials after this course. You can even learn how to build web applications and Windows applications, Windows Store applications so apps that can be sold in the Windows Store. You can learn how to create cloud services and video games and even applications that run on iOS and Android all using simply Visual Basic. So again, assuming that you have some version and addition of Visual Studio already installed on your local computer and you're ready to go, then we're going to begin in the very next lesson, Writing Visual Basic. And I hope you're excited because hopefully you can tell I am. I'm really excited to get started. This is so much fun. So let's go ahead and get started together and I'll see you there in that next lesson. Thank you. Let's take a look at how to install Visual Studio using the custom option. For this example, we'll use the Community Edition of Visual Studio 2015. In order to get it, simply visit visualstudio.com and click on the Download Community 2015 button. Once we've clicked on the download, it'll download to our computer and it's a web installer. So we click on the Run button and it will initiate the installation routine for Visual Studio Community 2015. Once we have the options screen available, it's time to start looking at customizing the installation of Visual Studio. For the most part, the default allows you to create web and desktop type applications. But if you want to create different styles of applications or include more languages, then the custom option is what you should be choosing. I always recommend selecting the custom option for the installation of Visual Studio 2015 to ensure that you're getting the packages and libraries that you need to create the applications you may wish to use. So by selecting Custom and clicking on the Next button, we are now brought to the screen where we can select the different features. The first option is Programming Languages. And if we click the arrow to expand it, we can see that we have Visual C++, Visual F-sharp, and the Python tools for Visual Studio that are additional programming languages that will get installed if you select this option. Remember, by default, Visual Studio Community Edition will only install C-sharp in Visual Basic Templates. Also notice under Visual C++, we have options for the common tools, the Microsoft Foundation classes, and then Windows XP support for C++. For my purposes, I like to have all of my programming languages available to me because they create projects using the different languages all the time. So I'm going to select the checkbox next to Programming Languages to install all of those programming types. Also, under Windows and Web Development, we can choose various options here for things such as the Quick Ones Publishing Tools, SQL Server Data Tools, PowerShell Tools for Visual Studio, Silverlight Development, etc. Here's a very important component. If you want to develop universal Windows applications, we need to ensure that we have the tools, the emulators, and the SDK. Now, you can choose the default install of Visual Studio and then come back and install the Windows 10 SDK at a later time, and that will include the tools, the SDKs, and emulators for you, but it's so much easier to install these during the installation of Visual Studio. Please note that it will increase the install size of the application, so the tool set will be much larger. So again, depending on what it is that you want to do, you may want to select the Universal Windows App Development Toolkit, PowerShell tool for Windows, or for Visual Studio rather, if you want to be using PowerShell tools within your applications. If you need backward compatibility for Windows 8.1 and Windows Phone 8.0 and 8.1, you can select this option. Also, there are some common tools or cross-platform mobile development tools. These are important if you want to develop applications using the Xamarin platform. Xamarin is a cross-platform tool that allows you to create applications for Windows Phone, for iOS devices, and for Android devices by using the C-Sharp language in Visual Studio. All of these tools are available for the cross-platform mobile development using Xamarin platform. It includes all of the emulators as well, so again, remember, it will increase the size of the install base for Visual Studio. You might also notice that because I selected the cross-platform mobile development tools, we now have a little box inside the Windows 8.1 and Windows Phone tools. If we expand that, we'll see that it has included tools and Windows SDKs. And the reason it does that is because there's a potential that you may want to target Windows Phone 8.0 or 8.1 applications, so the tools and SDKs will also get installed. At the same time, the common tools checkbox includes a little square box indicating that we have also added another component here, and that is the git for Windows. So we can install git, which is your source control, git hub extension for Visual Studio so that you can integrate with git hub source control projects, and then of course an extensibility tool to update three for Visual Studio as well. You'll notice that by selecting all of these options, setup can require up to 48 gigabytes across all of the drives that we'll install it on. So again, review each of the items that you have selected to ensure you have all the necessary components, tools, and SDKs for your development tools of choice or platforms of choice, and then select the next button. Once you do, you basically see a quick little selected features screen that will tell you all of the different items that you have selected, and by clicking install you'll agree to the license terms of all the software components. If you're not sure what those are, each one of the items that has license terms allows you to click on it to view those. Once you're satisfied with it, click the install button, and Visual Studio starts installing all of the components that you have selected. So this is a quick overview of how to perform a custom installation of Visual Studio 2015. Hi, I'm Bob Taber with Developer University. For more of my training videos for beginners, please visit me at devu.com. In this lesson I want to show you how to build a super simple visual basic application, a Hello World application. It'll simply display the message Hello World in a console window on your computer. Now, I'm not going to attempt to even explain why I'm doing what I'm doing. The focus will purely be on what and how I'm doing it. In other words, I want you to focus on the workflow at this first pass. How to create a new project? Where do you type your visual basic code? How do you test your application and actually see it running as you're building the application? What do you do if you actually mistype code? How do you fix the problems that pop up? And how do you save your project to disk? And things like that. And so for now, just try to follow along and do exactly what I'm doing. Don't worry if something doesn't really make sense just yet. That's really what the rest of this course is for. We'll get to it. I promise we'll explain everything. In the next few lessons, we're going to dissect this tiny little application that we're going to build here. And I'll explain at that point why we did what we did, the purpose behind everything. Again, like I said in the introduction to this course, I'm going to assume that you have some version and addition to Visual Studio already installed. Even if your Visual Studio looks a little bit different than what you see on my screen, that's okay. The basics are the basics no matter what. So let's go ahead and get started. And I'm going to go to the File menu and select File, New Project. That'll pop open the New Project dialog. And this is important. If you get lost on this step, you're going to be lost, significantly lost. So take a moment and really pay attention to what you're doing here. Make sure you're in the installed templates here on the left-hand side. You're going to see a number of languages and tools over here now beneath the word templates. You must make sure that you have selected Visual Basic. If not, you're going to wind up with a weird template and you're not going to know what to do next. I've gotten enough comments through the years to know that this is a frequent mistake that people make. So make sure that you select Visual Basic and then you'll see a list of template types. And we'll talk about what templates are a little bit later in this course. But for now, we just want to make sure to select Console Application. We're going to use the Console Application template pretty much exclusively throughout this entire course until we get to the very end. And so you'll always want to make sure to choose Console Application. The next thing we're going to do is give our new application a name. When we change the name, there will be some changes to the solution name here below it. And so I'm going to type in the word Hello. Capital H, Hello. Capital W, World. Notice that I didn't put any spaces between the words Hello and World. And then you'll see that that same word is typed here. I'll show you what that means a little bit later on. By default, it's going to put your new projects into your Documents folder. And so for me, my user on this computer is Bob. And Bob has a Documents folder. You're probably familiar with that. And inside of there, there will be a Visual Studio folder with the year or rather the version of Visual Studio that you're currently using. In my case, 2015, it could be 2050. I don't know. Whenever you're watching this course. And then finally, there's a subfolder called Projects. And that's where we want to start off by saving all of our projects. You could change this and put this someplace else. But if you keep it here, then you always know where to find your projects. Now, if there's any other selections to be made here, and it might depend based on which edition of a version of Visual Studio that you're actually using, just make sure that if there's an option to create a directory for the solution, make sure that that is turned on. But everything else can be turned off. You can ignore every other little message that pops up or click the OK button to create our new project. Visual Studio goes off and does some work for a moment or two. And ideally, you have this little window in the upper right hand corner called the Solution Explorer Visible. This is going to show you all the files and things that are associated with the project. We'll come back and talk about that later. Here in the main area, you'll see a tabbed area called Module 1.VB, hopefully opened up. And inside here, we're going to make some room for ourselves. We're going to put the little carrot there on line four. I'll hit the Enter key on the keyboard a couple of times just to make some space for what comes next. We're going to type in some code. I'm going to type in the word Console because I want to work with a console window. And I'm going to hit the period key on the keyboard. And I want to write a line of information to the screen. So I'm going to use this write line method. We'll talk about methods in just a little while. Write line. And I'm going to give it the message that I want to be typed in. So I'm going to use double quotation marks. And I'm going to type the word Hello, Space, World. Whatever I type inside of these two double quotes, this will actually be displayed to screen. We'll come back to that in just a moment. And then I want to make sure to write one more line of code, console. And you'll see little windows pop up with information and messages that can be distracting at first. But actually, this all comes together and it becomes one of the most useful features of Visual Studio. So ignore it for now. We'll pay attention to what it is a little bit later. Just type all the way through what I'm telling you to type right now. Read line. And then we're going to use an opening and closing parentheses, but nothing inside of it this time. Okay. So the next thing we want to do is save our work. And I'm going to hit the little icon on the toolbar. Save all. It has two little disks next to each other. And you'll see the little yellow line here turns into a green line, letting us know that everything's been saved. And then you should be able to find a little green arrow with the word Start next to it here on your toolbar. Now, sometimes you may not see these based on some of the default settings, or you may have accidentally moved some things around. Just about everything you see on the toolbar can also be found in the menus. So for example, in the file menu, there's a save all option. And then in the debug menu, there's a start debugging. So if there's something that you don't see on your toolbar that you see on mine, just look through the menus and you might find it there. But ideally, it would be here on your toolbar. I'm going to click the Start button. And you'll notice that the appearance of Visual Studio changes a little bit. And then off to the side, a console window pops up with the word Hello World with a blinking cursor. Awesome. All right, so we built our first application. How do we stop the application? There's two ways. I could click the little X button here in the upper right-hand corner, or I can hit the Enter key on the keyboard. The application will stop executing and now we're back into edit mode in Visual Studio. Back here in the code where we could modify it and make changes. So you can see that Visual Studio is now returned to its original state. And you might see some other windows pop open from time to time. You can safely ignore those for now. Now, what if your experience was vastly different from my experience? So for example, what if you type the code out but you see an error message pop up when you actually attempted to run the application or start the application? You get this little error message that says there were build errors. Would you like to continue and run the last successful build? Select No. And then what you should see is a list of errors pop up. A list of errors here in a little window called the error list. And in this particular case, you can see that I get a little notification of the issues. And if I were to click on one of them, it would take me to the line of code where that error was actually manifested. Now, the error list popped away, but if I hover my or click on the error list here in the bottom, it will pop back up for me. So it goes away, it pops up. All right, so you can feel comfortable with moving around Visual Studio to that extent. Also, if I hover my mouse cursor over this little red squiggly line, it will say that there is a declaration expected. The reason for this particular error is because you wrote the code in the wrong place. You may have placed it between the module and end module keywords, but not between the sub and sub. Again, ideally this code belongs right here between the sub main and the end sub. You need to put it right there in the middle. And so that's probably one of the first and most important messages is that it matters where you type your code. And I'll explain what a sub is versus a module. There are other kinds of code blocks as we'll come to understand as we continue through this series. But that's one potential error that you could have run into. You saw how Visual Studio tries to tell us that there's a problem with the red squiggly line. It also gave us a list of errors. Now, once we fix those errors, notice that the error list is clean. So you can see also that it tells us that there's zero errors with our code. Awesome. Alright, so maybe you had a different problem. Maybe you see an error that looks something like this and you get a red line completely underneath it. You try to run the application. You get that same little there were build errors message in a message box. You click the no button and you see something like redine. Notice there's no well and redline is not a member of console. Now, admittedly, since we don't know visual basic very well at this point, the messages are not as helpful. But the fact that the error is happening on this line means that we can take a moment and really, really try to investigate what the problem is. And in this case, if you really look at it carefully, you'll notice that I'm missing the L in redline. So precision is extremely important as you're typing code. You have to type exactly what I type in order to get the results that I get. So even if you deviate by one little character, it can unfortunately stop the execution and the compilation of your code. So in this case, we just have to add the L in redline and we're good to go again. You can experience something similar if we misspelled the word console. In this case, you'll see that Connell is not declared. It might be inaccessible due to protection level. Now here again, the problem is we misspelled the word console. But once we fix it, then the error will go away and we can run our application again. Or perhaps you didn't use double quotation marks. And you see that Hello World has no double quotation marks around it. And you get two different error messages whenever you attempt to run the application. One says something about a comma. The other one says hello is not declared. It might be inaccessible. Or not as familiar with Visual Basic. At this point, the messages might throw us for a little bit of a confusing loop. But the remedy is easy. Again, precision is important. We have to surround that message in this case with double quotation marks. And I'll explain why in an upcoming lesson. What that really is telling Visual Basic, the Visual Basic compiler. But that's how we would fix that issue. So again, I think that making sure that you follow my instructions carefully, making sure you type the code where I type it, not outside of one of the code areas like I've designated. Like I've tried to call your attention to, but rather in the right spot. And then making sure you spell everything correctly. That is the key to moving forward whenever you run into issues. It's probably not Visual Basic or you have a problem with Visual Studio. Some people will say is my version of Visual Studio different than yours because I typed this out and it won't run for me. And invariably what happens is they've done something incorrectly when they typed in the code. So typing in code is an exercise in precision. You've got to make sure that it's exactly what you see on your screen and what you see on my screen is identical, okay? All right, so assuming you've got this to work, then you're well on your way to building applications. You've already learned some of the most important lessons so far, whether you realize it or not. As you undoubtedly learned in this lesson, writing Visual Basic code is an exercise in preciseness. However, frankly, Visual Basic is probably the most forgiving of programming languages because it will always nudge you in the right direction, at least as often as it can. Or at the very least, it's going to show you where the problem was by putting a little red squiggly line or something along those lines, giving you errors in the error list that you can work from. So in the following lessons, we're going to begin focusing on two things primarily. First of all, why we did what we did here. What happens whenever we create a new project? What happens when we click the Save All button? What happens whenever we click that Start button to actually run our application? So that's number one. Number two, we're going to focus on the syntax of the Visual Basic code that we wrote. So if preciseness is required, then you're going to need to have some explanation as to what all the words and the symbols that we've been using here, the use of the period, the use of the opening and closing parentheses, the use of the double quotation marks. What do all these mean? And honestly, it's really easy once you get started. Once you get a few basics under your belt, I think you're going to see that writing Visual Basic is almost as easy as writing English into Microsoft Word. Okay, so anyway, we'll see you in the next lesson. Thank you. Hi, I'm Bob Tabor with Developer University. For more of my training videos for beginners, please visit me at devview.com. In this lesson, we want to start with the process of dissecting this tiny little application that we created. Previously, I wanted you to focus on the workflow, what we did and how we did it. Now, I want to focus on why we did what we did. It's crucial that we cement these ideas in your mind because they really provide the basis, the foundation for everything else that comes next after this. So what I want to do is start on the inside and work our way out. And whenever you learn how to write applications with Visual Basic, learning the syntax of Visual Basic, or in other words, learning the nouns and the verbs and the punctuation of the programming language, is really just half of the battle. The other half of the battle is learning about related pre-built functionality that's available to the programming language. So in our case, Microsoft has created something called the .NET Framework. And while that sounds a little mysterious, it's actually not all that bad. For now, there's really just two parts of the .NET Framework that really concern us. First, there's a class library, which is simply a library of code that Microsoft wrote to take care of difficult tasks so that we as developers actually who will utilize or borrow from that library, we don't have to build that code ourselves. We can just rely or borrow that code from Microsoft. So there's this library of code to help with things like math operations or working with text or displaying things to the computer screen or transmitting information over the internet and a ton of other stuff. So that's the first part, the class library, which is part of the .NET Framework. The second part is called the .NET Framework runtime. It's also known as the common language runtime or the CLR. So the CLR, the runtime, is just this protective bubble that your application when it's running lives inside of. And I use the term protective bubble because the CLR, the runtime, it takes care of all the low-level details so that you, the developer, can focus on what the application does and less about interacting with the computer's operating system, with its memory, with its hardware, and so on. And furthermore, the CLR provides this layer of protection to the end user so that you, the malicious evil software developer, you can't really hurt the end user's computer, at least not without them asking permission if you can delete their whole hard drive, okay? So they'll have some knowledge or some ability to say, no, I don't want to delete the entire hard drive. So for right now, it's really the .NET Framework class library. The first thing we talked about that I want to focus on because we're writing code. So whenever we typed in this phrase, console.writeline, we were using some code in the class library that knows how to display text in a Windows command line window. And then all we have to do as the programmers is actually say what it is that we want displayed to the end user. And so we're just focusing on the important part. These are the words we want written out to the screen. Everything else, how is actually written out to screen? Well, that's the part that Microsoft takes care of for us because they wrote a library of code that we're able to borrow or use. So this next line of code is also important. Here we're telling our application to wait for input before continuing to execute. So here again, we're calling a method inside of the .NET Framework class library that expects input from the end user. We don't have to actually go through the hard work of listening for keyboard strokes and worrying about the signal as it's passed through the operating system and worrying about the hardware of the keyboard. All of that is abstracted away from us. All we got to do is say we want to wait for the user to actually do something on the keyboard before we continue on. So what happens if I were to actually say let's ignore this line of code? And to do that, what I'm going to do is add a code comment, and I can use a single quote mark in Visual Basic as a way to comment out a line of code. This means that I want you, the compiler, as you're running my application, to ignore this line of code. We're essentially deleting it, but we're leaving it in the source code. I could have just deleted this out completely, so I'm going to select it all with my keyboard by hitting the arrow keys. I use the arrow keys a lot. You'll want to use those as well as the home and the end key so I can jump to the beginning of the line and the end of the line for any line of code. And I can also use the arrow key to move back and forth inside of the code. So here I'm going to hit the home key and then hold down the shift key and then hit the end key to make a complete selection. And then I can hit control X on my keyboard just like I do in any Windows application to actually delete that line of code. And yeah, I could have done that. However, now it's gone and I can't ever add it back in. I'd have to retype it. So commenting out the line of code is the preferred way to actually do an experiment without deleting your code completely, but you're saying ignore this line of code whenever you're actually running my application. So now what happens if we were to run the application but we left out that console.readline? Let's go ahead and run the application by clicking the start button. And it executed in a fraction of a second and then it ended. All right, so without pausing the application saying we need to wait for an end user to hit the enter key on the keyboard, the application executes and it's finished in a fraction of a second. All right, it flashed on screen and then went away. And so that's why we need both of these lines of code in order for our application to work the way that we had expected. Okay, so let's talk about the position of the code. You'll recall that I made sure in that previous video to emphasize that you have to put the code in the right place in order to get the same results that I got on my screen. So the right place was between this sub main statement and this end sub statement. All right, so together these define a block of code. And you can see when I even put my mouse cursor on this line that it will highlight the corresponding end sub. So here's the beginning sub and the end sub. Furthermore, I can hover my mouse cursor off to the left-hand side with this little minus and notice that it will highlight in a very, very light gray color the entire section saying that this all belongs together as one block of code. Furthermore, I can go ahead and click that little minus sign and it will roll the code up. And you'll notice that now we're going from line 1, 2, 3 and then we jump down to 10. Where did 4 through 9 go? They're actually rolled up together in this little section and I can hover my mouse cursor over and we can see the full definition for that sub main in a little window that pops up underneath our mouse cursor. But essentially what we're saying here is that this code all belongs together in a single code block and this code block has a name. We've given it a name called main. And once it has a name, we can call it by its name. So before we get to that, let's talk about this other level of indentation that we have here. An outermost module and as I hover my mouse cursor or I put my mouse cursor on the module, notice that it corresponds here down at the bottom with this end module word. So you can think of when you write code as a series of containers. Here we have a container for our code and then it sits inside of another container for our code. So I'm going to oversimplify it for just a moment and build on this definition but basically this innermost code block here is known as a subroutine or basically just a sub. It's actually known by many names and the context of how we're using it will determine what we call it. So in this case just a sub or a subroutine. In other words, it's just a block of code that has a name and we can call it by its name. We'll come back to that in a moment. In other situations we might see it called function. And notice when I change the word function here it changed the word function down there. Now we do get a little squiggly line here because it's not really being used the way that it was intended to be used. We'll come back to that later. Let me go ahead and type the word sub here again and notice that it automatically changes it to end sub for me again. In other situations it's not known as a sub or a function but rather just in general terms as a method. And so I'm actually going to use that term method many times whenever I'm referring to either a sub or a function. And so we'll talk about what methods are. They have a very specific meaning but for right now I'm just going to use it in a very general sense that this is a method and the method has a name. The name of that code block is called main. This specific sub routine, the specific method it actually has a special purpose in our system. Since its name is main it just so happens that this code will execute first whenever our application runs. So whenever the application comes to life the application will look for an entry point. What do I do first? And whatever is defined inside of this method called main will be the first code that actually gets executed. From here then we would actually call other sub routines or functions methods in order to accomplish things in our application. We'll see examples of that as we continue on in this course. So later on you're going to come to realize that a method, in this case just a sub, a method means so much more but I just want to use that simple working definition of it being a code block that has a name and since it has a name we can call it by its name to execute that block of code. So whenever you have a name you can call something by its name whether it be a method or a module or a class and so on. We'll talk about all these ideas a little bit later in more detail. So the main method lives inside of this module, a module simply known as module one, the default name. And so a module is simply a way to, simply an organizational tool. It's a way for us to keep all of the methods, the sub routines, the functions, that kind of are related together in some way that are similar in nature. So you put all of the methods that are somehow related into a single module. There will be another container for your methods that we'll talk about later that's called a class. So a module is kind of like a class but a class has a slightly more advanced and very important usage in Visual Basic. But in both cases, whether we're talking about modules or classes, you're going to put all the methods that are somehow related together inside of that same kind of organizational unit, that Tupperware container as I sometimes call it. So what do I mean by related together? Well, that's really up for you as the programmer to decide based on the type of application that you're building. You're going to come to understand as we go further through this and as you continue on past this course, the philosophies of writing code that will dictate where the code should reside inside of your application. So the module is pretty simple and is pretty straightforward and that's why we're starting with it here. And the class is a little bit more advanced but ultimately they're kind of the same. In fact, the class actually is more than just an organizational tool. I really oversimplified it like I oversimplified the notion of methods but I want to keep it simple for now. Let's just use that as a working definition until we get a couple of lessons from now when we'll start creating classes of our own and we'll talk about why classes are so important. But the main takeaway now is that code is organized inside of code blocks and you define a code block by using a keyword like sub or function and then end sub or end function or another type called a module and end module eventually will create class and class. Those define code blocks and code blocks can live inside of other code blocks as an organizational unit. All right, so let's take a look at this line of code again here in line number five as you see on my screen. Here we're actually executing a method we said before that this is from a library that Microsoft created and that's true but we're actually executing a specific method by using its name, right line. And so now anything that was defined inside of the right line method by somebody at Microsoft will get executed when we call the name of that method. So it actually lives inside of a class, a container called console. And so the second line of code that we wrote also is from the console class but it calls a different method called read line. So read line is calling a different block of code that somebody at Microsoft actually wrote and we've already talked about the purpose of right line versus read line. Why are they both associated with this console class? Well, they're organized into the same class, the console class because they both have something to do with building applications that display as console windows on our computer. So they're related in a sense in that way. If I wanted to do something with the windows console what would I do? I'd go to the console class and then call one of its related methods, okay. And the way that I do that is by accessing the methods of class using this little dot operator, all right, the period on our keyboard. So here we're able to say essentially module one dot main except in our case we're saying console dot right line or console dot read line. So this little period is actually known as a member accessor. In other words, we can access a member of the console class by using a period and then after the period, the name of the class, the period, then we can look at all the members of that class, the members being the various methods and other things that were defined inside of the console class, all right. And then we can actually type the name of the member in this case, the right line member method versus the read line member or method in order to execute it, all right. Now notice that immediately following both the right line and the read line that in both cases we have a pair of parentheses. Now, admittedly in this first case we're actually putting something inside of the parentheses in the second case we're not putting anything inside of the parentheses. In the case of the read line here in line number six, really all we want to do is just say go ahead and wait for input from the user. So we're using an opening and closing parentheses because we don't have any extra information to say to tell that library of code that Microsoft wrote. We're just saying wait. Here, however, we need to give some additional instructions. We need to say what we want right line to print to the console window. So to do that, we're going to give it the words we want it to print a screen. And whenever we're going to give it words we need to treat them as a literal string of individual characters. So I want you to write the letter H, the letter E, the letter L, the letter O, and so on and use a space. So I want this exact string of individual characters. So we're going to call this a string, a literally this string of character, so a literal string of characters to the console window. And so we're going to talk about strings versus other types of information, maybe numbers, maybe true, false, maybe dates and times. So we'll talk about data types in Visual Basic in another lesson, but it's pretty crucial to understanding Visual Basic. But here we're going to give it a literal string of characters we want printed out to screen. All right, but the key idea here is that some of these methods can accept input as parameters, so we'll call them input parameters, and some of them don't require any input parameters in order to do their jobs, all right? So we're going to come back to the notion of methods in the future and how to pass data into methods, just like we did here with Hello World in line number five and the significance of the double quotes, but just know that whenever you see a set of parentheses after a word, the method is being invoked. So the parentheses are actually a special tool inside of Visual Basic called a method invocation operator. We want to invoke the method. We want to say, do it, run, go, do your job, and here we'll provide you some extra information and the form of an input parameter, okay? So that's the purpose of the opening and close parentheses. So Visual Basic is really lax about some things and is pretty strict about some other things. In some programming languages, you could stretch a single line of code onto multiple lines because the line of code is so long that it might run off the visible area here inside of your code window. And now in some cases, like in C sharp, you can do that automatically. You don't have to do anything special. However, in Visual Basic, it's not the default behavior. If I were to try and separate this single line to two lines of code, the single instruction onto two lines, I'm going to get a bunch of errors, all right? In Visual Basic, by default, a single line represents a single idea, a single thought. It's like a sentence in the English language. And to separate these onto two separate lines, you're essentially creating two sentences without using the correct punctuation, all right, if that's the right analogy, okay? But you can actually do this if I had a really long line of code and I needed to separate it so I don't have to scroll off to the right-hand side of the screen every time that I wanted to read my code. I can use what's called a line continuation character in Visual Basic. So it's simply an underscore. So in this case, I'm able to say console and then hang on a second, let me use an underscore, write line, okay? And I might use some indentation here just to make it obvious that these two kind of belong together, all right? But that's not necessary. So in this case, this would be kind of silly to actually do this. So I'm gonna remove it, but you can use an underscore character and we will throughout this course to split up lines onto multiple lines to make it more readable so that it doesn't go off to the right-hand side of the screen. Additionally, I can kind of do the opposite where I can put multiple lines, multiple instructions on a single line. And so here again in Visual Basic, one line by default represents one instruction. And so we have two instructions in our program right now. But what if I wanted to combine them onto the same line of code? If I try to do that without anything, I would get some errors, right? Because there's really nothing separated and you would see the end of the statement was expected. And so if I really wanted to do this and there's really not much of a reason to, but you might see it in somebody else's code, you can use a colon. In that case, now we've ended one line of code here and we've said, okay, just let's pretend for a moment that this is actually a different physical line and then this other line of code and now the application will execute and run exactly the same as it did before. All right, there we go. I'm gonna go ahead and get rid of that too. Now, I want to also notice that by default that we get some indentation levels. Like here at this left-most indentation, we have the module. And then kind of to denote containment, there's another level of indentation for the sub-main. And then inside of the sub-main, again to indicate containment, there is the code that we actually wrote and then I showed you just a moment ago how I might use indentation another time to indicate some relationship. So if I wanted to do that, that might help me to see that these two lines in five and six are actually related together, they're physically separate lines, all right? So there is some indentation by default and the Visual Studio IDE, the code window that we're typing in will nudge you in that direction. Even if I tried to, for example, start typing a line of code here and do console.write line, that's all folks. And I hit enter on the keyboard. All right, it's not going to... Because I forced the issue, I made it line up there on the left-most column. It won't force it, but if I were to just hit the enter key on the keyboard, it's going to put it right there in line with all the other code. All right, so just be aware of that, that I might need to re-indent some code if I took extraordinary measures in order to move it off to the left-hand side. But indentation is completely optional in Visual Basic, it has no real bearing. Furthermore, white space has no real bearing in my program as well. So you can see I have all this extra white space. It doesn't mean anything. I could actually remove all of it just by kind of making some selections here on my keyboard and deleting. And this will work just as well as this works. So why do you suppose that we have the notion of indentation? Why do you suppose that I add and that the template added white space in between certain containers of code? Well, it makes it a little bit more readable, right? I mean, if you have it all scrunched up together or you have it way too far apart, or if all of the lines of code are butted up against the left-hand side, it's not visually as easy to tell where you're at in the hierarchy, so to speak, of the code structure. And so that's why Visual Studio automatically will try to nudge you in the right direction to format your code in this way. Now along the same lines, Visual Studio also color codes certain types of instructions that we type in. So for example, you can see here that this hello world is in this really by default. Your colors might be a little bit different than mine. It really doesn't matter. The fact is that Visual Studio will try to color some things differently. So by default, you can see here that there's this dark, deep red color. Which indicates that this is a literal string. Then there's this aqua color, which says that this is a class or a module. All right, there are things that have a more, a royal blue color. These are key words inside of Visual Studio, and you'll see some other colors pop up as well. Whenever we use the code comment, notice that the whole line turned green. That says it's a code comment. So different colors, just like indentation levels, just like white space, help the readability of our code. All right. So we've talked about the code that we wrote. Next up, let's talk about the file that we actually wrote our code into. This module one dot VB. I don't know if you saw that little tab name up in the upper left-hand corner. And we're going to talk about how code files relate to projects, and how projects relate to solutions, and what happened whenever we click the Save All button here on our toolbar. And then we'll talk about what actually happened when we ran our program then in the video after that. So there's some important concepts that you're going to learn about project management and about compilation in the next two videos. Make sure you watch them. We'll see you there. Thank you. And where they're stored on your hard drive, how to open up a project that you previously closed, how to open up one of the code files that I'll supply or that some friend might give you, that you can download in a zip file, how to unzip it, put it into a directory, open it up and so on. So whenever we created a new console project in one of the previous lessons, the module one dot VB file automatically opened up into this main area inside of Visual Studio. And that's one of the things that project templates do for us. They provide a great starting point for the type of application that we want to build, including files, boilerplate code. So it gave us this module, module one, sub, main, and sub, and module. Gives a boilerplate code. And then also it added some settings. We don't see them right here, but there are some settings that are stored here in this app config and in this hello world file that you see listed here in the solution explorer and some other resources, depending on the type of template that we choose, all right? So this little tab here at the top, and my version of Visual Studio, it's a dark blue tab. It really depends on the colors you have selected. And again, your version of Visual Studio might show it a little bit different than mine. But anyway, it indicates which file we're currently working on here inside of the main area. If we were to add an additional file to our project, there are a couple of different ways to do that. We would see we could open up multiple files here and have them all open at the same time, but only view one at a time. We'll look at some maybe window management accidentally as we go through this course and you'll see. But before, again, a more thorough explanation of how to utilize Visual Studio and get the most out of it, you'll want to watch an entire course just on the Visual Studio IDE itself, okay? But at any rate, that tab has a label inside of it and it indicates which file we're currently working on. So our Hello World program right now only has one code file, like I said a moment ago, but as our applications become more complex, we're going to organize our code into potentially many files inside of the same project. Now, if you take a look over here and I've already referenced it once, there's this window called the Solution Explorer that by default is kind of docked up in the upper right-hand corner of Visual Studio. And it basically has a tree-like representation, a tree-like view of the items in our project and how it's related to our solution. Now, as I said at the outset of this course, this is not intended to be a tour of Visual Studio. There are going to be other resources on Microsoft Virtual Academy that can help orient you to Visual Studio, but the Solution Explorer is the most important part of Visual Studio, in my humble opinion, next to the main area where we're actually going to type our code. Simply put, the Solution Explorer is our main navigational device to the other files and the settings that comprise our program. So as you can see here, we have a module 1.vb. If I were to close this tab in the main area by clicking the little X button off to the right-hand side and there's nothing now in the main area, I could open that file back up by just finding it here in the Solution Explorer and then double-clicking it and there you go. We're back into our module 1.vb. So files and important settings are organized into projects, which are then compiled into a single .NET assembly. We'll talk more about compilation and .NET assemblies a little bit later in another video. Furthermore, one or more projects are organized into solutions. So in many cases, as you're getting started, you're only going to have one project inside of one solution. But as you build more complex applications over time, it's highly likely that you're going to manage multiple projects that are somehow related inside of the same umbrella called a solution. Again, the reason for that might not be obvious today at this moment, but as you continue learning about Visual Basic beyond this course, I think you're going to find that as you build more complex business-oriented applications, this becomes a crucial code management strategy to put things in different projects depending on the functionality and the role of that code inside of the larger software system that you're building. Again, that's a topic for another day. Just for now, except that there's this extra layer called a solution that owns projects, one or more projects, and trust me, it becomes more important as we move past the basics. But for the most part in this course, we're going to only concern ourselves with talking about projects. This point should be, where are all of these files actually stored on my local hard drive? I can see them here in the solution explorer, but where are they on my local computer? So whenever we created the Hello World project and recall that we went to File New Project, that opened up the new project dialogue, and we typed in the name of the project that we wanted to create. And then I also called your attention to the fact that there's this location here and that this would be, by default, where our code is actually saved. So by default, it's going to put it in the current user's documents folder. So if you have multiple users on your system, then it's going to be whatever user you currently are logged in as. In my case, I only have one user on my computer, the Bob user, me. And Bob has a documents directory. And inside of that documents directory, there's a visual studio. And then, in my case, 2015, it could be 2016. It could be 2050 if you're watching this, what, 35 years from now? And then there's a subdirectory inside of that called Project. So this is where, by default, things will actually be stored. If we take a look at Windows Explorer, so I'm sorry, the File Explorer here in Windows, and let me resize this a little bit. Mine's going to look dramatically different from yours and I'm going to use this quick access feature quite a bit. But suppose, for example, that we're looking at the desktop here, by default, and I've got a lot of junk on my desktop. Here, I'm going to be able to look at the documents directory. All right. Now, sometimes this documents directory will show all of the documents. And sometimes it shows just a subset of documents. This case is only showing a subset. I actually have quite a few more folders. But for our purposes, right now, this will do. You can see that there's this Visual Studio 2015 folder for my situation, for my case. Inside of that, then there are a couple of subdirectories. There's the Project subdirectory. Now, again, let's just ignore this version of this and go back to the quick access, where we're going to get to my documents directory. You'll see everything in documents. We'll go into Visual Studio 2015. Then we're going to go and we see quite a few more folders. We'll go into Projects and there we are. This is a low world folder, all right. And as I add more projects, they're going to fill up this Projects folder here. And it's important to note whenever you create a new project, you can put it anywhere on your hard drive that you want. I just usually accept the default, at least to begin with, unless I'm very purposeful in what I'm trying to accomplish. Maybe I want to put it someplace else because I want to work in a team environment and we're all agreeing to put our code in a specific place or use a tool that really kind of pushes us, nudges us towards a different file structure. Be that as it may, we'll come back to that idea some other day. All right. So furthermore, you can open up a project that's saved anywhere on your computer and to illustrate this, I wanted to give you, and I'm just going to shut down Visual Studio for now completely. I gave you this file. You should be able to find it wherever you're currently watching this video, wherever you originally downloaded the video from. There's also a file that should be available called example.zip, and it has a project inside of it. And so what I want to do is extract this to my hard drive. I'm just going to right-click here and select Extract All. Pops open the Extract Compress Zip Folders dialog. And I'm actually not going to extract it to my desktop. I'm going to extract it to the root of my C drive. And then I'm going to click the extract button, and it says, hey, there are actually some files with the same names. Unfortunately, this is due to the fact that I've gone through this example before. So let me do this. Let me cancel this out. Cancel this, cancel, cancel, cancel. Let's open this up. Let's delete. Let's find my local computer here. There we go. And I'm going to delete this folder. OK, so now you can see this is all the junk on my folder, and I have a very, very messy hard drive. I'm going to right-click the example again and click Extract All. And here we're going to go and just say, I want to extract this project called example to my C colon slash drive. Extract it, and there we go. So now if we were to open this up and double-click the example folder, you can view the contents inside of it. And you see inside of this another example folder and an example.sln file. So this second example folder actually contains the project. And this example.sln file is the solution file. This solution file is the same as the solution that we saw in the Solution Explorer. So a solution can contain one or more projects. And here the projects are going to be contained inside of subfolders. If we were to actually open up this .sln file, here I'm just going to open it with. And you can see I have the Notepad app already selected because I've made some changes in Windows. If you want to open it up with Notepad, you should choose another app. It'll give you this little dialog here, at least in Windows 8 and Windows 10. All right, so we're going to open with. And here you might see some options. Visual Studio is the preferred way to actually open up an .sln file. We don't want to change that. Therefore, if you do search through your list of apps and you're trying to look for Notepad, make sure you do not click this check box. Always use this app to open .sln files. You do not want to do that. You will hate me if you do that. So select Notepad, but don't check that check box and click OK. You can see that this solution file just simply has some settings related to versions and what's inside of a project, some global settings, some other information about configurations, and so on. We don't want to make any changes in this file whatsoever. So just carefully close this if it asks you to save any changes that you made. Make sure you do not save those changes. Otherwise, you're just going to need to delete it and start over again with a new zip file extracting it, OK? All right. So we've satisfied our curiosity, but what's inside of this project folder? Well, you can see that we have another file called example.vbproj. This is the project file, and here I'm going to do the same sort of thing where I'm going to open this with and I'm going to choose Notepad again, making sure not to select this, just to satisfy our curiosity. Here we see that this is an XML file that just has other settings related to this specific project, a lot of settings. We do not want to make any changes to this whatsoever. It just has information that's going to be used by the visual basic compiler to create an executable for our application and also maybe some other things related to how we want our project organized and what we want visible in our application. I'm just going to close that. We do not want to make any changes to it. There are also then some subfolders inside of it, the same project folder. I think the most important thing we see here is this module 1.vb file. So this is the code that I wrote for the example project. And if I wanted to open up and work on this project now, I have a couple of choices. I could either double click this example.vbproj from our file explorer, or I could double click the example.sln file to load it into Visual Studio. So just to show you that, that's usually how I open up the projects. Or the other thing that you can do is actually go to the File menu and select Open Project or Solution. Or if you've opened it recently, it might be in your list of recently opened projects and solutions and you can navigate and find, for example, the Hello World project and open that back up into the Solution Explorer. Now, what I want to do is actually shut down Visual Studio one more time. Here I want to go into our documents, Visual Studio 2015, Projects, Hello World. Then I want to go to the Hello World project inside of the Solution folder and I want to look at this bin directory. So bin is short for binary. It denotes that there's a binary executable output that will be added to this folder whenever we go through the compilation process. Whenever we hit the Start button, it would actually create a debug version, compiled version of our application that can be run on our local desktop. So compiling your code into a working application is really the end goal of writing source code. But I want to stop short of talking about that in detail and pick up this idea much later in the course. I think you're going to get a better appreciation for it once we get past some of the basics. So I'm going to stop right now and I'm not going to show you what's inside of this debug folder. All I am going to do, though, is just talk about at a high level what we learned in this lesson related to the Solution Explorer, how it allows us to navigate through the code files associated with our project, how we're able to close down Visual Studio but then open up our project again either by navigating through the file system in the File Explorer or by using one of the open menus in the File menu so I can open a solution or project or open something that I've opened recently in the past in order to open it back up and continue working on code that I have in the past. We talked about the file structure and that you can save your projects and solutions anywhere on your hard drive, but by default it's going to put them in your current user's document slash Visual Studio slash project subdirectory so that it keeps them all nice and organized. I showed you how to extract out an example and put that somewhere on your hard drive so that you can then open it up into Visual Studio. So the source code that I give you and I make available with this course you can download it, extract it, and open it up and look at it in Visual Studio if you want to. So hopefully that all made sense and you understand those relationships. Now let's continue on and again we're going to focus on just that little hello world application but you can see how that's branched off into so many conversations now that are vital to our fundamental understanding of what's going on as we build applications in Visual Basic. We'll see you in the next video. Thank you. If you have any questions, please visit me at devu.com. In this lesson I want to get back into the Visual Basic syntax itself and I want to talk about declaring variables, choosing a data type for your variable and then initializing variables. So to begin with, as you can see in Notepad on screen I have a little algebra problem that I want to throw at you and even if you've taken an introduction to algebra you should be able to solve this one pretty easily, right? So here I just want to solve for the value of X. So without a whole lot of thought hopefully you can take a look and see that, well, the value of X must be seven, right? So using that same thought process now, take a look at this Visual Basic code. So X equals seven, Y equals X plus three. Console.WriteLineY. What do you think will be displayed in the Console window when we execute this Visual Basic code? Well, probably the value 10, right? So you just read Visual Basic without any help from me. It's pretty common sense, right? I mean it, for the most part, makes sense what you're trying to accomplish once you understand, for example, Console.WriteLine. So, you know, first as far as Visual Basic is concerned, the X and the Y in this situation are referred to as variables. And so a variable is simply a bucket in your computer's memory that's capable of holding a value. So you can put stuff, you can put values into buckets or rather into variables. You can take stuff, values out of variables or the buckets, all right? And then suppose I put something in the bucket, I can put something else in the bucket and cover up or eliminate the original value and now it has something new in that bucket in the computer's memory, that variable, all right? So this particular case has these buckets just holding numeric values, but we could create buckets that are just the right size to hold any kind of data. So for example, we can create a bucket that's just the right size of variable in the computer's memory that's just the right size for strings of individual characters, so strings. Very big numbers, very small numbers, true, false, dates and times and numbers that have values after the decimal place and a lot more. So there's a lot of different kinds of data types that are available in Visual Basic. And so in the case of this little code snippet that you see on screen right now, we would expect that both X and Y to hold numeric values. Now these particular numeric values probably don't have any values after the decimal point, so that narrows down the kind of data or the data type that we would choose to store values for this particular application. Now we know that X and Y should store numeric values, but we have to express that intent using the Visual Basic programming language so that when our code is compiled it can be executed and carry out the instructions that we have in our mind. So the instructions that we give in Visual Basic will ultimately be executed by, remember that .NET runtime, what I call the common language runtime or just the CLR, and part of its responsibilities is to allocate space, buckets in the computer's memory sufficiently large enough to hold the variables that we declare, to hold data, and we tell it what kind of data, the size of the bucket in other words that we want to create in the computer's memory. So in this case we're going to have two data items, X and Y, and we have to tell the runtime using Visual Basic code to allocate some space, enough space in memory, sufficiently large enough to hold numeric data sufficient for our application. So how do we do that? Well, we do that by declaring variables. So let me go ahead and get rid of this and I'm going to create a new project. There's a number of different ways to create projects. We already did File New Project, right? But here on the start page there's also this little link that we can use, New Project. Either way it's going to pop open this New Project dialog. So what I'm going to do is call this project Variables, all right? And kind of the same rules apply that we talked about before, making sure that we don't make any other changes and just click the OK button. Now the big takeaway from this lesson is that a variable is simply a bucket in the computer's memory that you can store data inside of and then you can retrieve data out of it and that you have to create the right kind of variable using a data type. We have to say what kind of data, what data type we intend to store inside of that variable that we declare. So all the same rules apply here that we talked about in the very first lesson. First of all, you have to type the code in exactly the way that I type it in. If you don't, you're going to get some kind of error. Work through the errors, make sure you pay attention to detail. You know, if you have to pause the video, rewind it, look at the source code that I wrote because I'm going to supply that to you in zip files. You can unzip it, look at it, and compare what I wrote versus what you wrote. But by all means, write this code yourself and start building that muscle memory as you're typing code yourself. If you do run into problems, remember, Visual Studio doesn't leave you hanging. You'll see the little red squiggly lines. You'll see the list of errors as you attempt to start or run the application. Those will all give you hints and clues as to where to look for the problem and then just start developing that sense of being able to identify visually where the problems are in your code. You got to pay attention to the minutiae, spelling, punctuation, everything that, fortunately, individuals, people like you and I can understand even if it's not spelled correctly or punctuated correctly. Unfortunately, computers need things exact. And while Visual Basic is forgiving, as we said, you still have to give it the correct instructions. So what we want to do is write two lines of code where we're going to declare two variables. We're going to say create two buckets in the computer's memory that are sufficiently large enough to hold numeric values. And the way we do that here inside of our Submain is to use a dim and that is shortened for dimension or it's, we often call it declaring variables, okay? So we're going to give it a name. That is the name of our variable X. We can give it any name with some exceptions. We'll talk about that in a minute. Now we've got to say what kind of variable we want to create and we're going to create a data type called integer. We'll talk about that in a minute, too. So I'm going to do the same thing with Y as integer, all right? Now, to borrow from the explanation earlier in the lesson, we're officially asking the .NET runtime to allocate space in the computer's memory sufficiently large enough to hold two numeric values, one that we're going to label X so we can get back to it to save new values in it or to retrieve the values that are already inside of it and Y, another label for a different bucket, a different space in the computer's memory so they will hold two different values potentially, all right? So we're asking it to create these two buckets that will each hold values that eventually we're going to drop into those variables or drop into those buckets. And then after we've created those buckets or those variables, then we can begin to assign values into the variables and then retrieve values out of the variables, all right? So most importantly, we're going to assign integer values into those variables. How do I know that they're integer values? Well, again, here, we use the key word integer in lines number five and six. So integer is the visual basic term for a math, is a mathematical term really. It is, it refers to a number that has no fractions or values after a decimal place. It can contain very large numbers from 2 billion, 147 million and something odd numbers to a negative 2 billion, 147 million and something odd, okay? So if you need to store a number that's larger than 2 billion, 147 million, then you want to create a different bucket in the computer's memory because you're going to need a larger bucket to hold larger numbers. Conversely, you probably want to use a smaller bucket if you really don't plan on using very many values inside of it. So for example, a true-false value, you need a real tiny bucket because it only needs to store a zero or a one, which is true or false, okay? So anyway, like I indicated earlier, there are many different types of data types. There are simple data types, and then you'll also learn about complex data types. And then later on in this series of lessons, you're going to learn how to create your own custom data types using classes, all right? So because I don't want you to be overwhelmed just yet, I'm going to keep it simple for the moment. We're just going to talk about the integer data type. Here at the outset, we'll also talk about the string data type in this lesson a little bit later. All right, so first of all, I'm going to sign a value to X. I'm going to give it the value seven. Then I'm going to assign a value to Y. And we'll take whatever the value of X is and add three to it. Now what I want to do is write out the value, console.writeLine, the value of Y. And then, of course, we're going to use console.readLine so that we can actually see what it is that we typed in. Okay, let's run the application briefly. And we already know what the answer should be. The answer should be 10, right? Based on the little notepad equation that we saw earlier, we essentially just recreated this but using actual Visual Basic Code in order to come up with the value 10. So what really was going on here? Well, after we've created two buckets, two variables in the computer's memory, sufficiently large enough to hold integer values, then we started assigning values or putting values in those buckets and retrieving values out of the buckets. So in this first case, in line number 8, you can see that I am putting the value of 7 inside of the value in the bucket labeled X. Then I'm going to retrieve that value out of the bucket labeled X and say, what did I stick in there? Oh, yeah, the value 7. We're going to add those two values together and then assign that value to Y. So at this point now, Y should equal 10. Then we're just going to merely do what we've seen before and instead of hard coding the value of 10 as a literal string of two characters, 1 and 0, we're just going to give the console.writeLine our integer value of Y storing the value of 10 and it will figure out how to print that to screen and that's how we saw the number 10 show up in our console window. So I think one of the most important things that I didn't cover just yet is the role of this equal sign. It's actually an assignment operator. So in English, that line of code is basically saying set the integer named X equal to the value of 7. All right, and so we do the same thing in the next line of code. We're assigning this value into this variable. All right, so hopefully that makes sense. What I want to do now is comment out all these lines of code and I can just go through here and one by one use the little single quote mark in order to comment all of these lines out or tell you what, I'm going to show you a shortcut. There's a tool here on the toolbar that allow me to do the same thing. So I'm just going to select all the lines of code with my mouse and then I'm going to choose this little comment out the selected lines. Now, notice that I can also use this keyboard combination if I hit Ctrl K, Ctrl C, that's called a chord in Visual Studio when you do, it's like creating a chord on the piano and it will also comment all the lines out. But I'm just going to click the button here and you can see that it added a single tick mark to every line of code, thus commenting out the work that we've just done. I'll leave it here for your reference, all right. Now I'm going to create a few empty lines here by just hitting enter on the keyboard a couple of times and now let's create another example. Here what I'll do is we're going to go console.writeLine, open and closing, double quotes, what is your name? Question mark. On the next line we'll go console.write, notice I'm not going to use writeLine, we'll talk about the difference between the two here in a moment, console.write and then I'm going to use double quotes inside of that and say type your first name colon space inside of the double quote. The next line of code I'm going to create a bucket or rather a variable called lowercase my capital F and first capital N in name as string. Okay, so let's talk about what I did here. Instead of using just a single letter as my variable name, I'm able to use a very long variable name. Furthermore, I'm able to use lowercase letters and capitalize letters in order to kind of give me a visual cue of where one word ends and another word starts, all right. And this is called camel casing, we'll talk about in just a moment. And instead of creating an integer value this time I want to capture from the user their name. Their name is not going to be stored in a bucket that can hold integer values, right. We're going to need to store strings of characters so that it can store Bob, B-O-B, okay. So that's what my goal here is to retrieve the name of the user into this variable called my first name and the way that I'm going to do that is through the use of the read line. And so we're going to use the read line in a slightly different way than we had before. So my first name equals console.readline, okay. I'll explain what that does in just a moment. We'll make some more room. And then we're going to go console.writeline, open and close, double quotes, type your last name and here actually I don't want to do write line, I'm just going to do write. We'll go dim my capital L last, capital N name as string. My last name equals console.readline and then finally console.writeline and here this is going to look crazy. I'm going to do hello, comma. I'm going to use an ampersand character. My first name, another ampersand, that's under the seven key or over the seven key on your keyboard and now I'm going to use an opening and closing double quote. I'm going to put a space in between the two of them, all right. And this is just going to provide some spacing between the first name and the last name, like so. Okay, so let's go ahead and get started here at the very top of this and explain what this is going to do. First of all, what we're going to do is ask the person for the first name. When they type in their first name and hit the enter key on the keyboard, then we're going to retrieve that value and stick it into a variable called my first name. We'll do the same thing with last name by creating a different variable, reading off the value and putting it into the value of the variable. And then we're going to do console.writeLine and we're going to concatenate or append together my first name, my last name and this literal string, hello, comma, space using this ampersand character which is the string concatenation operator in Visual Basic. It just means that you'll just tie together all of these individual strings and we're using spaces here like in this case and in this case right here in order to give the correct spacing between the various words. All right, let's run the application and we'll go and walk through it and talk about what it does. All right, so here we go. What is your first name? Type your first name. Here, Bob, enter. What's your last name? Taber, enter. All right, now I unfortunately forgot something very important in my program. What did I forget? Whoops, I forgot the console.reline. So we can run it real quick again and I also want to put one space here between the colon and that closing double quote so that it keeps it consistent between the first name and the last name. Let's run it again. All right, and here we go. What's your first name? Bob, type your last name. Taber, hello, Bob Taber. Very cool, all right. So, great. First of all, let's talk about naming conventions and convention is basically something that most programmers do and they do it because it's not only a best practice but because all the other programmers are doing it too. And so it makes your code look consistent if you were to share your code with other people. So in this case, I named my variable my first name with starting off with a lowercase m and my than the capital F and first and capital N and name. And so this convention is called camel case and you should get into practice of using camel case whenever you name your variables because, again, most programmers do this, especially for variables that are declared inside of a given subroutine, function, or method. And we'll talk about the scope of variables in another lesson, but basically any variable that is of a local scope inside of a method, you should create them using this style of convention. You can name them anything you want. You should use long names and resist the urge to do what some books and some authors and articles that you might read online do, which is to use a convention like STR first name, all right. The reason people do this is to remind themselves that this is a string. If your methods or functions are so long that you can't remember or you can't see their declaration in one page of code, then your methods are trying to do too much, but that's a whole other topic. Typically, you don't need to use that. It just muddies up the readability of your code, all right. So furthermore, if you were to hover your mouse cursor over a given variable, you can see pretty easily what the data type of that given variable is. In this case, my last name is declared as a string. As you can see there, off to the right-hand side of the little bubble window that popped up underneath my mouse cursor. Okay, so the next thing that might have caught your attention is that we used right line versus right, here in lines 14 and 15. The only difference is that right line will create a brand new line for the entire statement, whereas right will echo the characters that you have as input parameters, but it won't move automatically to the very next line. It'll just stay on that line. So that's what allowed us to say type your first name, and then as we began typing, it came off to the right side of the colon that we had added right here, okay. So here we have requested now the actual name of the user and this is where we're using the console.reline in a slightly different way. We're retrieving whatever the user typed on the keyboard and when they hit the enter key on the keyboard, at that point, the read line method will have executed and take whatever values were typed in by the end user and then assign them to this variable. So we've seen console.reline used without retrieving values like so, but it has this second function where it will actually retrieve back the values if we're interested in those values that the end user types in and we are in this case. So we do basically the same thing here, nothing all that different until we get to line number 24 where we start appending values together into our right line in order to display them nicely to the end user to format that string nicely. Now there's two things that I want to point out about variables and about visual basic in general. First of all, visual basic is case insensitive. Now other programming languages like C sharp will allow you to create two different variables that have the same name but with different casing. So you could create, for example, my first name all lowercase and then create a second variable called my first name all uppercase and then create my first name with uppercase, lowercase, uppercase, lowercase and those will be three different variables. You can't do that in visual basic fortunately. It makes it easy to step on yourself and to make mistakes if you're not careful when doing that in C sharp. So you can't do that in visual basic. That means if I were to do this, my dim first name as string, you'll see that I get a red squilly line and it says the local variable my first name is already declared in the current code block. Why? Well, even though the casing on the F and the N is different, it is essentially the same as this declaration here in line number 16. So that's the first thing about visual basic is that it's case insensitive. Now when you type, sometimes visual basic will try to capitalize words for you automatically. So I'm not going to use the shift key at all as I type this. So dim and notice when I hit the space bar it made it from a lowercase d to a capital D. My other value as and I'm going to hit the space bar and it capitalized the word as and I'll hit integer and I'll hit the space bar and it capitalized the ion integer. So visual visual studio will capitalize words for you, but essentially that's that's a function of visual studio, not a visual basic. Now you'll also notice inherently that while it is case insensitive, you cannot declare the same variable twice. So that's the second thing that we noticed here a moment ago and that's why this would not work. My first name as string will give us an error because we've already declared my first name here and case does not matter. So you cannot declare the same variable twice like you can in other programming languages. Okay. So now that we understand how to declare a variable, let's declare it and initializes value in a single line of code. So here I'm going to comment out this line of code right there and I'm going to go to the next line. Dim my first name as string equals double quotes Bob. So when I use the term initialize, that means I'm going to set the value of a variable immediately at the point when I declare it. That's like creating the bucket and the value in the bucket all in one line of code. So typically what you want to do is give your variables values as soon as possible. This puts your variable into state, which will be an important idea as we learn about writing real applications as we get deeper into this series of lessons. But also experienced developers like to write less code and they're always looking for a convenient way to reduce the number of keystrokes and just the sheer amount of code that they have to read through. And so, you know, something as simple as at some point it's going to become simple to create new variables and to initialize their value instead of doing that in two lines of code, it just makes sense to put them all in one line of code. So what I want to do is actually now let's comment out this because that doesn't really make a lot of sense in this application to go ahead and initialize the value the way that we did here. But what I will do here in this little block of code is to kind of do it all in one shot on these two lines lines 22 and 23. Let's redo this so dim my last name as string equals console dot read line. So now we're able to do both of these things, not only create a new variable but also initialize this value to whatever the user types in on the read line. All right, so we talked about quite a bit in this lesson. We talked about what a variable is. Choosing the right data type based on the kind of data that we hope to store in memory. We talked about the difference between an integer and a string. So now we've got two data types to work with, right? Numeric values, especially ones that are between negative 2 billion and positive 2 billion that have no values after the decimal point or a string of individual characters. We looked at using the equals sign as a assignment operator for assigning and retrieving values. We looked at the arithmetic operator. I didn't really talk about it, but basically we were just going to use the plus sign in order to add values together just like we would do in an amath problem and we also looked at the ampersand which is the code, the string concatenation character in order to append two strings together. We looked at the difference between console dot write and console dot write line and we talked about naming conventions in camel case. We looked at some of the rules of visual basic regarding naming how visual basic is case insensitive, but it also will not allow us to create two variables with essentially the same name but just with different casing. So we've added quite a bit more information under our belt about visual basic syntax. Let's continue the ball. We've got it rolling now. Next lesson, thank you. Hi, I'm Bob Tabor with Developer University. For more of my training videos for beginners, please visit me at devu.com. In this lesson, things are going to get a little bit more interesting. Based on the user's input, we're going to write logic to execute either one block of code or a different block of code. When I use the term logic, basically I mean that we're going to make a decision to execute one block of code or another block of code based on some condition. For example, the user's input or maybe the state of the computer, the system itself that we're working in, or some other data that we have available to us. We're going to decide what to do with that input, with that data, and then react accordingly. What we're going to do is create a new project called Decisions. Again, visual basic console application. We're going to call this Decisions and click OK. I'm just going to start writing some code. Again, what you'll want to do is pause while I'm typing this and type it along with me and then I'll explain what it does. I'm willing to bet that you can figure out what this does even without my explanation because at this point things are so easy. Let's go ahead and just write it together and then we'll go on and talk about it. Here we go. There we go. I think probably most of this would make sense as you look at it on my screen. The one thing that might look new to you is the if statement that we have here in lines 10 and the end if in line 12. Notice that there's this level of indentation then creating a code block in between the if and end if statements. We've set up this condition if the user value is equal to one. So if the value that the user typed in when prompted is one then what we want to do is set this variable message equal to the string value you want a new car and then print that out to screen. So let's go ahead and run the application and just make sure it runs in this very simple case which I'm pretty sure well when I hit one on my keyboard and hit enter hey we want a new car. What I'm not accounted for are the other cases. So for example to nothing happens and the same would be true even if we typed in something like a bob and hit enter nothing happens alright. So first of all we want to talk about the evaluation operator. It is the equal sign so it's playing double duty. We can use it as an assignment to set the value of message equal to the value of some string like you want a new car but when it's used in the context of an if statement here we're going to do an evaluation is this true does user value equal the number one or the string value one alright. If it does then execute the block of code that's defined between the if and the end if if this is false so when I typed the number two or when I typed in the word bob then that's false and we do not execute the values inside of that code block okay. So that is what I meant by making decisions where we're building logic and executing that logic and then based on the input of the user will decide what to display or what code execute in a more general sense whether we execute this block of code inside of the if statement or not so again in this case this is using the equal sign as an assignment operator this is the evaluation or the quality operator okay. So what happens then if we want to try different combinations well I guess what we could do is then start a whole new if statement so if user value equals two then we can set the message equal to you one a new boat and I'm willing to bet that that would work but there's a more simplified version of this let's go ahead and just delete that because what we can do is inside that same if block we can create additional checks called else if statements alright so if the user value equals one is not true then we're not going to execute this block of code but what we will do is then move down to the next the next check and in this case else if user value equals two alright and if that's the case then we'll set the message equal to you one a new boat I could also do else if user value equals two message equals you one a new cat alright and then finally what if I none of these are true what if none of them are true and at this point then you know if we run the application and I type in the word Bob I get nothing alright well there's one of two ways I can handle that in this simple scenario I could assign the value of string to initially to bad input like so so it would none of these conditions would register and therefore it would just stay at its default value bad input and that would be printed to screen so here Bob that input but what I'd really like to illustrate for our purposes here just so you can see the last part of it if else if and if statement is just the simple else statement and in this case we're saying if this is not true and this is not true and this is not true then alright well this is the catch all otherwise just do this in this case we'll just set the message equal to bad input please try again alright or something like you lose or whatever the case might be and so whenever we run the application we type in Bob and hit enter bad input alright great I want you to notice something how I how I designed this code I could have in each of these cases just done console dot right line and then said you won a new car like so alright I would have had to add the console dot right line in each of these else of statements and in the else statement as well however what I chose to do instead was just to define a variable and have it store the message that I want displayed and then just call the console dot right line a single time here at the very bottom alright so that's just a way to simplify the code to structure the code in a very logical easy to maintain sort of way if I wanted to change how this message is displayed I might have to change it in several different places so for example I might want to change whoops let's do this and say result colon space and then display the message I would have to make a change to every one of these code blocks if I had written the value out but now I can just make a change in one place and just display then the message after it so just be cognizant of the fact that you can simplify your code and you can expand its functionality while reducing its the amount of maintenance that has to happen or add new functionality so I feel like I've accomplished that in this case by just kind of using this message variable to store the actual message and then only using console dot right line one time in my application so finally what I want to demonstrate to you is I'm going to comment all of this out and in some cases you don't need the if, else, if, else, and if you can use something just called the conditional method so there's a method called if with an I two I's, IIF and then an opening and closing curly brace it now in this first part what we want to do is set the expression so let me actually grab some code from earlier here and we'll grab these first three lines of code and I'm going to select them all and then use the button that's right next to the comment out the selected lines and this is the uncomment the selected lines and that will remove the little comments from each line of code alright so now we have the user value again and here what I want to do is if I if open and close parentheses user value equals the value of one then after that one I'm going to use comma you can see I can add a true part and a false part so here what I'll do is say the true part is car but for everything else if that's user value is not equal to one you just want a free cat alright so let me do this I'm going to go dim message as string equals empty string and then message equals if the user value is one then I'll give them a car but anything else they'll win a cat and then we'll do console dot right line the message and then finally console dot to stop the execution and now let's run the application and type in the number one great and then I'm going to type in the value Bob and I want a cat I guess I need to improve this just a little bit and do this you one a and there's the message and I might even just add an ampersand and then I'm going to put a period to make the end of the sentence like that okay I have a better idea let's fix this I don't like that that's a lot of concatenation there's an easier way to do this and I'll explain this little bit the syntax a little bit later but inside of that string what I'm going to do is add replacement syntax and there's some special features of replacement syntax that we're going to see in an upcoming lesson that will allow us to format what we put in here like if we have a date or a currency value we can do some really neat things but for right now I'll just use you won a curly brace zero curly brace double quote and then I'm going to use a comma after that and then put in the message like so okay now I need to explain these commas inside of the opening and closing parentheses you see that we have this if conditional method here and we use a bunch of commas what those are it allows us to separate the input parameters to each of those methods so sometimes a method only will accept a single input parameter like console dot right line now console dot right line can also accept two parameters or more in this case we're going to give it a string and then a value that could be used in replacement whenever it comes across a replacement code again we'll talk about replacement codes at length a little bit later but you can see here I'm passing in two parameters to the right line method by using a comma in between them here we're using three input parameters by using two commas here we do the evaluation is this going to be true or false if it is true then we give it the true part and then if it's false we give it the false part and whatever is returned back from this method whether it's car or cat it'll be assigned into our message variable which will then be added to our U1A and then we'll replace whatever that replacement code is whatever it's either car or cat exclamation mark at the end so now let's run the application again and here I'll type in the number 1 you want car see how that formatted it nicely and we'll run it again and this time we'll type in the number 4 you want a cat so we learned quite a bit in this lesson just tacking on some additional features of visual basic we looked at most importantly the if and else if and if statements in order to add some conditional logic to our applications so we made some decisions and based on values and evaluating the truthiness or falseness of a particular expression we're going to execute one of the code blocks inside of our if else if else and if code block alright we also looked at this magical if IIF method which allows us to again evaluate true or false and then return either a true or a false value that we can then like assign to a variable in this case then we also talked about how to add multiple items into input parameters using commas to separate each of the values in the input parameter and then finally we talked about this replacement syntax with curly braces and with the number zero inside of it and how we're able to replace a part of the string that we're giving to a right line by using the replacement code and then passing it the value we want to be stuck into that template okay for display alright so you're doing great we're learning a lot and let's continue on we're going to keep adding on the complexity and make our applications more and more interesting see in the next video hi I'm Bob Tabor with developer university for more of my training videos for beginners please visit me at devu.com in this lesson I want to spend a bit of time talking about some of the smaller syntax elements in visual basic that you'll need to master in order to understand how a properly formed line of code is constructed so in one of the first lessons I may have briefly referred to the visual basic syntax I'm driving nouns and verbs and punctuation and I want to elaborate on that just a little bit more and explain what I meant by that in this lesson so just like the English language has parts of speech and it has punctuation the same thing is true in software development and the visual basic programming language is no exception so we're going to talk about those building blocks to create those sentences those basic building blocks to create instructions in visual basic and so statements are like sentences statements are complete thoughts in visual basic they're like complete sentences and a statement is made up of one or more expressions and in turn an expression is made up of operators and operands so it goes statements statements are made up of expressions that consist of operators and operands so we've seen statements obviously just simply lines of code executable instructions that we've given the compiler whenever we type them into our module 1.vb expressions are some examples of expressions are things like a method call so console.write line passing in an empty string or hello world whatever the case might be whenever we use the if statement we evaluated an expression to see whether it evaluated a true or false so the expression portion of that was user value equals one so if user value equals one then execute this code block below it okay and then also there are expressions of assignment where we're assigning the value of a variable equal to some other value so each of those are examples of expressions and they have two things in common they are made up of operators and operands so an operand is similar to a noun in a sentence they're things that are that are that are nameable okay so variables that would be a good example of an operand but things like um literal strings that's an operand or a literal number like the number seven that would be an operand as well and so these are easy to remember because you're creating these yourself you're giving names to variables or or even classes or objects as we get further along um and you're giving value uh to uh literal numbers and literal strings right so operators are similar to verbs so you have operands are like nouns operators are like verbs and uh they will act on the nouns so they're things like for example the addition operator or the equality or Simon operator or the string concatenation operator uh typically you're going to use built-in operators whereas operands you name them yourselves typically operators are provided by the programming language now there's exceptions in both cases you could create your own operators or overload operators that's kind of an advanced topic so you know this is a little bit goofy I guess you could say and there's quite a few built-in operators and you're going to need to memorize many of them because it's how you're going to perform actions on your operands the things that you come up with the the intent of your code so fortunately as you're getting started uh you can use kind of a subset of all of the operators that are out there and then learn them commit them to memory over time and not have to refer to a cheat sheet whenever you need to to remember them so I'm going to help facilitate this what I did was create a project offline called operators expression statements and I merely created the code that you see here and you don't have to type this in yourself you can just open up this project if you want to follow along on your local computer uh because I don't know that there's any real value to typing this in this application doesn't really do anything it's just illustrating code ideas okay so if you run it it's not I don't even know it'll do anything honestly I don't think it has any yeah it has a console right line at the end but that's about it okay so uh just want to walk through quickly this is not an exhaustive list but this will give you a few to to chew on and to work with initially we've covered some of these already we'll we'll add on a few during this this lesson and you can expand your vocabulary of operators and keywords and so forth over time but in each of these cases uh an expression is made up of an operand like a literal string or a variable or an object um and an operator so an operator is something like the assignment operator so here we have an operand which is x and an operand which is the literal value of 3 and the operator is acting on the value of x so the way we would read this the value of 3 is being assigned to x all right so you see the associativity of the code and the direction it will go from right towards the left so anything on the right will be evaluated first and then it it gets assigned to the value that's on the left all right so that's the assignment operator we have the addition operator the subtraction operator the multiplication operator the division operator so these are things that you would probably come to expect uh then you can see uh we looked at the equality operator to see if two values are in fact equal or not true or false x equals y now there's some other variations on this we can check for example if x is greater than y now in numeric terms the greater than the less than operator the greater or equal to and the less than or equal to operators they're all pretty under easy to understand but you might be working with dates or strings in which case the greater than less than greater than or equal to less than or equal to might be a little harder to understand what is being compared um is it the length of the string is it the um the whether they're you know alphabetical order or not and so on all right then there are conditional operators the conditional or and the conditional and operator so that you can tie two expressions together and evaluate them so x is greater than y a is greater than b if either of these are true so if this is true or this is true then perform the code that you see in that code block the and operator is inclusive so both have to be true in order for this to happen so x must be greater than y and a must be greater than b in order for the code inside of the inside of the if statement to be to be uh to be executed all right we've also talked about the member access operator the period and how that allows us to uh to call a particular method of an object or a class in this case we've been calling the right line method of the console class by using the period in order to access it now when in this way the associativity goes from left to right so we start with the console object and then we call into its right line method and then we pass in a input parameter of a literal string and so in this case also I just want to point out that uh the double quotation marks that is the literal string operator and then there are other operators like for example the as operator you could say as is a keyword dim is a keyword that's all true sub is a keyword modules a keyword but if it acts on operands then it's also a operator in this case it acts on the operand to be assigning it a data type of integer alright so why am I telling you all of this well because the syntax rules of a programming language really do matter so for example um I can't just do that and expect anything to happen I mean visual basic compiler will look at that and say what are you trying to do you've only given me expression and an expression it it it's not a complete statement I need more than just an expression in order to do something ok so in this case we're only just doing x plus y but x plus y what alright what do you want me to do with this so in situations like these you can see visual studio will actually catch these syntactical errors uh as compilation errors we can't even run the application uh we can't even compile this code into a uh into an executable that will run inside of the dotnet framework clr the dotnet framework run time why not because the code cannot be compiled and um turned into a language that is uh acceptable by the dotnet framework run time so in that case you can see it the code editor gives us this red squiggly line letting us know that we have a problem in our code uh and so it anticipates the issues with the code by pre-compiling as we're typing alright if we were to hover our mouse cursor over we're going to get some very vague explanation as to the problem method arguments must be enclosed in parentheses so it thinks that what we're trying to do is um call um you know call some sort of method like this right and even so it's still going to have some issues alright so basically we don't even have enough code here for visual basic to give us a good error message unfortunately um and so essentially we just have to be aware of the fact that when we type in a line of code we have to kind of be purposeful and understand what it is we're trying to accomplish uh if we don't have the right set of expressions filled with operator and operands as we had here just a moment ago then we're not creating a properly form statement since we don't have a statement it can't really do anything with that code that we write so for beginners all you really need to understand is that there's a proper syntax in visual basic just like there are rules for the English language just like there is proper grammar in the English language so understanding that is a big step to solving your own problems whenever you're phrasing visual basic constructions that the visual basic compiler will accept and compile down into uh into a language that the .NET framework runtime can understand so I tell you what let's go ahead and stop right here let's recap the things that we talked about in this lesson first of all we said that statements are complete instructions in visual basic they consist of expressions and a statement is like a sentence in the English language and expressions are things that are that contain sounds and verbs the combination of the two so actual expressions are made up of operands and operators and an operand is a thing it's like a variable or a literal string something that we give value and importance to by naming it or giving it value and so for now you can think of for example the console class that's an operand and the variables that we've created those are operands whereas operators and we spent a lot of time looking at operators here and there are even more than that that we didn't talk about like I don't know if I said anything about the method invocation operators but this is definitely an operator that will kick off the execution of a method so there are lots of different types of operators and you'll need to learn the operators in order to perform actions on the operands that you create and that gives the instructions the proper instructions to that formulate your program now we've already been using these operators for all sorts of purposes until now even if we didn't identify them specifically as operators we're still using them and just understand that they are what actually do things in the application and just by using for example x or giving console you know by itself on its own line it's not going to accomplish anything we have to use operators and we have to use operands this is an operand in order to accomplish things in our applications and that's all I wanted to say hopefully that was helpful in diagnosing and understanding the code as you write it. Alright let's continue on the next lesson we're doing great. See there thanks. Hi I'm Bob Taber with Developer University for more of my training videos for beginners please visit me at devu.com in this lesson we're going to focus on iteration statements and a specific iteration statement the for next iteration statement. Sometimes you're just going to need to loop or iterate through a block of code to iterate through a sequence of items and maybe to perform a series of checks until you find a successful match maybe to execute the same code a number of times just because that's part of your business rules whatever the case might be actually you'll find yourself doing this more than you might anticipate and while it may not seem all that practically useful at first trust me you're going to need this in your toolbox as you start to write more interesting applications so let's create a new project and we're going to call this for next iterations and click OK and the syntax is really simple and I again I'm willing to bet that you're able to figure out what this will do without me telling you what it does so here we go there we go that's all we need so can you guess what you're going to see in the console window whenever we run the application let's see if you're right ok so if you guessed that you would see the numbers one through ten printed out into a console window you're right so basically all we're doing is executing the block of code defined by the four and the next statements in this case in lines five and seven anything between the four and the next will get executed a number of times until we've reached a certain condition in this case we're going to start off with the value one and assign one to index but once we get to assigning the number ten to index that'll be the last time we iterate through the code defined inside of the code block between the four and the next and then we break out and here we in line number nine we wait for the end user to move on that they have actually seen the content that we've printed to screen and that's pretty much all there is to it so we're instructing visual basic to execute a block of code a number of times and once we've completed that sequence of times as defined by this higher end boundary then we'll break out of the four next loop iteration statement and move on to the rest of our code alright so inside of here we can do some interesting things so like for example what if I were to go if index equals seven I could do something like then console dot right line you know found seven like so and we could run this and then once we get to the number seven we can print that out I have an idea why don't we shorten this just a little bit like before I don't think I showed you the then the then portion of the if else if else statement but you can use the then in order to combine everything on a single line like so alright so the then will allow you to combine a simple check with a result if index equals seven is true then go ahead and perform this line of code so we're able to condense three lines of code and do one line of code and now when we run it we get the exact same results okay I just wanted to show you that little use of the then keyword great and what if though let's comment that out and let's bust back over here to if index equals seven console dot right line found seven and now at this point we found what we were looking for if we wanted to break out of this loop we're no longer searching for the value we found what we were looking for we could do something like exit for and so now when we run the application the result looks a little bit different we get to seven we found seven and now we exit out of the four statement and we continue on executing our lines of code great this might be a good time to talk about one of the features of visual studio and again I'm trying to talk about visual studio but you still need some tools in your toolbox if we're going to build applications and one of those tools are the debugging tools of visual studio which is probably one of the best reasons to use visual studio you can actually pause and watch the execution of each line of code by simply setting a stop sign or break point in your code and then we execute the code and we get to that break point then we can continue to step through the code line by line or continue on and allow it to continue to execute the lines of code so to set a break point it's really easy in visual studio there's actually a number of different ways to do it but I find that the easiest way is to find this little gray column off to the left hand side underneath the tab heading and just click in that column for the line of code that you want to set a break point on so in this case I want to set a break point on line number six so I just click in the little gray area next to six and it creates this little stop sign over here on the left I guess it's a circle it looks more like an octagon to me and then it highlights the rest of that row in red and so now whenever we go to run the application and we're in debug time we're actually the execution of the application has stopped now unfortunately I got this little window that popped up let me get rid of that move it down but you can see that in this case the line of execution has stopped here on line number six and what we can do is hover our mouse cursor over the variables in this case there's only one variable but if I hovered over in this case the variable index we can see its current value and I can click what was formerly the start button it's now the continue button and when I run it I can and hover my mouse cursor over you can see that index has increased to two so when I clicked continue it executed the next several lines of code came back up to the top and we were able to break again on that same line of code since we're just iterating through the same block now I can use keyboard shortcuts or I can use these little items here in the toolbar while we're in debug mode to step through our code now I'm going to ignore the step into and the step out of they're kind of special cases and not really essential to us until we start building more complex applications but the step over is probably what we want to use I'm just going to hit the step over or F10 button on my keyboard and here I can just begin to step through each single line of code and I can continue to evaluate what the values are I can look at this autos window or the locals window or even the watch window and see the value of variables so in this case index is one of the local variables and I can see it here its name and its value and as it changes value notice that as we executed that that for loop in line number five the value turn from a black font to a red font indicating that the previous line of code changed the value of that variable so that's just a little visual cue to let us know that something just changed in our application let's see what else we can do here if I have a specific variable that I want to keep an eye on I can kind of highlight it and then drag and drop it into a watch window so that even if I am moved off to another part of the program I can always keep an idea keep an eye on the current value of the index in one of the watch windows so the other thing that you can do which is kind of neat is hover your mouse cursor over and see the current value of any given variable and I can even pin this down so notice that when I did that it pinned create this little pinned area and I can actually drag it and move it around so that as I start stepping through the code that little window pops up here and you might have seen it briefly change color to red whenever we hit the index six and continue moving on through our code here and at this point we'll see that index will in fact equal seven so we'll step into our if code block execute the console dot right line and then we'll see what happens when we hit the exit four it jumped from line number ten all the way to line number fourteen and if we hit continue now we'll just see this console window and we're back in runtime and hit the enter key and the keyboard to continue all right so those are just a really really quick overview of the features there is one cool feature that I want to show you that's applicable here since we're working with iteration statements and that is we can configure our breakpoint by clicking the little gear wheel that appears as we hover our mouse cursor over our breakpoint and I can say that I only want to break on this line under certain conditions and the condition that I want to that I want to break on is whenever index equals seven so whenever we hit that point I'm going to say let the breakpoint stop the execution of the code otherwise let's just go ahead and blow our way through one through six and so now I hit the continue button let's hover our mouse cursor over our index or I can just see it off here to the right hand side it is in fact seven I'm done with that now I could say I want to keep an eye on this and just keep that around or I can actually just get rid of the whole thing by just clicking the little X button there all right but you see how I was able to configure this breakpoint and make it conditional so that it only stops whenever the index value is equal to seven and there's some other options here that I could choose for example I could log a message when we hit a certain situation and then continue the execution we're not going to do any of that right now but notice this little tab breakpoint settings pops up in line very very neat and we can continue on the last thing that I want to show you and you can see that the icon has changed from just a red I guess it's a circle but it looks kind of to me like an octagon but notice that whenever I change some of the settings it has a white plus symbol in the middle of it let's go ahead and turn off that but what I do want to do say I want to disable the breakpoint temporarily because it's not useful to me at the moment so let me just run the application the breakpoint is still there but we're ignoring it for this run of our application and then I can enable it one more time or get rid of it all together by clicking on it a second time and any of the things that I did here I'd be able to also do from the debug window where I'm able to toggle breakpoints, create new breakpoints even make them functional breakpoints changing their settings about when they should actually be enacted, delete or disable the breakpoints and so on so let's go ahead and get rid of that alright so I also wanted to show you something cool another feature of Visual Studio since we're on this topic and we've got some time I'm going to go ahead and well we'll just leave everything where it's at here what I want to do is show you how to use code snippets and if you can't remember how to use an if statement or how to use a for statement or any of the other things that we're going to learn about typically what you can do is just type the first word and you don't remember the exact syntax you can type in for tab, tab and bam it expands it out and creates a code snippet I can continue to tab my way through and notice that there are three fields that I'm tabbing between and they're all kind of in this golden rod or yellow color that allow me to change for example the variable name that's used as the iterator variable so I can change it from index just to the letter I I can change it from 1 to let's say we'll start at the number 3 and we'll go to the number 13 instead and when I've finished replacing the various parts of this for statement I can hit the enter key on the keyboard and now I can continue on and writing the rest of my of my statement here so in this case it would just be I let me comment this all out changing my mind on that and there you go now we're going from 3 to 13 instead of 1 to 10 and another interesting thing I can do is to actually go and here let me show you one more thing we'll just go if tab, tab here you can see that I'm checking in this case the only thing to replace is that conditional check what are we going to evaluate whether it's true or false we just make that change there so I equals 3 or whatever the case might be let's put that in the context of this so if tab, tab I equals 4 enter and now we can continue on here and write whatever we want to write likewise so those are code snippets another feature or visual studio the final thing I want to show you about the for next statement is that you can step backwards so if I wanted to go from 13 to 3 I could do that but unfortunately if you just leave it like I wrote it it's not going to give you any satisfaction what you need to do is actually add a keyword called step and so I can step backwards through a for statement by saying step one and we can do the step to do some interesting things here I'm going for 13 to 3 that's cool let's go for tab tab and here we'll go from 1 to 10 but we're going to step 2 and we'll do console right line so here we're just going to whoops index we're going to start with 1 and then we're going to step 2 until we get to 10 so let's run this and basically this is gives us the ability to count odd numbers so we print out 13579 we hit 10 we break out of the for loop so that's our ability to step 2 numbers at a time and essentially avoiding all the evens okay so there's a lot of options here again in this lesson we talked about quite a few things we talked about the for next iteration statement and how it will automatically allow us to iterate through a block of code a number of times as defined by the conditions here and we are assigning the current value of the iterator of the variable that will hold the current index from one number to another number alright so that will define the number of times we can obviously step backwards by using a negative step or step over numbers by using two three ten whatever it is that we want to use we're able to use the if and then keyword in order to do a really quick conditional statement all in one line of code we use the debugging tools and even conditional debugging disabling debugging stepping through lines of code all of that we looked at code snippets that allow us to generate lots of code a little template of code that we can then go through with the tab key to change various values so we looked at a lot of cool little features here in a relatively short amount of time let's continue on we're doing great and hopefully you're gaining confidence in your ability to write code using visual basic because I know at this point now we can do some pretty interesting things so let's continue on the next video we'll see you there thank you often you're going to need to work with several related variable values so how do you work with multiple variables that are all somehow related they're all intended to be used as part of a group but how can I treat them as if they are part of the same group how can I enforce that relationship between multiple values so as you look on screen right now this is an example of how not to do it here you can see that I have a series of numbers or variables rather defined as variable names number 1, number 2, number 3, number 4 and I assign their values appropriately right now the problem with this scheme that I've cooked up here is that I'm relying on a name and names of things are fragile they're not enforceable because we're making up the names ourselves the compiler wouldn't care if we misspelled one of the names and it would be just fine with that and we could probably work our way through that but still they're just kind of they're kind of loosely connected together and only connected because of the meaning of the name that they have it's not a full proof approach towards creating related values and treating them all as a single unit of content here now previously I compared a variable to a bucket that's created in the computer's memory that's just the right size for a single value of a given data type now to extend that analogy a little bit further you can think of an array as a bucket that inside of it contains other little containers other little buckets that you can put values into okay so another way to think of an array is that it's a sequence of data all collected together in the same variable or bucket in the computer's memory now I hesitate to use the word collection or sequence those have a certain connotation for programmers collections definitely have a specific connotation to dotnet developers but you can think of an array in a sense as a grouping or a collection of data lower KC collection of data okay so you declare an array just like you would any other variable you start with the data type that you want to create and then you say how many elements are rather how many of those little sub-buckets inside of the big bucket that you actually want to create and so in this particular case what we want to do is create a quick example of an array in action so that we'll be able to revisit this example a couple of times and learn more about arrays in the process so the first time we'll use kind of a long hand format here let me get rid of this because we know that's not right so let's go ahead and you can see that I've already created a project called understanding arrays pause the video take a moment to create a new project named understanding arrays catch up to where I'm at and then unpause the video and we'll continue on what I'm going to do is create a new array and so to do that I'm going to create one named numbers and then I'm going to say how many little sub-containers I want inside of it and then give it the data type alright there's actually a shorter way to do this let me just show you the short way because nobody ever does it this way alright so here we go in this particular case you have to remember that this number is zero based so while it says four there's actually five containers because you have to count zero whenever you're dealing with arrays alright so there's in other words we're creating a bucket in the computer's memory a variable named numbers inside of that bucket there are like five containers and we're going to reference each of those containers by their ordinal position zero one two three four five little sub-containers inside of our array called numbers they're all going to be integer values inside of it you can't mix and match alright and so now that we've declared our array we can actually start assigning values and retrieving values from the array using this style syntax so for example if I want to reference the first item in the array I'm going to use parentheses and then the number zero so parentheses are doing double duty just like the equal sign did double duty remember the equal sign was the method invocation operator now it's also used for so that we can access individual elements of our array so in this case we're going to set the first little sub-container inside of our array the first element of our array at index zero equal to value four here I'll just go ahead and keep working with the next element in the array we'll set that equal to the value of eight and then we'll set the next element of the array equal to the value 15 the next element in the array equal to the value 16 and then the next element of the array equal to the value 23 okay and that's roughly what we see that we have here the good news now is that I can just treat this array with the keyword numbers and I can access all the items inside of that without and they're all collected together I guess you could say inside of the same memory area and the same label in this case the name numbers so I would verbalize this in one of a number of different ways for example I would say that numbers sub one equals eight or the numbers array at index one equals the value eight or I might say the second element of the numbers array equals the value eight or something along those lines okay so this is called the index the value the numeric value to actually access an individual element or what I was calling a subcontainer inside of the array itself those are indexes and they allow you to access an element of the array and here we're assigning the values and we can retrieve the values in the same way that we would any other variable okay so that's the nomenclature that you would use to talk about them now what happens if for example I try to access one more element of the array and so here in this case I'm going to try to access number sub five and here let me do console.write right line and we'll just do something like tell me how many items are in the array how can I tell how many items are in the array programmatically I can use a property called length okay so give me the length of the array in other words give me how many items are in the array and then we'll just do console.reline so let's see what happens here when we attempt to use an extra element of the array attempt to assign an index outside of the five that we defined here as the original size of the array alright well we get our first exception runtime exception that we've experienced while coding in visual basic here we have an index out of range exception wasn't handled in other words we were able to compile our code but when we were running our code we ran into a problem and it stops the execution of the code the user can't proceed in fact what they'll see on their screen is dramatically different than what we see on our screen in fact let me just kind of stop the running of this application and show you if we were to release this application as is our end users would see something much uglier and so I'm sorry for this quick aside I just want to show you what you would see here we'll talk about this all in depth a little bit later we run the app and notice what happens you get immediately this you know stopped working a problem caused it to stop working correctly and then you get this unhandled exception it spits out all this information that's what your end user would see as a developer running the application visual studio kind of steps in and it puts up a friendly message box and explains what the situation is and how to fix it but ultimately the index five is out of range in other words there's a range of accepted values and since we have created an array with five elements but we try to access a sixth element we're going to get an exception so we can't do that ok we can do something like this console dot right line and we haven't looked at how to actually access a given element of an array here we'll do we'll use that replacement that replacement code that we learned about earlier so the third element of the array contains and then we'll just do like that so we'll use the open and closing curly braces with the number zero and then we'll access that third element of the array in fact the third element of the array is not three it's the index of two right alright so just make sure we catch that so let's run the application again you can see the third element of the array contains 15 the total length total number of items in the array is five items ok now what if we wanted to actually display on screen the value of each of the items well this is where that four next statement comes in so I'm going to type in this watch this is cool four tab tab right so we're going to go from index equals and remember we can't start with one we've got to start with zero and then we'll need to go numbers dot length but this is going to give us the total number of items and we want to convert the number of items into a zero based index so we're going to have to subtract one right so this is going to give us five items but we really want to go from zero to four so that's why we did it this way just remember that little dance you have to do and now we'll go console dot right line and then numbers and then in between the opening and closing parentheses we'll use the index variable that will allow us to index into each of the items in our array and print them out to screen and so we see each of the five items there now let me take a moment here and just comment some of this stuff out because I want to show you an alternate way to define your and not only define the array but then also initializes values all in one shot through an initialization syntax so here we're going to go dim numbers now instead of giving it the number of items we want in our array I'm just going to leave it empty so I'm going to add the open and close parentheses but I'm not going to put a number inside of it I'm going to say I want these to be integers and then I'm going to use an opening and closing curly brace and inside of that add a series of numbers like so and when we run the application we'll get the exact same results that we got last time and you might be wondering well how in the world does this work ok so we're able to create an array of type integer and instead of saying explicitly how many items we want in the array at the point of initialization we'll just allow the number of values that we type in here to dictate the number of items in the array so this will automatically create a numbers sub four five items five elements rather in the array and it automatically puts values into each of the elements element zero one two three and four then we just print them back out the screen and that's how that works let's comment all of this out and moving on let's look at the fact that we don't have to just use integers we can also use strings so here I'm going to create dim names and use that same style syntax that we just used a moment ago I'm going to say I want an array of names and I'm going to set them equal to the names of some people that I have known once upon a time not personally unfortunately that would be pretty cool and then what I want to do is iterate through each of the items now I could use the same syntax that we used here and get the length and iterate through each index for this new array called names but there's even an easier way to iterate through each of the items and that's with a four each so I'm going to type four each tab tab let's do that again four each tab tab there we go so four each name as string in names alright and then here we'll go console dot right line name and let's go ahead and run it and see our names printed out the screen now let me explain what just happened there so here we create an array of names there's going to be four elements in the array and here we're using the four each instead of the four and this basically just says hey you've got an array or a collection in this case an array so let's just look through each item in the array we'll copy off the current value as we're iterating through and we'll stick its current value as a string inside of a temporary variable called name and then we'll just work with the name variable here as we console dot write it out to our applications user interface alright now you can also do some other very interesting things for example what if you wanted to take a string and you wanted to reverse it so you wanted to write the whole string and reverse let me tell you a tiny little story that on my very first job interview I was asked to take my name that made me go up to the white board and write my name on the white board and the guy who I actually became good friends with afterwards but at the time I was pretty flustered he said okay write code to take your name and print it backwards and I had no idea how to do that but I promised him said I don't know how to do it now but I promise you within an hour after this interview I will know and so I did I wrote him an email found his email somehow wrote him and he was impressed enough by the fact that I was willing to figure it out that that was he didn't he didn't say no don't hire this guy at least I don't think he did but anyway I got the job so I don't want you to go through that same humiliation that George put me through and so here what we're going to do is create a little example and we'll start off with one of my favorite motivational sayings alright and so remember what I said about the line continuation character and how you don't want to have to scroll off to the side of the screen every time just to see all of your text it's much easier if you just for example pick a spot add a double quote right in the middle space underscore and then go to the very next line and tab your way over a little bit and then add you can either add the ampersand before the line break or you can add it after the line break basically we're going to make two strings concatenate them together using this the concatenation character and this use the underscore character in order to get them all to essentially be one line of code even though they're spread across two different lines of code so there I have a very long sentence split up on a two lines of code as my text and now what I want to do is convert each of the individual string of each of the individual characters that are a part of the string remember we even said that this was a string of characters well really a string is just an array of individual characters all kind of you know put together so what if we could take that string and converted back into an array of characters and fortunately there's a really easy way to do this so here's I'm going to create something called a character or char I'll call it a char array an array of characters as char equals my text dot two char array so notice that the string that the string data type has a method that microsoft wrote that allows me to take that string and convert it into an array of individual characters like so so now here I have this char array this array of individual characters and I can do some really interesting things with it at this point for example I can use the array class and say array dot reverse and then give it my char what do you think will happen here yeah it takes all the characters and reverses their ordinal position so the first will be last and the last will be first and all the others will follow suit as well so now if I do a for each tab tab for each item in my char array and here I'll just console dot write not write line just write my char or actually item because that's what I'm calling it here this is the little temporary variable that we'll use then I think it's going to reverse that string for me so there you go this took that entire sentence and it reversed it so you can read it backwards you can get what you want out of life if you help enough other people get what they want very cool thank you Zig Ziglar for that help alright so you could use the for next if you prefer I like this for each it is so elegant and it just copies in the current value you don't have to worry about lengths and indexes and things of that nature you're just going to grab the next item and work with it alright so at any rate hopefully this was pretty enlightening arrays are great you'll learn about something called collections a little bit later in this course collections are awesome they're like arrays on steroids we're going to talk about those much later near the end of this course but let's just continue on we're learning lots of great stuff and we're compiling this toolbox you're doing awesome we'll see in the next lesson thank you Hi I'm Bob Tabor with developer university for more my training videos for beginners please visit me at devu.com in this lesson I want to show how to define and call simple methods and we use the term method as an umbrella term at least at this point to talk about both subroutines and functions we've been using them up to this point but how do we create our own that's what we're going to learn about in this lesson so creating methods will help us in a number of different ways first of all they'll help us to better organize our code and you'll see that here in just a moment secondly they help to eliminate duplicate code and it eliminates the need to copy and paste the same chunk of code multiple times and I'll talk about the dangers of copy and paste in this lesson but methods also allow us to encapsulate a specific feature of our application in one method and this makes that feature reusable across our entire application and depending on how we package it it could make it reusable across multiple applications but that's kind of an advanced topic and then finally whenever we need to update that one feature of our application instead of looking all over our source code for everywhere that we copied and pasted that code all we got to do is change it in that one place where we define that functionality and all we do is just make our change in that one spot and then every every place in our code where we call into that method it will gain the benefit of those changes that have been made so there's a lot of benefits to using methods it's actually one of the most important building blocks as you're seeing larger and larger applications so it's definitely something we need to get under our belt and just remember that a method whether it's a sub or a function it's simply a block of code that is given a name so if it's a sub it's going to be sub whatever my name is and sub or if it's a function it's going to be function whatever my name is and function and so whenever you go to since it has a name we call it by its name in order to invoke the code defined inside of that code block so we would call whatever my name is or whatever I call it a moment ago. So again it's one of the most important building blocks as we're getting started here for building larger applications so this is one of the times where I'm going to ask you to make sure you download the code associated with this lesson here I have a 2.4 and after folder for this particular lesson and I want you to grab the contents of the before folder which should be called which is a solution and a project called simple method I'm going to copy that and what I want to do is put it in my projects folder now instead of navigate to my project folder every time what I did was I dragged and dropped the folder reference to this quick access area here inside of the file explorer so now if I want to get to my projects folder I just click projects there and then I can simply right click and paste in my folder and now I can double click and open up the solution file and we can begin our work inside and so basically what this lesson is is just a little name game and let's go ahead and play it so you can see how it works this is going to ask me a series of questions like what is my first name what's my last name and then where was I born I was born in Oak Park, Illinois and then it'll take each of those Bob and Tabor and then Oak Park and it will reverse them and then print them to screen okay so this is using the algorithm that we learned about when we looked at character arrays in the previous lesson we're just going to use it multiple times and this will make it a great candidate for extracting out some of that code and putting it into methods so as you can see here the code that actually implements that little name game it's actually pretty hairy what we wind up doing is re-implementing the same code a number of times in order to do that reverse string algorithm so I'm doing it once for the first name once for the last name and once for the city and so we're essentially here's the first name last name in city here's the first name the last name and the city so you can get the feeling that we've invented the wheel a couple of times here and that is an opportunity for us to improve the quality of our code what we want to do is reduce the duplicate code in our application first of all and duplicate code in of itself there's really nothing wrong with it there's no way that you can completely remove duplicate code from your application but duplicate code is usually the result of copy and paste and so invariably what will happen is you say well I need to I need to reverse not only the first name but I also need to reverse the last name so let me copy and paste from up here and I'll paste it down here and invariably what happens is you forget to change maybe the variable name from first name to last name or whatever the case might be and so you subtly introduce a bug in your application that you now you got to hunt down and figure out but furthermore if you have the same code repeated many times then whenever changes are requested in your application you're going to need to go and find every time you've implemented that particular feature of your application and change it in multiple spots and that will lead to subtle bugs as well because chances are you're not going to find every implementation of that given feature but if we were to be able to step back and say to ourselves you know I'm really doing the same thing three times and extract out those things that are common across all three of those implementations so the little algorithm that is required to you know convert a string into an array of characters to reverse it and then combine it back together if we were to take that and extract that out and then leave in the only things that are different about each of the implementations I'm going to use it for a first name I'm going to use it for a last name I'm going to use it for a city well now you've got this nice separation I can take all the code use related to reversing the array and put it into its own method and then I can call into it three times just passing in what's different as an input parameter to that method so the second reason that you'll want to actually break up your application into methods is to simplify the readability of your code so if there are several lines of code that do the exact same thing you're going to find that your code is less readable so as I'm looking at this code and I'm trying to understand what it's doing here it's just got a lot of a lot of thick code that I have to I have to mentally parse through to understand okay I see what they're doing there alright see what they're doing there I see what they're doing there I see what they're doing there wouldn't it be easier if I just took out all the code that knows how to reverse an array and put it into a method called reverse array or reverse string or you know yeah reverse string that would be a good name for the method and now I can just look at that name reverse string it's nice and friendly it encapsulates all the functionality required all the code required to reverse the string and now as I'm reading through my code it becomes very obvious what this application is attempting to do because I've made my code much more readable so you should strive to make your code human readable make it read as much like an English story as possible and one of the ways you do that is by choosing variables and for your methods and you want to tell a story as you're going through that main section of your code that calls into the different methods to do all of its dirty work so you should strive to make your code human readable it'll make it easier for you six months from now when you look at your code again it'll make it easier for your teammates who you've asked to help you maintain the code and also make you look like you really know what you're talking about so maintenance and maintaining code is a big deal and whether it's you maintaining your own code or other people maintaining your code or you maintaining other people's code there's a form of communication that has to go on and part of that communication is the words you choose to use and the way you spell things and the conventions that you use so code readability super huge in order to reduce the friction of understanding what code is supposed to be doing as you're building your applications so what I want to do is introduce a few methods and try to reduce the complexity of this application so what I'll do to begin with here is start off by by maybe taking something really simple like taking this for example and moving it into its own method so I could for example create a sub called display result and inside of here let me just say I want to pass in a message as type string so now we have an input parameter one input parameter and we're going to let the user pass in what needs to be displayed out to the end user so here I might do something like console dot write results colon space and then console dot write and in this case just the message alright that's pretty easy and we can easily just replace this line of code with this display result I don't know that we've made a huge improvement to our code however it is obvious what it is that we're trying to do now by making our code more readable we're displaying the result alright small improvement but the really the key here is how do you define your own methods use in this case a sub routine a sub routine is different from a function it basically is fire and forget I want you to execute and then I don't want to hear back from you again go do your work and then quietly end your execution so we also see now how to define a parameter in this case a simple parameter it is just a string that we're passing in and this allows us now to use IntelliSense as we added the opening and closing parentheses you can see that we get this message of what's expected we're expected to pass in a string called the message and so we then can just you know type in the result and it'll satisfy that alright so that's one version of this method but you know that methods not all that useful what might be more useful is if we were to do something like this sub display result and you can see that and we're spending a lot of time here just kind of concatenating strings together so this and equal is just taking the current value of results and adding the current item to it so if you I know you probably haven't seen that before but that's what it's doing there I think we can simplify and remove just like all of this code by just creating a more clever version of display result so for example we could give it the reversed first name a string the reversed last name a string and then the reversed city a string okay alright now there's a couple of things here the first thing that you see is that all of these input parameters that we've defined are separated by commas so in this case we have one input parameter we're accepting one string and in this case we're accepting three strings separated by commas alright I may want to move these two separate lines because frankly it's a little bit annoying to have to move off to the side of the screen notice in this case I didn't have to use the the line continuation character whenever we're defining or calling methods and we want to put those methods parameters on separate lines just to kind of line them all up and make them all kind of nice and compact as opposed to just moving off the side screen we don't have to use the line continuation character so that's a huge score for us alright so the next thing that we'll want to do then is do something like this in fact here I'm just going to copy this and in this case we'll just go instead of using one replacement code I'm going to use three code so instead of just using the curly brace open and close curly brace and then zero I'm going to use also open curly brace close curly brace one open and close curly brace two and then I can pass in all of the things that I want pushed into that format so for example reversed first name comma reversed last name comma and then reversed city comma like so and here again I don't have to suffer with my code running off to the right hand side screen I can just go ahead and hit enter on the keyboard and move them down to the next line and now even though this does take up a lot of lines of code they're really just parameters that have been moved to the next line alright so it's really just what four lines of code as opposed to what I have here about eight lines of code and the next thing you might be wondering is how in the world did we name our new method the same as our old method what we did was we created an overloaded version of our method so you can create more than one definition for a method now look what happens in IntelliSense whenever I type in display result and use the open parenthesis you'll notice that IntelliSense will show me that I have two versions of this method the first one accepts one string as an input parameter but if I use the down arrow on my keyboard or the down arrow in this case on the little IntelliSense pop up then you can see that there's a second version of this method which will allow me to pass in three different strings the reversed first name, last name and city okay so why would you ever want to create three different versions of the same method typically you want to create multiple versions of a method if you're creating a framework that other people will use you can even do it for your own use if you need to be able to call a given method in several different ways depending on the usage or the purpose doesn't really make sense in this case because the application is so small I could really just go and delete this first version if it wasn't for the fact that I was just trying to teach you how to create an overloaded method now the key to creating overloaded methods is this the method signature must be different for each overloaded version of your method and a method signature is the number and the data type of the input parameters that are accepted as input parameters to the method so in this case we have one input parameter of type string in this case we have three input parameters of type string we could create another version of display result that had message as integer and visual basic would be just fine with that why because the method signature is different even though we have one input parameter their data types are different but what we can't do is this we can't say other message on this case we're going to get an error and you can see as we hover over it says that it has multiple definitions with identical signatures well but wait a second I named this message and I named this other message the method signature has nothing to do with what you name the input parameter only letters and the types of each of the parameters so these are essentially the same method signature even though we are using a different a different name for the input parameter okay delete all that alright so that's an a overloaded method this forces us now to rethink how we actually are calling our code here so I'm going to be able to delete like all of these lines of code here all of these lines up to that point okay and what I'll do is just call display result I'm going to use the new overloaded version of it by using the down arrow on my keyboard to give me that little guidance there and so the first thing is called I think first name array and then last name array and then city array like so I don't think we're going to get the satisfaction from this that we want but let me try and see what this looks like just now before we go too far okay and it actually does work we don't have to do anything else how does it work fortunately console dot right line is smart enough to take just about anything we throw at it and it doesn't know how to deal with an array of characters but it sure does know how to take an array of characters and how to flip it around and display it in as a string so we don't have to do the for next at all fortunately now we could go the extra mile if we really needed to and do something like string concatenate or concat and what that would simply do is just take each individual element of the array and add it together but again fortunately in this particular case console dot right line does this for us and we don't need to do that now the funny thing about console dot right and console dot right line if you take a look at their definition there's 19 overloaded versions of right line so again it will take just about anything you give to it you can see that the fourth version of it will take character arrays and so that's essentially what we've given it we've given it that string we've given it character arrays it knows how to deal with it that's because somebody nice at Microsoft said you know it might be useful if we gave overloaded versions of console dot right so that no matter how you call it it will actually do what you think it will so look how much code we've been able to eliminate by just by being a little smarter about creating a method and then passing in the appropriate values to clean up some of this initial stuff here we're actually collecting these values and so what I want to do next is actually create another method and this time what I want to do is create a function and a function is just like a sub routine but a sub routine will fire and then end quietly but not a function a function will end and return back a value so for example let's just call this get reverse string like so and we'll type in messages string and we're going to expect a string to be returned from this function so notice we defined our input parameter but we've also defined the data type that we would expect as a return value when we call get reverse string so inside of this code block here this function we can do something like this so dim message array char array equals message dot 2 char array character array array dot reverse using that message array we just got our hands on and then what we want to do is return string dot concat like we just learned about and give it the message array and that should again take all of the individual characters and munch them together back into a string we're going to return that string back to the caller alright so let's see how that's going to affect what we're doing here this really gets pretty simple at this point we don't have to and we've already eliminated some of this application but we can get rid of yeah pretty much all of this code right here these six lines of code get rid of that and what we can do is just wrap get reverse string around the console dot redline like that how crazy is that right so get reverse string passing in a string whatever is returned from redline we'll save it here in last name get reverse string now we're going to need to change these input parameter names to first name last name and city instead of what they were formerly named as because we already did some of the work outside of our display result now look at this we've really paired this down a few lines of code and we can easily see what the code is attempting to do we're going to grab whatever the user types in and reverse it and then display that to the screen and so now starting to read a little bit more like a paragraph and we can see that it still works hopefully let's test it to make sure and it does awesome okay but before we say that this is finished what I want to do is create one more version of this reverse string just for kicks now what we've been doing up to this point is just passing an input parameter with using the default technique which is something called by value which means that whatever we pass in here will actually just be a copy of the actual value that gets passed into our method what if we wanted to actually make a change to a variable itself in other words what I mean by that is we create a sub routine called sub reverse string and instead of just passing in the message as string will say tell you what instead of just giving us a copy of the value so in other words just instead of giving us Bob or Tabor the value give me the actual memory location where I'm storing the value Bob or the value Tabor give me the memory location the bucket in the computer's memory I want to manipulate the data in that bucket alright so I know that's kind of an odd way of looking at it but here we're just passing and saying oh yeah the value that we've gotten back is Bob or Tabor but in this case what we're saying is I want to actually have a link to that location in the computer's memory and I'll manipulate that directly from my reverse string sub routine alright so to make this work we're going to have to redo our code a tiny bit specifically here and we'll just change this around a tiny bit instead of calling we get reverse string right there let's keep riveting I'm going to call it um we'll call reverse string right there as we're making the call in now you can see I'm going to get going to get some problems here because this does not return a string so I'm going to do it a little bit differently than that even alright and this will add some lines of code but I just want to show you the difference between buy value and buy ref so let's take um reverse string and we're going to pass in first name reverse string last name and then reverse string city alright so here what we'll do is instead of the default which is buy val we'll say instead give me a reference so I'm going to say we're going in by buy reference so this will give me an actual connection to the variable first name or last name or city in the computer's memory and now it can manipulate that directly okay and so I'll just do dim message array as char array equals message.to char array like so whoops array.reverse message array and that should be all I need to do because this message whoops I think I need to do one more thing which is string.concat uh actually message equal string.concat message array like that okay that should work let's see how we're going to manipulate the value of message but we're not returning anything that's because we're actually manipulating the value up in the bucket so now let's run the application and and it still works okay pretty cool so we learned quite a bit in this in this lesson now before we kind of wrap up here on developer university I issue a decree and that is that no method should have more than six lines of code in it if it has more than six lines of code it's probably trying to do too much in the system now of course rules are meant to be broken but as a rule of thumb this six line rule will keep your code nice and tidy and readable now I've broken that rule here only because I'm trying to illustrate some ideas but ideally we would compact this down and make this much smaller creating more smaller methods preferable to creating one monolithic method with just a ton of code inside of it so we want to create lots of small methods create methods with good names and let those methods drive the storyline of the application as it unfolds as it's executing okay but in this in this lesson we looked at how to define our own methods creating sub routines which fire and then end quietly versus functions which fire but return something of a given data type and we declared that with the as data type name at the end of the function we looked at creating input parameters and we looked at creating multiple input parameters we looked at creating overloaded versions of methods by creating methods with different method signatures and a method signature is simply the number and the type of input parameters for a given method we looked at how it looks like from a consumption standpoint when we use IntelliSense to show us the different versions of our methods we looked at passing values into methods using both by val which is the default we're just passing the value of the bucket in making a copy of it essentially and passing it versus by ref where we're saying actually let me deal with the bucket directly like we did here so that I can manipulate exactly what's in memory so when I'm reversing those strings I'm reversing first name it started off as Bob or Tavor would be a better example and ends up as robot so that when we're displaying the result it will it'll be actually manipulated by the point we get to that line number 20 okay and even though we've added a lot of extra code here we really did not dramatically expand the number of lines of code notice we only went from like 50 to 53 a lot of this can be stripped out right so we could have completely reduced this code down to just a handful of lines of code very cool now if we ever need to manipulate how the the reverse string algorithm works we just change it one little spot we ever want to change how the code is displayed we change it one little spot and we're done okay alright hopefully that all made sense and hopefully you're starting to get a sense of what it means to to write your code correctly to make it readable maintainable to think and have a strategy for your code maybe rules of thumb that help you to keep the scope of the code on a per method basis down as small as possible nice and tidy nice and understandable nice and readable okay so that's pretty much that wraps up this topic we'll continue on the next lesson we'll see you there thanks Hi I'm Bob Tavor with Developer University for more of my training videos for beginners please visit me at devu.com this video we're going to take a look at another iteration statement we're going to look at the while iteration statement so if we kind of do a quick review on the iteration statements that we've already learned about first of all we looked at the for iteration statement which allows us to loop through a block of code a preset number of times based on how many items that we've kind of decided in the for statement itself so we create a counter of sorts and it will iterate through the number of times in our counter so there's a preset number of iterations through a given block of code we also looked at the for each which iterates through a block of code once for every item inside of an array and so again that's kind of a preset you decide ahead of time how many times you're going to iterate through a given block of code but what about those situations where you don't know up front how many times you need to iterate through a given block of code you need to decide that inside of the block of code inside the block of code will dictate how many times to iterate through the block of code I'll give you a quick example of that well in those cases you'll use the while statement and you'll test to see if a certain condition is true if it's true you'll continue to iterate if it's false you'll stop iterating you'll break out of the loop and then we'll also look at the do while statement which is very similar except it guarantees that you run through the block of code at least one time so we'll look at that subtle difference in this lesson to begin you can see that I've already created a new a new project called while iteration so you can pause the video catch up with me I just created a new project named it while iteration and there's gonna be a lot of typing so what I'll probably wind up doing is pausing the video while I type and then I'll pause the video or you should pause the video after I'm finished typing so that you can type in all the code that I typed and then we'll explain it and walk through it together alright so here we go we'll start with a really simple really simple example of the while and then we'll blow it out to a much more interesting example something that's very practical that we would probably wind up using in a real console window application by creating a menu but let's start simple and so again a lot of typing I'm going to pause the video right about now okay so this is a pretty simple example like I said a moment ago here all I'm doing is using this while and while statement to create a block of code and we'll continue to execute this block of code until the user response variable is no longer true when we set it to false then we will break out of this while statement and continue on with the execution of our application now you'll see here that I am keeping track of a counter so I have this counter variable that I've created in line number five and then line number eight you can see that I'm adding one to that counter variable by taking the current value of counter and adding one to it this is just to let me know that how many times I've actually run this block of code just for a simple example and then I'm going to print that to screen that this code block has executed that many number of times and then I'm going to ask the question do you want to continue or not if the console dot read line is equal to why for yes then we'll return true when user response is true then we'll go and execute this block of code another time but if it's false then this will no longer be correct or true and we'll break out and let's watch this actually run the first time through I'm going to type in the letter y and hit enter I'll type in the letter y and hit enter I'll type in the letter y and hit enter and then I'll type in the letter n and hit enter and now we've finished and I can press enter to exit okay so what the while and while statement does just to recap is that will continue to execute a given block of code until a given condition is no longer true in this case user response will is the is kind of the key that we're using here to determine the whether we should continue running through this block of code or not alright so again a very simple example what I'm going to do is actually select this entire block comment this out it's not every practical example so I want to give you something much more interesting to work with and so for this next example we're going to create a a menu system like you might have seen if you ran DOS programs way back like 25 30 years ago okay so here we're going to go ahead and start typing I'll pause the video you can catch up once I finish typing in you'll want to pause the video type in some of the code yourself okay alright so you can see here that and again please pause the video I'll give you an opportunity to type in all the code I'll give you a nice clean screen like this pause right now because we want to start by writing this code to display a menu so we're doing something similar here with the user response we're just going to call it display menu this time as a Boolean we're setting equal true and while display menu continues to be true then we'll continue iterating through now you can see here that I did not have like an equals true that's kind of redundant you don't need to do that because display value or display menu rather is already a Boolean it's going to be true or false so all we need to do is just check whether the expression in this case it's just a variable equals true or false well display menu already equals true or it's going to equal false by its very nature because it's a Boolean so you don't have to do the equals true or equals false part whenever you're evaluating a Boolean okay so here's what we're doing we're actually calling this other function called main menu and then main menu will return back to us a Boolean and then we'll decide whether to rerun the main menu based on the response that we get from main menu so the real work goes on in this function main menu is Boolean here I'm going to clear out the console calling the clear method alright so that's a new method in the console here we'll just wipe out everything that was currently being displayed on screen then we're going to say would you like to either play the print numbers game the guessing game or would you like to exit out of the menu system here we're going to retrieve the result from the user what would you like to do one two or three and here's where we then decide what are we going to actually do are we going to call into another method called print numbers because they want to play the print numbers game or are we going to call into the guessing game method and I'll show you those in just a moment because they selected number two or do you want to return false alright so in these cases these methods will return a truer false here when they want to exit will return false that'll get bubbled up through main menu into our main and display menu will be set to false so we'll break out and and the program at that point ok so if they type in anything else then we'll return true which will return back to here which will then set display menu back to true which means we're going to call main menu again we'll clear out and then say alright well you didn't give us one two or three so I'm going to give you another chance to answer the question and if you ever get confused about the flow of this application just set a break point and step your way through it using the debugging tools right so you can see how this actually works now inside of the print numbers in the guessing game for now all I did was just implement console dot right line we're going to we're going to come back and flesh this out so I've just stubbed out this method for the moment but in both cases we're going to return true saying ok we finished the guessing game or we finished the print numbers game why don't you just go ahead and re-show this menu to the user so they can decide what else they want to do inside of our application so the nice thing about this little setup and you can use this same little scheme that I've cooked up here to create multiple menu levels inside of a DOS based or rather console based application ok we'll flesh out these to show some more features of the while statement and then also look at that do or the the do while loop as well let's run the application see how it works so the first time through we see there is a choose an option one two or three I'm gonna choose number one and even though unfortunately you see that nothing really happened the reason is because I forgot one line of code in both of these console.reline cause we want to be able to show that text before we continue on ok here we go do it again print numbers game here press number two guessing game here press number three and it exits alright so that's how the menu system works now let's focus on another aspect of this print numbers method and the guessing game to look at two different coding examples revolving around the loops the do while and the while loop ok so I'm going to pause the video again here as I type in some more code alright so I went ahead and fleshed out the print numbers method can pause it and catch up here and then I also created this guessing game method you can see most of it on screen right now pauses right here if you want to catch up and then you can pause to see this end part in lines eighty two eighty three four so like I said a lot of typing but you'll definitely want to catch up with me and and type all this in let me explain a few things about how this works so the print numbers game let's just go ahead and run the game and see how it works let's choose number one and we can type in number I'm going to choose the number seven hit enter and you can see all it does is just print off from one to seven and that's pretty simple right then let's play the guessing game it's a little bit more involved and we get to guess a number between one and ten this is where things start to get a little bit more interesting I'll guess the number three that was the wrong answer number four number two number six seven eight nine what did I miss five all right it took me nine guesses all right so we randomly choose a number from one to ten it's pretty cool and then we keep asking what do you want to guess the number we can improve this and maybe that's a good exercise for you to say you're getting warmer or you're getting colder or it's higher or slower maybe give some hints as well but now we can exit out of the game so the print numbers game recall it was fairly simple all we're doing here is just allowing the user to type in a number and then we're going to actually read that number from the read line method and notice that I've got this little C int we're converting read line because it returns to us a string value as you can see over there on the right hand side but what we need to work with is an integer value and the bucket sizes are different so we're going to need to convert from the string which if they type in the letter the alphanumeric character seven we need to convert that into the integer value of seven those are two different things alright so now that we have an integer we can work with it in a mathematical sort of way adding numbers to it and so on as long as it's a string seven if we were to attempt to add one to it we'd probably get a seven one instead of eight okay anyway we create a counter just to keep track of how many times we're actually iterating through and we're going to continue to iterate through until we get to the same result value that the user typed in which point then will pop out of our looping statement and continue on alright so for each number from zero to or as long as we're continue to be less than the value that was typed in we'll continue to iterate through but when this is no longer true then we'll pop out of the iteration statement alright so let's move on and look at the guessing game now in the guessing game you type in a number and we are going to try and guess the number that the computer has selected how do we get a number that the computer selects we're going to use this class called random random is a class created by Microsoft now it's similar to the console class and so much that it's part of this library of code that Microsoft's allowed us to use inside of our applications and it specializes in creating random numbers but the way that we're using is a little bit different like in this case notice that all we had to do is to say console class dot clear console class dot right line whereas in this case we have to do something a little bit special we have to create a new instance of the random class and so we're creating a compartment in the computer's memory a bucket in the computer's memory sufficiently large enough to hold this random data type alright and so we're going to call that bucket in the computer's memory random lowercase r random alright so it's a little bit different than in the usage and I'll explain the reason why the different usage in an upcoming lesson when we talk about classes alright but at any rate so now that we have an instance of the random class we can use the random classes methods in this case we're going to use the next method to grab a number between one and ten so we give it what's called the lower boundary so I want a number that starts anywhere from one but I don't want you to go to eleven so that's the upper boundary don't go to eleven twelve thirteen stop at ten so it's going to pick a random number from one to ten and store that number here we're also going to keep track of the number of guesses for the user so if it took them five, six, seven guesses whatever the case might be and then we're also going to create this incorrect boolean flag because I'm going to anticipate that the user will be incorrect a number of times and this will be what ultimately breaks us out of the do-while loop and say you are correct it only took twelve guesses and then we'll actually show the number of guesses on screen now what happens inside of this code block is important notice that we're not using the while statement we're using that do-while loop that I alluded to a moment ago and remember the quality of the do-while loop is that it guarantees we're going to run this code at least one time so in this case I need to at least one time make sure that the user can see that they can choose a number between one and ten and then every subsequent time I'm going to ask them again which is picking a number between one and ten you're wrong picking a number between one and ten so I needed that inside of the code block inside of my loop and I needed to run it at least once that's why do-while loop made sense in this example now we're going to retrieve the guess from the user and then we're going to increment the counter of guesses now I could have done something like this like I did previously guesses equals guesses plus one but I chose to use a little shortcut which is the plus equal and so those two lines of code are equivalent I just had to type fewer characters so take the variable guesses and add one to it is essentially what line number 74 says alright next up we're going to take a look here at the little check that we do now we're going to grab the random number from the user and this is the important part notice that random number is an integer but I'm going to convert it to a string by calling the two string method I could have done something like we did earlier with CSTR like that and that would work just as well so I'm going to convert this value to an integer I'm going to convert this value to a string I'll just go ahead and leave it like this so we're converting data types so this is an integer but I need it to be a string so that I can compare it to the result I just did the same basic thing two different ways here in these two different methods but it's essentially the same kind of check if the guess is incorrect then incorrect will equal or I'm sorry if the result is equal to the random number so if they guess the correct number then it's no longer incorrect it'll be correct so we're going to set incorrect equals the false which will then break us out of the loop however if they are in fact incorrect will stay true and we'll just say hey you're wrong try it again and we'll loop through this block of code another time but assuming that they got it correct we bust out and then we just merely print this to screen and then we return true in order to get back to our menuing system and allow somebody the user to choose a new game alright so hopefully you learned quite a bit in this lesson we looked at a simple use case where we're just using the while statement in order to evaluate something and decide whether we should continue to iterate through the block of code based on something that happens inside of the block of code we looked at how to create a menuing system using the while loop and then we also looked at using the while loop in some creative ways in a more practical example here and then we looked at using the do while just to compare the while versus the do while the only difference is running the block of code a guaranteed time at least once versus not running it potentially one time and then we also looked at a few other things like converting types using the CSTR so convert to string and convert to int method we also looked at using the plus equal operator so we also looked at the random class and how we're able to generate a random number now we can create some interesting little games alright so hopefully that was a pretty helpful lesson a lot of typing but again that's good for you creating muscle memory new observations come whenever you're typing in the code in yourself as opposed to just watching somebody else do it so make sure you're getting your hands dirty in the code alright we'll continue on the next lesson we'll see you there thanks hi I'm Bob Tabor with developer university for more my training videos for beginners please visit me at devu.com now many types of applications that you'll wind up writing involve text whether it's text that you'll need to feed into other applications or text that you'll retrieve from end users or text that you will actually format for display to an end user so there's this notion of massaging data changing it in subtle ways in order to format it specifically for input to another software system professional software developers spend a lot of time taking data changing it in some way and then putting it into another format for ingestion into another software system or formatting the data for display or looking at the data that's been input or by an end user or by another system and ensuring that it's in the right state that it looks correct in order for it to be used inside of our application so mastering the manipulation of strings is a vital skill in visual basic furthermore the string data type can hold a lot of information it's actually when you compare the buckets and the sizes of the buckets in the computer's memory the string bucket is a massive bucket if you want to continue that analogy so efficiently working with strings is another vital skill in visual basic in this lesson I'm going to demonstrate several common string manipulations that are made easy by both visual basic proper as well as the .NET Framework class libraries and the inherent functionality that it just baked into the string data type the string class so you can see that I've already created a new project called working with strings and we're going to do several different things we're going to work with special characters inside of our literal strings we're going to format strings for display using the replacement syntax that we've already looked at a couple of times we're going to look at it has actually more functionality than what we've seen up to this point we'll look at just basic string manipulation pulling things out putting things in breaking it apart things like that and then we'll take a look at working with large strings more efficiently by using a special class called the string builder alright so let's begin by looking at how we work with literal strings and special situations with literal strings so for example I might create my string equals my so called life and I have a couple of options here if I want to say this in an ironic way I could separate so called using a single quote but what if I needed to use a double quote unfortunately if I use double quotes it's not going to look quite right and I'll get some errors here because we're not able to tell the visual basic easily that we just want to use a double quote here inside of our literal string so to fix this you can escape double quotes by using double double quotes together so when I pair up double quotes like so we're saying we want this to be treated as a as a double quote inside of a literal string same thing with this second instance right here and so we're able to treat the whole thing as a literal string and if we were to print this now let's go console dot right line my string and we'll go console dot redline it will actually print out correctly for us and I just hit the F5 key on my keyboard to run it instead of hitting the little run button the start button on my toolbar you can see it formats it correctly my double quote so called double quote life great all right so next up let's comment that out and we'll take a look at what if I need to add a new line or a line break in between a literal string so here I might have my string equals what if I need a new line I want to put maybe that that new line character right here how do I do that well we've already seen the little technique that we've used to kind of add to two literal strings together using the ampersand character right and so what we can do is actually in between the ampersand characters use the special the special constant called VB new line alright and there's a bunch of these little constants that are available for VB if you type in VB and you're looking in tele-sense some of these have very specific usages that may not make sense here but I'll show you a couple of these throughout the remainder of this lesson but for now we just need something that tells visual basic that we want to create a new line right in the middle of our literal string so let's go ahead to the application now and you can see that we were able to break onto a new line even though it's one literal string here that we've created on line number 6 alright what if I need to add a tab in the middle a tab spacing in the middle of my literal string so what if I need a tab in my line so the same thing would be true here I'm going to go ahead and start the process by splitting these two segments into two literal strings and appending them together using the ampersand add a second ampersand and glue them together with then a VB tab so another constant from visual basic the VB tab constant and now when we run the application you can see that it puts a tab spacing in between the two segments of my literal string so that's how you insert these special characters or these special situations into your literal strings alright next up let's talk about the formatting the special formatting that we did inside of strings using member console dot right line and we were able to say hey there's this replacement syntax and I can replace that with something like Bob so I can do hello comma and then the replacement code 0 whoops and let's go ahead and just remove that part so we did that right and we could see something like this right so what if let's get rid of that and let's go back down here what if I need to do that same sort of replacement code inside of a literal string instead of using console dot right line because you saw that wouldn't work I can use string dot format and it's identical we can do the same sort of thing with that so hello comma replacement code 0 Bob exclamation mark and let's go ahead and dim this string equal string dot format there we go that's the correct incantation and we get the results that we're looking for so string dot format will allow us to add the the replacement codes the formatting replacement codes here inside of a literal string here I just used another little string but we could use a variable or whatever alright so that's a very simple case but let's look at some more interesting cases so for example we already looked at an example where we were able to use multiple input parameters so string equal string dot format and then we were able to do something like the make zero the model one and the maybe even year two of course this is zero based and we'll do so we have a very specific format that we want to print our string to screen and then we can also then add in the values that we want like for example BMW 745 li and 1995 alright and let's go ahead and put some of these on separate lines so you can see them so I'm going to add a line continuation character right after the equal sign and then I'm going to go ahead and split these off into different lines as well for readability sake like so so this is all one line of code even though I split it off into multiple lines and now let's see what we get whenever we run this and the key notion here is that we're able to insert multiple replacement codes inside of a literal string by just supplying then a list of input parameters after the template that contains the replacement codes it's zero based so the first item, the second item, the third item will be replaced in to those replacement areas that have the curly braces and the and the index now we can mix things around for example like I could take the two and put it here and take the zero and put it there and then I could also use the same replacement code twice inside of the same string so that I could essentially use that same number 1995 two times of course this will be nonsensical because the make is not 1995 but you can see at least I'm able to switch around the order it does not have to be just in the exact same order as inside of the we have the items that we're passing in but this is still element zero, one, and two we're just putting them in different places inside the template and even reusing them multiple times alright let's comment all of that out and now let's take a look at an even more interesting usage of this so my string and say that we wanted to format a string for a specific purpose like we wanted to take the number 235 and this number we want to represent it as currency so in that case inside the replacement code we're going to use the colon and then a special replacement code formatting syntax and this will represent this as currency now if you're in another country and for example if you're in Great Britain it will represent this based on your operating systems locale feature so you may have it represented with the British pound sign as opposed to American dollars with the dollar sign and so it's smart enough to know how it should be represented on screen in this case you can see the dollar sign 2335 alright here we're going to do the same thing dim my string and a string now you may have noticed here that I was able to do this and not declare a data type I don't recommend that you do that it's kind of an advanced topic to explain what happens when you don't do that I don't want to get into that right now let's just go ahead and fix the code but that was my mistake but it will still work okay but it has a different connotation on the downside so we'll just not do that alright next up let's format this number 1234567890 but let's format it as a real as a real number with commas and decimal points at the right spots alright so I'm going to use this special format code colon capital N alright and so now let's run this and see that it makes it into an easily readable number of 1234567890 0.00 okay so that's the N formatting code and then here dim my string string what if we needed to represent a number as a percentage so string.format and we want to take the number 0.123 and represent that as a percentage so again we'll start with the replacement code 0 but I'm going to use colon P this time and now you can see that it will print out the number as 12.30 or 3% with the percent sign it also uses the decimal place in the correct spot so that's how you work with the replacement code and the formatting of a percentage and then finally you can create your own custom templates I guess you can say area codes using for example I want to create 1234567890 I'm going to create a phone number so I want to use the way that you would represent a phone number in the United States which is three digits for an area code so I'm going to use pound pound pound which means just three numbers the first three that you have here and then a space and then pound pound pound dash pound pound pound pound pound okay so that's the format of a phone number I could even do something like this phone colon just to kind of flesh out this example a little bit alright so now let's see that in action let's run the app and whoops didn't do something here oh that's right alright I only I didn't give it the replacement so here's what we need to do wrap a set of curly braces around it zero and then colon and now this becomes the template for the replacement code okay now let's run the application and you can see it formatted it using the numbers that I supply what if I were to supply more numbers we'll put a one here at the end then what the template can hold let's see what happens what's the behavior here well notice that it pushes it to the very it pushes it from right to left so it's going to honor the template from right to left now it's going to push more digits into that area code area unfortunately it's not what we would probably want however we should probably validate our data to make sure it's an actual valid phone number before we do any formatting about it formatting with it alright so moving on we're going to talk about dealing with strings large strings we already said that the string bucket is very large the problem with working with strings is that they are what's called immutable so whenever I put a value inside of a bucket that's holding a string or a variable that's holding a string if I want to change what's in that bucket I essentially what's going on behind the scenes the .NET runtime is going to create a second bucket it's going to pull all the values into the second bucket plus the new value that you want to append to it and then it's going to remove the old bucket and then it will change the label on the new bucket and so it does all this for you behind the scenes but it's a very intensive process to make changes so if I were to do this for example just to kind of illustrate what you should not be doing and let's go for tab tab index equals one to one hundred and inside here I'm going to go my string plus equals or actually ampersand equals so take what the current value of my string is and I'm going to add on the index now I'm going to convert that CSTR to a string ok so that I can take this numeric value and then convert to a string and then append it on to the end of this string plus I'll go ahead and append on a dash dash just so we can kind of see that in action like so alright and then we'll run the application and you can see that it'll do it pretty quickly we get from one to a hundred with double dashes in between but what we had to do that little maneuver behind the scenes a hundred times and unfortunately that will be very processor and memory intensive that's probably not the way that we want to append a lot of strings together instead we can use a special class whenever we're working with a lot of strings and we're going to do a lot of appending of strings and we don't want to take up more more memory and processing power from the computer then we absolutely have to so we're going to use a special class called the string builder so here in this case instead of declaring my string as a string I'm going to create it as string builder and so in this case you'll see that I'm going to type this class named string builder but it cannot find the string builder class in the .NET Framework class library now the reason for this I'll explain later but notice that as I hover my mouse cursor over it it shows a red squiggly line and this tells me there's an issue the type string builder is not defined now I know that it exists in the .NET Framework class library so what I'm going to do is actually utilize this little light bulb that popped up underneath the word string builder and it gives me an option to either do one of two things actually several things but these first two are the most important I can either say give it to me because I know it exists in the system.text.string builder namespace whoa what's a namespace we'll talk about namespaces later so it's like a last name for your classes alright or as you can see I can as I get the little light bulb popping up here I can import system.text and when I do that it will add this little line of code at the very top the very first line of code to import that namespace so that it can find this class inside of the .NET Framework class library so like I said the class name is string builder I know it's somewhere in the .NET Framework class library I just have to go to the right shelf on the library to find that class alright and so that's all I'm saying here hey go to the system.text shelf and you'll find a class name string builder there so we're giving a little extra instruction to visual basic to where it can find this string builder class inside of the massive library of functionality that that Microsoft gave us okay so we'll just do that and now that we've included or found that I'm actually do as new string builder again we'll talk about the new keyword a little bit later and this time we'll go for tab tab index equals one two hundred enter and inside of here what we'll do is my string dot append so we're going to use the append method and it's more memory friendly than using the ampersand equals in order to in order to append two strings together this will not perform that little dance in memory that we suggested earlier so in this case all I need to do is use the index alright and I don't even have to do that little conversion but I'm going to anyway CSTR index to convert that number into a string and then my string dot append and we'll go with the literal string now the result will be identical however you're going to see a strange behavior here at the very no it didn't okay very good so you can see that we were able to get these exact same results it was just much more memory friendly than doing it this way okay using the string builder alright let's continue on I'm going to comment all that out and move on and talk about doing some string manipulations by being able to identify or manipulate the certain parts of the string so I'm going to start off with a phrase from a song that I like I'm going to add a space and then last summer we took threes across the board period space space alright so I have a leading space in front of this in front of this phrase and then two trailing spaces at the end and we'll look at how to trim those off in just a little bit first thing that I want to do however is set my string equal to just a subset of these so I just want to pull out certain words or certain phrases inside of the string and I can use my string dot substring look at that method that it gives us and I can choose to say hey start at position number 13 and return back everything count 13 0 1 2 3 4 5 6 7 8 9 10 11 12 bring back everything after that and then print it to screen and you can see we did that I can also say well this is the starting point but I can also give it an ending point as well so I'm only going to choose 15 characters then and print those out so we took 3s as opposed to the entire the entire message I just grab off 15 characters put them in my string I can do something like this my string equals my string dot to upper and that will make the entire string uppercase like so or conversely I can make it all to lower like so and it's all lowercase furthermore I can replace characters so my string equals string dot format whoops I'm sorry string let's start that over again my string dot replace and what I want to do is search for the old character which will be just a normal space character and I'm going to replace it with double dashes so for every space that we see it will be replaced with double dashes and you can see then we get the following with 4 dashes here at the very end because we had 2 spaces here at the end of our original string and one of the other things that we can do with strings is get the length so for example let's go ahead and do my string equals string dot format and I'm going to say my string is so many characters long alright so we'll start there and say show me my string length just like we used with the array to see how many elements are in the array we can also do that with a string again a string is just really an array of individual characters right so we can see how long how many characters are actually in the string and print that out that the my string is 47 characters long very cool okay now what I'd like to do I'm like to use the trim function and so we're going to just add on to this after trim then we're going to print off the length of our string so what trim will do is actually remove any of the leading and trailing spaces for a given variable or in this case a literal string and then it will return back the new string without leading and trailing spaces however in this case since it returns a string I can continue to call another function or property of the string and I'm going to call length again so I'm chaining together commands this is a string this method returns operates on the string and then returns a string and since it returns a string we can then go ahead and call another method that we get access to the string class and that is the length so here we go and we'll run it this time and so we've cut off three characters and so you can see after we've called the trim it's only 44 characters long alright and so we can also just so you know do mystring.trim we can only trim off the start or trim off the end okay so you have some options there you don't have to trim all the spaces you can just do the first or the last spaces using the trim start or trim end alright so that's pretty much all I wanted to show you but ultimately I would say that you should take a few moments and look at the other functions that or methods that are available on the string class and just take a moment to learn about them there's a lot more that you can do some of these won't apply but some of them will and before you go and just start trying to manipulate strings and you know write like more than one line or two lines of code to make some significant changes to strings just remember that you could probably find an easier way to do that just using the built-in string method you may have to get a little creative sometimes but you definitely can figure out how to manipulate the string to make it exactly the way you want using the built-in functions you just have to find the right combination of functions and call them in the right order and it'll probably make your life a lot easier alright so that finishes up our discussion of manipulating strings let's do the same thing with dates and spans of time in the next video we'll see you there you're doing great thank you hi I'm Bob Tabor with developer university for more of my training videos for beginners please visit me at devu.com in this lesson we're going to learn how to manipulate and display dates so how to add values and subtract values from dates date math can play with your head how to display different parts of the date or how to use some of the built-in features in visual basic and the dot-net framework class library to display dates in various formats we'll also look at how to work with spans of time so three years five years thousand days whatever the case might be and subtract and add values to those and a lot more so this will be fun you'll need to work with dates for the same reason you'll need to work with strings and business applications dates are pretty used frequently for things like project management for content management systems for order management systems and so on so we've learned how to work with a string and integer and we've learned how to work with a Boolean now we're going to add a new data type that allows us to work with dates and times and then later a new data type that allows us to work with spans of time so we'll start off by working with dates so here we're going to go dim my value as date and if we were to just work with the date by itself I think it's important for you to see this right off the bat let's go ahead and just write out the value of the default value of a date and see what we get because at this point we've not initialized the date so it's the equivalent of an empty string or the value of zero for an integer which is the initial value and that's generally not what we want to work with but I want to show you what you'll see if you were to work with an empty date it'll give you some representation of a date it just might not be what you want so let's go ahead and run the application and so it's going to give us January 1st 81 at midnight okay so that's probably not the value we want to work with unless we want to see how many minutes, days, and seconds since January 1st 1 AD at midnight instead what we'll want to do is initialize that value either to a specific date in the past or future or if we want to work with now there's a special function in visual basic that allows us to work with this moment as the application is running it's called the now function if we run the application we'll see that I'm recording this on May 24th at 10.35, 35 am alright so what if we want to format that date for display well there's a couple of different ways a couple of different built in features of dates that will allow us to format it for display featuring different portions or representations of dates so let's go myvalue.2 let's see there's just a bunch of these two methods so to local time to long date string let's use that one first to long date string then we'll go console.rightline myvalue.2 short date string let's do the same with times console.rightline myvalue to long time string and then you're going to see that there's not much of a difference between the two but I wanted to for the sake of completeness show you the two short time string as well and let's go and run the application we should see five representations of now on screen so again this is without the default format if we print it off we'll just get the date and the time and the ampm portion the long here let's compare these and put them right next to each other here so the long date string will give us Tuesday May 24, 2016 nicely formatted and again this will depend on the culture of your computer so if you are in Europe or if you're in some other country you might see the default representation of the date different than what you see on my computer which is set to the culture being English United States and this is a common way that we would represent dates so here the short date string we just see the month day year again you might see day month year which is common in Europe and other countries then the long time and the short time pretty much the same the only difference is that with the long time we see the seconds not just hours and minutes and then am or pm and there's different ways that we can represent if we want something a little bit more custom so for example we can just pull off a specific portion of the date in this case myvalue.month and I'll use ampersand and then two dashes and then myvalue.year so we can grab off just about any portion even minute milliseconds we can pull off the time of day we can pull off day of week for example day of week day of the year whether or not this is daylight savings time or not that we're currently in um the time of day and so on so I'm just going to pull off day of week just so you can see this and we'll run the application and you can see that the day of week is two this starts with Monday is the first day I think Sunday as the zero day so just zero based I believe but five would be and then the day of the week would be the second item or the second index which should be the third item I think okay but what if I wanted to print something off a little more friendly than that for example what if I wanted to do the myvalue and I wanted to see for example the actual um the friendly month like this is May when I'm recording this so what I can do is call two string whoops two string and then I can use a special formatting provider and so in this case I know that I can just use four capital M's in a row in order to grab off just the month and print that to screen so you can see here this will print off just the month of May and for more information about that there's this page you'll want to go search for online custom date of time format strings search for this custom date and time format strings on msdn.microsoft.com so just go to bing.com type that in and then it should get you to this page and you'll see that there's all these different formats that we can use to pull off just for example um d lowercase d would give us just one through thirty one day of the month would give us zero one through thirty one so that's not all that helpful but we can pull off the HH for example giving us a twelve hour clock or capital H to give us a military clock so you can see examples here I use the four M's to give us you know the full name of the month or we can use three M's to grab a abbreviated for December it would be DEC from March it would be MAR and here we can grab off the different years and different um four matters for strings by just using two string and then passing in the four matter that we want to use alright so I just wanted to make you aware of that uh for reference now I said earlier that we can also uh do some some date manipulation by adding and subtracting days and hours and just about anything from our date so here we go console dot right line and here we're going to take my value and I'm going to add and notice that I can add lots of different things to it I can add a time span which we'll talk about time spans a little bit but more importantly let's like add days or hours or milliseconds or minutes or months or seconds or even years to the current day so if I say hey I want to add three days I'm saying what will be three days from now so uh I'll go add days three and then I'm going to chain together another method now remember what I said about chaining previously here we have a date I'm going to call the add days method to add three days onto the current date and notice that it returns back to me and it tells you can see that it returns another date to me so since it returns a date I can call another method on the date and I can do something like two short date string like so and now I'm going to say three days from now would be 27th right so today is the 24th three days from now is the 27th and I print that out to screen let's go ahead and comment that out too uh and like I showed you a moment ago you can do lots of really interesting things here my value dot add hours so three hours from now to short oops to short time string and that'll say three hours from now would be 142pm that's accurate uh what if I wanted to subtract days is there a subtract method no there's not but what you would simply do is just use a negative number so in this case I'm just going to subtract three days so three days ago to short date string three days ago would be the 21st of March okay so we can just use a negative number inside there now earlier I said that while we can create a um a date in the past or I'm sorry a current date we can also generate a date for the past or the future by initializing its value like so there's a couple of different ways to go about this so let's take my birth date for example as new date and notice that inside of the new date there is an overloaded what's called overloaded constructor and I'll explain when we talk about classes and creating new instances of classes really soon here in the next couple of lessons this will make more sense to you but essentially we can call the method at the time when we create a new instance of a given class and we can pass parameters in to initialize the date of that new object again this will make more sense later but just know that I can go ahead and provide for example some information as I'm creating a date in this case I can provide the year the month and the day to initialize an instance of date so 1969 will be the year the month will be 12 for December and the day will be 7 alright so this now I've created a new birth date go ahead and console.write line this my birth date and see it represented here in our window 12769 again the United States version of this would be December 7 1969 at midnight why midnight because we didn't specify a time but we could do that as well by saying I think I was born let's see do we even have a version of this that would allow me to pass in an hour yeah I think I was born like 7 in the morning so let's go like 7 30 in the morning even down to the second let's go 1 alright so now we've given more information as we've initialized our new date to the past December 7 1969 at like 730 in the morning okay now what can we do with this well we can do anything that we did previously with it we can actually use it to find out the span of time how many days have been alive so on we'll come back to that in a moment but this is one way that we can create a new date in the past or the future by initializing it in the constructor we can also do something like this where we create a my birth date as new date but we don't have to initialize it right away we can instead set my birth date equal to and I can use a string passing a string of the date representation using this parse method so almost every uh every data type including integer and so on they all have this parse and they also have something called try parse which we'll talk about later and parse will take some string and say I'll try to make this into a date if I possibly can so I'm going to give it some random string in this case I'm going to try to make sure that it lines up um with an actual date and hopefully the parse method is smart enough to take that string and convert it into a date uh and assign it then to the my birth day variable in which case you do get it to uh to work again here so that's another way that we can create a new instance of a date in the past or in the future and then the final way is to use some uh to create a literal date now in the past we created literal strings right uh by using double quotes around a string so I could create a string called 1969 uh or December 7 1969 but notice that this isn't going to work let me see if it works it works only because visual basic does some uh some it it is very forgiving like I said before it will do conversions for you if it thinks it can okay it's very clever in that way we shouldn't rely on visual basics functionality to do this instead what I'd like to do is use the actual literal characters for a date and instead of using double quotes you would use pound symbols around a date and that would make it into a real date so we would get that but yes we don't even have to use date dot parse with the string we can just give it a string and visual basics smart enough to figure it out but do not rely on that it's called evil type coercion evil because you can get you into some problems you should always be very deliberate about how you work with types in visual basic even though it forgives you if you're not very deliberate okay so always use the correct verbiage and don't rely on visual basic shortcuts would be my recommendation alright so uh let's get back to what we were working with originally here and create again dim alright and now what if I wanted to work with a span of time and so we're not working with hours minutes seconds we're working with at least in form of a date we're working with it in terms of how long something took or how long something will take so uh if I have my birth date then I can also calculate my age as time span so here's a new data type that represents span of time not the date but the time between two dates so uh in order to figure that out my age I'll take date dot now and since now returns a date we already know that the now what the now function does will go dot now dot subtract and then I'll pass in my birth date and that should give me a span of time uh for how long I've been alive now what I can do is go my age dot and see how many seconds I've been alive how many minutes I've been alive how many hours how many seconds and so on so let's look for the total number of days that I've been alive and it'll come back with a very large number sixteen thousand nine hundred and seventy point forty five days so whenever I run this the number always gets larger every time I record the series and I always feel a little bit older so at any rate that's how we would figure out then to use a span of time and we can do that by giving it two dates in this case I'm taking the current date and subtracting off another date to figure out that length of time and at that point then I can take my age and say you know ten days from now so let's um add um let's add a span of time so new uh time span and we'll say hey uh let's give it the number of hours minutes and seconds or the number of days and so on so uh let's give it in in one hundred days whoops one hundred days uh zero hours zero minutes and zero seconds how old will I be I'll be let's uh set my age equal to my age dot add and then run it seventeen thousand and seventy days old okay so we just added on a hundred days okay so that's how you manipulate dates and spans as well as manipulating times printing out various portions of dates and times uh and hopefully that'll give you all the tools again my advice regarding dates and times and spans are the same as my advice with strings which is if you're doing a lot of work to try to figure out how to how to manipulate a date time or a time spam you're probably doing it wrong there are so many built-in functions and we haven't even looked at them all that are available from the dotnet framework class library or that are baked right into the date data type or the time span data type uh just do a little do a little research online and search for the exact problem you're trying to solve and chances are there are existing functions that will take care of the majority of it so that you're not writing so much custom code alright alright so you're doing great we've made it so far through and I would really say that at this point we've hit the halfway mark because up to this point we haven't done anything all that complex things are going to start getting interesting now as we move on and talk about classes and this is always sort of a big hurdle for people conceptually the syntax of classes is easy it's just the conceptual nature of it so don't get discouraged everybody has this little hurdle and I'll try to do my best to explain it in a way that's understandable just take it in stride and understand it in the context of how the dotnet framework class library was built and if you understand it in those terms first then everything else will work and make sense for you and that's all you really need to know at this point in your journey towards visual basic mastery okay so at any rate this kind of concludes the first half of the course what comes next a little bit tougher don't worry if you got this far you definitely can do it you have the power to stick to it and I'll do my best to help out we'll see in the next lesson thanks hi I'm Bob Tabor with developer university for more of my training videos for beginners please visit me at devu.com now near the beginning of this series of courses I said that modules and classes were containers for the methods that you create but I did say at that time that classes had a special purpose and I think you'll start to see that special purpose emerge as we continue through this series of courses now the dot net framework class library is a library of code created by Microsoft that we can use in our applications right and I explained that the methods that we can use in our application like right line read line and the others they're all packaged inside of classes so to get to a specific method we would use the class name then we would use the member access operator the period operator and then the name of the method that we wanted to invoke and I explained that the console class contained methods that were all related to working with the windows console and we saw the random class and the random class has methods as well we only used one of them but it has a method called next which allows us to generate the next random number that the class can generate so the methods are organized into the classes based on their relationship or their need or kind of organize that way so that you can easily find what you're looking for now truth be told I totally oversimplified the explanation about classes because I really wanted you to gain some confidence in yourself and your ability to write visual basic code before we introduce classes it's a little higher conceptual it's there's nothing hard about classes per se it's just that classes introduced the idea of object-oriented programming and sometimes new developers find object-oriented programming ideas a little bit challenging at least at first now not to scare you away but it took me a little time to kind of wrap my brain around object-oriented programming took me probably longer than most people just because I was always looking for something harder making it more difficult than it really was the fact of the matter is that on one in one sense it's very simple and then on another in another sense you spend the rest of your life trying to master it okay so not to scare you off but it it'll be pretty simple I think once we get some basic explanations under our belt the code that you write in methods are ultimately defining the classes of your application so every method that you utilize from the .NET Framework class library is just a class and that's why it's part of the class library that's why they named it the class library and the classes are all around you you've been using them up to this point pretty much for every little application that we've written and so you're really an old pro at it I'm merely going to fill in some of the details to what you already know in this lesson in the next few lessons and kind of round out your knowledge and then maybe someday whenever you sit down to build a real application a new application you'll start to see the value of classes and maybe you'll even start like an experienced software developer who might organize their methods into the various classes to help in a number of different ways to help organize their thinking to make their code more maintainable and so on but at this early point in your software development experience I just want you to be able to utilize the .NET Framework class library efficiently so I want you to understand the nature of classes and how to create an instance of a class create an object how to utilize properties and methods of a class and so on so the truth of the matter is that I couldn't possibly cover everything there is to cover about object-oriented programming and specifically about classes in this course there's just not enough time because it's a vast topic I have an entire course devoted to it on devu.com and then you can go on from there and read books and books and books about object-oriented programming I just wanted to present enough information to you to help you get comfortable with the basics of how to use the existing .NET Framework class library from Microsoft use those library classes in your applications and so in order to illustrate how Microsoft put together the .NET Framework class library we're going to build our own custom classes and to show you how they built the class library alright so what I want to do is start talking about the need for classes and talk about working with related properties so suppose that I want to create an application that keeps track of data about cars because I own maybe a company that deals with a car lot I'm selling cars on my car lot and I want to keep track of all the cars on my car lot alright so I want to keep an inventory of all the cars that are currently in my possession as the owner of the car lot what I could do probably to begin with here is to create a series of variables about a given car and I just maybe want to keep track of three properties of each car so I have one car on my car lot I'm going to say car number one and I want to store its make as a string and I want to store its model as a string and then I also want to store whoops this should be car one and then car one year as integer and so then maybe I come along and I need to add a second car I've got two cars on my car lot now I might need to go car to make a string dim car to model as string and then dim car to year as integer and then if I get a third car well here we got to do that all over again car three make as string dim car three model as string dim car three year as integer and then I decide well you know what I really need to do is not only keep track of the make model and year but I need to also keep track of the color for each of the car so whoo I do car one color as string all right anything got to go down here add car two you can see that this isn't a very efficient way to keep up with all the cars on my car lot okay first of all I'm kind of relying on just a naming convention just like I did with a raise remember when we talked about that relying on a car on a naming convention to keep everything kind of bundled together and there's no way to enforce that there's no way to enforce that what I'm saving car three color isn't related to car one why because these are just loosely related together and the only way that they're related is in my own mind and the only reason they're related in my mind is because of what I've named them so this isn't a very good technique for keeping related attributes of a single entity a single object a car in this case into one logical container when I think about it arrays really aren't the right way to go about this either because you can only store a single data type inside of an array so and furthermore how would I keep track of you know if we were to say car one and say it had four attributes how would I be able to say that attribute number two was always the model regardless of car one car two car three so that arrays aren't really the right solution for this either what we would probably want to do instead is actually to create a new class of information a classification a type and that type would be a car an automobile and a car would have different properties and then whenever we went to represent a new car on our car lot we could just say car one is actually type of car and since it's a type of car we know that it has a make model year color and so on so here's what we want to do we want to create a new class and inside that class we're going to define the properties the attributes of a car that are meaningful in our application now there's a lot of attributes about a car we could say sticker price we could say the number of of miles that it has on it you know but those things may not be relevant to the application we're building so we really just want to model those properties that are interesting to us inside of our application so what I want to do is add a new file to my project we haven't done this yet and there's a couple of different ways to go about this the easiest way in my opinion is just go to the project menu and select add and one of the options is to add a class and it will pop open a new dialogue called the add new item dialogue it'll already pre-select class we can we can add a lot of different types of things but class is what we want let's name it car dot vb and click the add button ok so now we have you can see here a public class car I'm not going to talk about the word public just yet that'll come in handy here we talk about accessibility modifiers a little bit later but for right now all I'm really interested in doing is defining what a car is inside of my application and again car lot I just want to keep track of the make the model the year and the color so what I'm going to do is create four properties of a car that are general and they're applicable to every car that's ever been created on the face of the earth okay so it's it's a generalization of the idea of a car so in this case public and we'll give it to name property make as a string public property model as string public property year as integer and let me fix that E in year and then finally public property color as integer whoops as a string great let me change the R I know that it's not case sensitive but I like making my code read correctly great so now I've got a car class and it allows me then to create new instances of cars each car will be defined or differentiated as a make a model a year and color now I can create a new bucket in the computer's memory sufficiently large enough to hold a new car object it's just like an integer it's just like a string it's just like a date it's just like the console class it's just like the random class it's just like every other class or data type that we've worked with except we created this it's a custom data type it's a custom class and we get to define how that class actually works by creating its properties and its methods so now let's suppose that my aim is to use that car definition that car class definition to create instances of the car class that represent individual cars on my car lot so I want to create a bucket in the computer's memory an instance of the car class that will hold each of the cars so I might have two or three different cars on my car lot I want a variable of type car that will hold all the information about one specific car on my car lot alright so let's go ahead and talk then about creating a new instance of of a class versus the class definition itself the class is the blueprint alright but what we want is an instance or we want that blueprint to turn into an actual representation of a specific car so what we need to do is take this car class and say I need a new bucket based on this car class definition and then I'll fill in the details about it so I need to take the pattern, take the blueprint and then instantiate it create an instance of it realize that from the theory of what a car is to an actual instance of a real car like my car sitting in my driveway right now so you know in the real world you can use the same blueprint to create many different houses right the blueprint is just on a sheet of paper but the house actually is at a physical address and you know some neighborhoods they call them cookie cutter houses because they all look the same right well you could use the same pattern to create the same shirt or pair of jeans over and over again or the same recipe to create the same cake or the same casserole and get the same results each time that's the purpose of the pattern that's the purpose of the blueprint so each time you want to build a new house it'll be at a different address a different street address each time you follow the pattern you'll create a different shirt you might use different fabric it might be a slightly different size but the pattern will give you the overall shape of that given shirt or every time that you create a new shirt you can sell it to a different customer there's an instance of it that you create from the pattern each time you follow a recipe you're going to create a different meal available and that can be eaten by a different person okay so the same is true with classes each time you create a new instance of a class you have a new object that's distinct and separate from the other instances of that class alright that lives on its own in other words is what I'm trying to say so think of the class as a cookie cutter you can't eat the cookie cutter right you can eat the cookies that you make from the cookie cutter so when you instantiate a class you create a cookie or an instance based on the shape of the cookie cutter or the class okay so I'm going into a lot of conceptual explanations of the difference between a class and using the class or the cookie cutter and using the cookie cutter or the pattern and using the pattern the difference between the blueprint and actually using the blueprint to create a new house or whatever okay so hopefully I'm making that distinction extremely clear once you get that clear in your mind things will come so much easier alright and so what we want to do is create a new instance of a car let's go ahead over to our module of vbn or sub main and create a new car so dim my car as car alright now at this point all I've done is created a a label that I can attach and say this is of type car now in order to actually create the bucket in the computer's memory I have to use a different keyword my car equals new car at this point the new keywords is like a factory it takes the blueprint and it creates an instance of the object in this case a car and it essentially creates that bucket in the computer's memory and at that point then we've created the item in memory and we've got the name or the label for that bucket my car and so now we're ready to work with my car and we can do something like this my car dot make equals Toyota my car dot model equals forerunner my car dot year equals I think it's 2010 and then my car dot color equals white ok so now that I have a bucket in the computer's memory labeled my car I can set the properties or the attributes of my car and describe my car using the various properties that have been predefined for a variable of type car so here we've got a class but the class is called car an instance of my car or of the car is called an object so here's the class and here's the object here we create a new instance of the car class in the computer's memory we instantiate it, we bring it to life based on the fact that we know it's definition the cookie cutter here, the blueprint and now that it's in memory and we have a connection to it by its label my car we can start working with it and we can create a second car dim my other car in fact we can do this all kind of in one shot equals new car, like so so we've done these two lines of code except in one line of code actually there's an easier way to do it with still less code, my other car as new car alright actually so that's probably the shortened form that you'll find me using most often because I can do it all in the fewest number of characters possible and so then my other car can be a make equals let's go Honda my other car is the model let's call it a chord my other car dot year is 2012 my other car my other car dot color equals black now that I have two cars I can console dot right line and I can print out the specific attributes of each car so let's just say let's just do two things here and let's take my car dot make and then my car dot year and print them out like so and I can do the same thing here with my other car I just copied and pasted that line and I'm going to change what we're printing out and here you can see I have Toyota 2010 Honda 2012 alright and I think the most important thing to realize about this is that I can set properties using the assignment operator but I also can get the properties just like I can't any other variable by merely referencing it using the name of the object in this case my car it's the instantiated version of the class so it's an object so that's the difference a class versus an object classes the blueprint the object is the instantiated version of it that has it's different from every other instance because it's a different bucket in the computer's memory so hopefully I've belabored that enough so that you understand it so you can see that we create many instances of a single class by giving each instance of the class a different identifier a different name and so it's distinct from every other item based on the same class in the computer's memory now I've merely hard coded the values here in this example typically what you would do is retrieve those values maybe from an end user letting them type in the values we might pull it from a database or from a file and instantiate an object and then copy the attributes from the file into the object and then work with it and then save it back so again here we're taking baby steps but that's how we would get information in we probably wouldn't always just hard code them the way that we've done here it would make for a very inflexible application what we really want to do is either retrieve data from an end user or retrieve data from some file source or from some online source now I want you to notice also that IntelliSense was smart enough to show me all of the attributes that we've created right as well as a few extras like equals get hash code and get type that's because every object or every class is actually based on a kind of a grandfather that inherits from system.object in the .NET Framework class library so even though we're creating a custom class it's really borrowing from other the definition of what a class really is that's defined in the .NET Framework class library so we get some functionality for free like the two string method the get type to get hash that's where all these other things come from but they don't really have any functionality just yet by default we could over override their default implementations and do something interesting with them but we won't do that in this video okay so I just wanted to point that out now the next question is how long does this instance of the car or the other car stay around well as long as we're using my car or my other car in our application then it will continue to stay alive but when we stop using it it will die and we'll talk about the scope of variables but specifically about objects as well as object lifetime in an upcoming lesson because it's a very important concept but essentially when we get to the end of our sub what will happen is those two cars will be removed from the computer's memory thrown in the trash and that memory is now freed up for other applications that we have on our computer so also what I wanted to point out here is that we used a shortened version of defining a property there's actually a longer version that allows us to add more functionality inside of our properties so this version is called an auto implemented property we're able to create a long version of the property just by typing in the word property or prop have it highlighted in the IntelliSense and then hitting tab tab and here you can see a fully implemented property and I don't want to really get into all of it but you can see that it does have these two little sections here the get and the set so that's the two operations that you can perform on a property and retrieve its current value or you can set its current value by passing it a new value using the equal sign, the assignment operator this full blown version of a property allows me to step in and write custom code, custom logic so that when anybody tries to access and retrieve the value of an attribute or change the value of an attribute and say wait a second, before we give away the value that's inside of our new property let's make sure that they have the appropriate level of access because I may not want to give away some super secret information if the person who's currently logged into my application is not of a certain level inside of our organization so this is where we could do some gating and stop people from accessing information at this property level we could also then do some validation and say you know a car can't be in 2030 that year hasn't even come yet so we could validate the set and only allow certain values to be set so if we try to set for example the year to 2030 we could throw an error and say no no no no you can't do that so that's the purpose of a full blown property definition but we're not going to use that not at least in this video I just wanted you to be aware of the fact that this is a shorthand version of creating a property this version of the property allows us to get it or set it to any value that you could typically set into a string even if it doesn't make a logical sense inside of our application ok now since we defined a data type just like string or integer we can use those as input parameters to function so what if I were to create a little helper method here and to determine the value of each of our cars what we could do is create a new function so I'm going to call this determine market value and then I'm going to pass it in by val my car as car and I'm going to return back a money value whenever you're dealing with monies decimals the decimal data type so when you're dealing with money you want to work with the decimal data type it's like integer except it allows you to have values after the decimal place and so in this case what I could do is do some super secret formula here to figure out what the value of any given car is I could even go and search online to find the value of the car but we're not going to do that instead I'm just going to hard code and return whoops I'm going to return the value of 100 for the car so we're going to pass in my car we're going to do some evaluation on it we could like retrieve its properties here my car dot make so maybe we'll do that in a future example let's do it pass it to something online get the value and then return it back so here if I were to let's comment this out and let's just do this my car let's go determine market value and we'll pass in my car alright then we'll see what the current value of my car is alright you can see that let's go ahead and format it like currency right so use the colon C formatter now we can see the value of my car is actually $100 alright so the point here is that we can use now this data type car that we defined just like any other data type integer string date whatever and we can use it as input or as return values from functions that we create but there's maybe even better way to do this let's talk about creating methods inside of our class definition so I said before that a class is really just a container for your methods but I haven't shown you any methods I only been talking about the properties but we can also create methods inside of our classes so let's do that instead of putting that determined market value here as a function that we pass the car into we should be able to just create it here inside the class it will have access to all the data that it needs in order to make the determination so we shouldn't have to pass in anything we'll just say let's go just public function market value as decimal so we're not passing any values because we're going to be able to access the attributes of this car so let's go ahead and we could do something like first secret formula right here we could actually look online for the value and then return it but what I'm going to do is something a little bit different we'll just write some really crazy logic here to determine the car's value so I'm going to create a car value as decimal this is ultimately what I'm trying to determine I'm just going to create a variable that will hold it and now what I want to do is find out the current year of the car now I could just type year like that and um it would work but what I would really prefer to do is to say not just year because year where did this come from is this some it might be difficult to remember the properties of a car if I were to look at this in the future and say I don't know I'm looking at this function it's not clear to me where this year word came from so what I can say is for this instance of car this current instance give me the year attribute now I prefer doing that clearly visual studio would say well you could probably simplify this and it gives me the little the little light bulb under it and it says just remove the me qualification alright so we'll just go ahead and leave it off but remember if you want to reference this specific instance of the class and retrieve its attributes the year it's make its model then you can use the me dot but we'll get rid of it so anyway if the year is greater than 1990 than the car value we'll just hard code it to $10,000 otherwise if it's older than 1990 then we'll make the car value just $2,000 and then we'll return the car's value like so okay and now let's go ahead and rework this line of code and we'll just go console dot write line in fact let me just borrow almost everything inside of here except it will change how we make a call and in this case we're just going to go my car dot determine my car dot market value okay I thought it was called something else and so now I'm going to be executing a method so I have to use the method invocation operator on it it's not a property properties I don't have to use the method invocation operator even if I try to I'll probably get an error alright it lets me do it again that's only because visual basic is very forgiving and I can probably leave it off here too and it will still work but again I want you to be purposeful and think about the usage of a property versus a function or rather a method let's run the application and you can see now that our Toyota is worth $10,000 alright so what do you make of all this well in this lesson we used a very concrete example the example of a car and a car is easy for all of us to conceptualize it's tangible there's a real world equivalent we can think of what a car really represents in the real world we can model it fairly easily because we know the attributes of a car just like we know the attributes of a pad of paper or whatever the case might be now you're going to be building applications especially in this series of lessons and typically you're not going to be responsible for creating your own custom classes I think your main exposure to classes will be what we've experienced so far which is those classes again which were created by Microsoft and available in the dotnet framework class library in most of those cases the classes that have been defined the dotnet framework class library do not have real world equivalents like something tangible like a pad of paper or like a car that we can sit inside of or touch in other words the classes inside of the dotnet framework class library are more conceptual in nature for example I might work with a class that represents a connection to the internet or I might work with a class that represents a stream of data as it's being streamed into me from some other source flowing from one place to the other like a pipeline and we already saw that there were objects like a span of time it's difficult to put your hands on time right but there are objects in the dotnet framework class library that represent a span of time between two dates okay so very conceptual in nature in these cases we're not working with something tangible that we can touch and we can feel but we're working with something again a construct of our own minds and that is that we can't touch inside of the computer now as you mature as a software developer you might want to invest more time in learning how to create your own library of classes that interact with each other in some meaningful way as a means of breaking down real world problems into conceptual problems and turning them into code by abstracting their features their most identifiable features that are important for your application to a series of classes and that process that you go through to turn something in the real world into something conceptual is called object-oriented analysis and design and that's not something that we're going to cover in this series of lessons you can spend years learning how to do it properly but I do have some courses on devvue.com that will help you learn that if that's something you're interested in I spend a lot of time actually thinking and talking about object-oriented programming there to recap a class is a data type just like any of the data types that we've learned about up to now it's similar to those basic data types like integer and string and it's also similar to those complex data types like console and random that we've used up to this point in time and you can define a custom class with properties as we saw here and methods like we saw here and we can actually then utilize them by creating new instances of a given class and then using the member access operator to either set or get the properties or to call the methods that have been defined on our classes and inside of those methods we can access the various attributes of this instance of this given class and create business logic around it to, in this case for example, determine the value of the car alright so don't worry I've got a lot more to say about classes if you don't understand everything there is to know about classes just yet why you need them that's okay don't fret about it just make sure that you understand the process that we went through to create a new class how we created properties of the class by using the syntax public property then the name of the property and then as whatever data type that we want to make that property understand the purpose of when we typed in prop tab tab and we were able to create the full version of a property and we see here the get versus the set for that property how we created a method we could have used a sub we used a function because we wanted to return a value but again how we created a method inside of a class and then we were able to access that either property or method by using again the member access operator for a given instance of our class and if you understand just that much then you're doing all the right things up to this point we'll fill in more details in the coming lessons so if this didn't make sense there's nothing wrong with watching this video a second or third time or even watching other videos that might help you better understand classes but do this stick with this don't drop it right here even though we're at a conceptual hurdle for you a lot of people have a challenge with this and don't make it harder than it really is at least not at this point so you're doing great, let's continue on the next lesson we'll see there, thanks Hi, I'm Bob Taber with Developer University for more of my training videos for beginners please visit me at devu.com in this lesson we're going to continue on with classes and object oriented programming we're going to talk about the lifetime of object references and how .NET manages the memory that your objects use secondly we're going to talk about constructors which are special little methods that run at the moment you create a new instance of a class and we'll talk about why you even want to use constructors and then finally we're going to talk about shared methods and properties shared as a keyword in other programming languages it uses the term static meaning that you can use that particular method or property without creating a new instance of an object first so that would explain the console window and it's different from how it's different from the random object that we used in previous lessons so let's go and get started and this is one of those cases where you probably want to use the code that I'll supply you can find it wherever you're currently watching this video or wherever you originally downloaded it from there is a folder called before and you should be able to find in the before folder an object lifetime project and you want to copy that somewhere on your hard drive I'm going to put it where I put all my projects here in the project subfolder visual studio in my documents directory so now let's double click the solution file to open up visual studio and you'll see that I've already created pretty much just copied the code that we worked with previously here to create a car class with the make model year in color and then you'll notice also in the module vb in the sub main we're creating a new instance of the car setting its attributes and well there's a little bit of something that will come to a little bit later let me go ahead and delete that for now so anyway what I want to do is actually focus on this line of code line number 5 what's actually going on here well the dotnet framework run time when it encounters this line of code will have to go and create a spot in the computer's memory large enough to hold a new instance of the car class so that's that bucket analogy we've been using it's going to create a new bucket in the computer's memory large enough to hold a new instance of this custom class that we created so the computer's memory has addresses in it similar to the address where you currently live in your home or apartment so admittedly the addresses in a computer's memory looks a lot different than the address you might live at 123 east main street you know some city you know some country and then some postal code it actually uses hexadecimal values as addresses but their addresses their known addresses nonetheless and that's how the dotnet framework run time knows where it put your buckets it keeps track of the addresses and it keeps track of the address and the little friendly label that you give it whenever you create a new instance of a given object in this case my car is at this address it uses that address looks up into that address in the computer's memory finds the bucket grabs the values out unless you work with them so the dotnet framework's first job is to find an empty address where nothing else is being stored right now whenever you create a new instance of of an object and so that address has to be large enough in size to store a instance of our given class so it creates the object and then it grabs the address of that object and copies that address down and so it always knows where to find that object in memory that we've labeled my car in this particular situation so that you can always get back to that object in memory and so you can store that reference in your variable but really all you're doing is storing an address in that variable and behind the scenes the dotnet framework runtime knows what it means it goes and finds the actual bucket at that location so my car in this case is simply holding an address or what we would call a reference an object reference a reference to the instance of the car class in the computer's memory so whenever you need to work with that instance of the car class or my car identifier we can set and get attributes we can call functions and the dotnet framework takes care of the rest for us awesome so it gives you this illusion that you're actually working with with the object itself but in reality you're just holding onto a reference to an address in the computer's memory and then the dotnet framework runtime takes care of all the rest and makes it hidden from you so an analogy that helps me understand references to objects is kind of maybe to extend the analogy of a bucket a handle on the bucket we've used the bucket analogy several times up to now so whenever you store an object in memory dotnet gives you the developer basically a handle that allows you to get back to that bucket so you can hold on to that bucket so what happens if you let go of the handle well you'll no longer be able to get to that bucket the bucket will no longer be accessible why will it no longer be accessible well one of the missions of the dotnet framework runtime is to keep the memory region clear and get rid of stuff it no longer needs and so the dotnet framework runtime goes through and cleans up memory every once in a while and it does that by counting references or counting how many handles you're actually holding on to so if we're no longer holding on to a reference or handle to that particular object in the computer's memory to the car class then it's going to remove that instance of the car class from the computer's memory because it thinks we don't need it anymore so it frees up that space in memory so that other programs can actually use that for their own needs so this process of cleanup is called garbage collection and there's a lot you can learn about garbage collection and how it works behind the scenes not all that important for the moment but what I want to do is actually run a quick experiment and I want to actually use that line of code that I accidentally left in a moment ago so my other car as car equals my car so here we go at this point now we did not create a new car in the computer's memory all we did was say I want to create another handle and I want to attach that handle to the same handle that my car is pointed to so we essentially just copied the reference from my car to my other car now we have two handles attached to the bucket in the computer's memory at this point and to prove this here let me just show you how I can prove this so console.rightline and we'll go myothercar.make that should be sufficient to prove this to you then what I'm going to do is go myothercar and I'm going to set the color from whatever it is to black and then what we'll do is console.rightline we'll go mycar .color just to see what color it is is it still white or is it something else so this should prove that we're now dealing with two handles to the same objects in the computer's memory so let's also write a console.readline real quick here and let's run the application and you can see the first thing we get printed out is Toyota so that was what we got from myothercar even though we never set explicitly the make attribute of myothercar because it's referencing my car it's able to grab out Toyota and then next the we're looking at mycar we set its color to white but since myothercar is pointed at the same object in memory we can set it to black thus affecting the color of mycar and setting its color to black as well alright so now you have two references to the same object in the computer's memory and I think the important thing here is that you can create a variable that can hold a reference but you don't have to create a new reference necessarily just copy the reference from another object alright so another analogy that kind of helps me because you don't think about multiple handles on a bucket maybe you can think of it like strings on a balloon after you cut the last string on a balloon what happens if it's filled with helium it's going to float off into outer space and you never hear from it or see it again alright so the same is true whenever you're working with references here in your application when the references go out of scope in other words whenever the current threat of execution of our application exits through the end sub and it leaves the code block where the variable and the object of the object the variable holding the reference to the objects in memory are actually defined then we actually lose those references we're essentially cutting the strings off because we're exiting out of the application or at least out of the scope of this method and those variables are no longer accessible the .NET Framework comes through and says oh hey car class it looks like nobody's looking at you anymore time for you to go away and so it takes it and removes it out of memory alright so that is known as reference counting to see how many references are still attached to a given object the .NET Framework will count the references at the count if the references go to zero the count goes to zero then it will remove that object from memory so at some indeterminate time in the future after we exit out of the execution of our application then the .NET runtime with garbage collection feature will come around and will count references it will remove the objects in memory freeing them up for other applications now what if we wanted to explicitly remove our references in other words what if we explicitly wanted to cut the strings to the balloon before we go out of scope because we hope to use that particular variable again and we're working with a lot of objects and we want to free up the memory we can actually do something like this so here I'm going to set my other car equal to nothing alright so when we set this equal to nothing we're saying hey instead of pointing at something point at nothing so now if we were to try to reference and go console that right line and go my other car dot and we attempt to get the color out let's see what happens when we run the application we can get an exception that there's a no reference exception there's a reference but it's no in other words we don't know what it's pointing to it's pointing at nothing so we can't access an object that is pointing to nothing in memory let's go ahead and stop that now if we were to set both of these to nothing so my car equals nothing we would actually probably kill off this line of code as well and then at some future point in time some indeterminate point in time but the object would actually be removed but we doesn't really matter from a practical purpose because we don't have any access to that object in memory anymore so in some situations this indeterminate amount of time because the garbage collector will run whenever it feels like running there are some rules and memory pressure that force it into action and otherwise it will just be dormant but if we need to be specific about removing objects and we want to be explicit about removing objects from memory because we have a very memory intensive application we can do something called a deterministic finalization approach that allows us to say hey stop everything you're doing at framework runtime and remove it now and we might want to do that in situations where we're holding on some to some connection maybe to a network resource to a database to a file and we want to sever that and make sure that at the moment that we say we want it to be severed we want it to be actually severed so that it frees up that resource so something else can actually use it so that might be a scenario where we would want to be very specific about it removing that object from the computer's memory but otherwise we can just let the dotnet framework do it on its own and not really worry about it that's a little bit more of an advanced concept we're not going to cover that in depth in this series of courses however if you were to search for the words deterministic finalization online you'll find some articles about it out on MSDN maybe even some videos alright so the next thing that I want to do is focus on the little subtle usage of the opening and closing parentheses because hopefully there's something about that that should jump out at you and that little something is the fact that we're actually using the method invocation operator here whenever we create a new instance of a class so whether you realize it or not whenever we create a new instance of a class like the car class we're actually calling a method called a constructor and it allows you the developer the option to write some code at the moment that a new instance of our class is instantiated that moment when that new instance of the class has been created in memory we can write code at that point to do things like for example put the object itself into a valid state just like we would any other initialization that we've used for other variables or even the array as we learned earlier so this means that we can use our the special constructor method to construct or initialize the values of properties so that our objects are ready to be used on the very next line of code you may not always be able to do it that way but it's definitely an option to use so I want to create a quick example here of why you might create a constructor and that'll allow us to set the properties of the car at the moment whenever we create a new instance of the car so to create a constructor you use the public sub and then the new keyword represents a constructor so here I'm going to do something like maybe I would load this from a configuration file to populate the make the model you're in the color I might actually load it from a database or maybe grab it from online somehow but in this case what I'm going to do is to actually hard code the make property so that by default all new instances of the car class will automatically be or have its make property populated with a real value so here what we'll do is just say make equals and then we'll say Nissan so now whenever we create a new car what we can do right away is console.rightline and then look at mycar.model or is it make sorry and you can see that initially by default the car is in a valid state setting its property to Nissan of course then we cover that up by setting it equal to Toyota and print it out a little bit later but at least you get the idea of how you can use it now admittedly this doesn't make a whole lot of sense right here I'm just showing you the technique that you would use not really the rationale but let me show you an overloaded version of a constructor so like you created an overloaded method in one of the previous lessons when we talked about methods and you did that by creating different method signatures you can do the same thing with constructors as well the method signature you'll recall is the number and the data type of the input parameters so we can create a second public sub new and as long as we change the method signature so at least in this case add one input parameter then we'll have a different version of our input parameter will be two different ways that an object can be created so let's do this by val and then I'm going to use a underscore now I'll just call this the make value string by val model value string by val a year value as integer and then by val color value as string ok and then here what we would do is just do a mapping from make equal to make value oops model equal model value year equals year value and then color equals color value alright so now whenever we create a new instance of car and let's just do that here for example in fact let me just comment out everything here so far and we'll essentially do all of that in one line of code so dim my car as new car but notice now I have two versions of my constructor the first version will accept no input parameters but the second will accept four input parameters to make the model the year and the color alright so here we go let's go toyota forerunner 2010 and white alright so we're able to now run our application in fact yeah let's go ahead and run it and you can see that we still get toyota printed out why is that well because we were able to do use an overloaded constructor to pass in all of the values we wanted to populate at the time of instantiation instead of doing it in subsequent lines of code alright just to kind of reinforce the overloaded nature of it we can't create another overloaded version without any input parameters why because there will be multiple definitions with identical signatures alright but I do want to say this if we were to remove this version that accepts no input parameters what happens then when we go back to this line of code well whether you realize it or not there is a default constructor now in this case because we have at least one constructor defined here comment that out we get a complaint but once I get rid of that notice that we're able to call the default constructor and it doesn't really do anything but if you were to look at the code that's generated the car class will have an empty method called new and it will call that nothing happens but just know that behind the scenes there's a default constructor that's always created for your classes so you can always use the method invocation operator after the creation of the instantiation of a new class and you can know that at least it will work it won't throw an exception however once you declare a single version of a constructor then from that point on you won't be able to use it because the default constructor will be covered up by your new constructor alright and furthermore even if you were to create this version like we saw earlier it will cover up the default constructor as well alright finally I want to talk about another keyword called shared and what you can do with the shared keyword is to create methods especially methods but also properties that do not require you to create an instance of the class in order to use them so many times classes that we're going to work with related to building .NET applications they don't require that you create a new instance of them first in order to start using their methods and a good example of that is the console class we didn't have to create an instance of console we just started using the methods of the console class like write line, read line, clear and others so another example when we were working with arrays you remember I used the array.reverse method we didn't have to create an instance of the array class we just started using the array.reverse method you typically would use this whenever you need methods but you don't really need to keep the state of an object you just want to collect together a bunch of utility methods that do something in your system but they don't rely on a specific instance of a class in order to operate write line, read line, clear they're all available by just referencing the class name console because when Microsoft created those methods on the console class they marked them with the shared keyword if they were writing it in visual basic alright so you can create your own shared methods as well and so our objective here at the outset is really just to utilize the .NET Framework class library and understand the difference between a shared versus an instance class so there's instance methods and their shared methods there are instance properties and shared properties for the most part up to this point in the car class we've only used instance methods and instance properties but what I want to do is create another class and I'm going to call this public class car lot and here what I want to do is create an add to inventory method so public sub add to inventory and what we'll do is go by val new car as car and then I'm not going to implement the body of this because we really don't have anything at this point that would help us with this but the body of the method goes here I might save this instance of car in an array or better yet in a collection which we'll learn about later but the focus here will be just on the fact that we can mark this with the shared keyword and now notice in our module 1.vb what I can do here is go car lot dot add to inventory I didn't have to create an instance of car lot because the add to inventory method is shared across all instances of car lot it doesn't depend on an instance it's shared so in this case I would just pass in my car and then it would perform whatever operations on it you might also notice that I was able to define a second class inside the same file I typically would want to move those out into their own files but for such a small version of a class I can just create it right here inside of another file now why you might want to use the shared keyword that's a little bit more complicated it might require a longer discussion of design patterns and coding heuristics again I just want you to know that it's available and more importantly I want you to know that you're going to encounter shared methods as opposed to instance methods like we created you know previously and then also with our constructor you're going to encounter them in the .NET framework class library and then why you actually use this inside of your own application might not be obvious now but you can pick that up a little bit later as you're designing your own code libraries that other developers on your team might utilize so it's not really important why you use them just yet just know that they're in use in the .NET framework class library and there's a reason and we're not going to talk about that reason in this series okay in this recap what we talked about in this lesson we talked about the lifetime of an object including what happens when there are no more references to an object in memory and how the .NET framework runtime employs garbage collection to remove objects at some point during the execution of the application we looked at constructors and talked about when they're actually invoked how to create an overloaded version of a constructor we talked about the default constructor and why it's not available if you create any other version of a constructor and then finally we also looked at we looked at the shared keyword essentially to create utility methods inside of classes so that we don't have to create an instance of the class in order to utilize that particular that particular shared method and we've seen instances of this all over the place whenever we were working with the console class the date class and so on alright and you'll continue to see those in the .NET framework class library that's the important part alright so I if you don't completely understand the notion of shared or any of these other ideas just I would say for now just go ahead and continue on just understand basically conceptually what it is to learn a lot about some of these other concepts as we continue to move forward ok so let's continue on the next lesson if you got this far and you're with me you're doing great we'll see in the next lesson thanks Hi I'm Bob Tabor with developer university for more of my training videos for beginners please visit me at devu.com now we haven't spent much time talking about the scope variables up to this point we did see how scope would impact the lifetime of an object in the previous lesson talking about as object references go out of scope so as the current execution flow for the application extends beyond the end of the sub what happens to our objects in memory well they get garbage collected right but but I want to take some time and talk about scope and I want to make sure that you understand local scope and scope at a module and class level and so that you can more completely understand the topic and then we'll use that as a launching board to get into visibility and so there are visibility modifiers like the public keyword there's also a private keyword there's several others in relation to writing classes and then methods and properties inside of those classes and how those keywords those accessibility modifiers change the visibility of classes in their members alright so before we jump into accessibility modifiers like I said I want to talk about variable scope so let me start by saying that whenever you declare a variable inside of a block of code that variable is really only alive and accessible for the life of that block of code meaning that whenever that block of code has finished executing the variable defined inside of that block of code is no longer accessible it's values are disposed of by the dotnet framework runtime so I want to see how that applies to common code blocks that we've been working with up to this point and kind of extend out from there and to begin what I want to do is go to the before folder for this for this for this lesson and so wherever you currently are watching this video or where you originally downloaded it from there should be a folder of code we're going to look at the before folder to grab out our understanding scope project and I'm going to copy it personally I'm going to copy into my projects directory here so that I can find it with all my other projects I'm going to double click the solution file inside of that project folder and you'll see that we have just a simple car class and then also our module one dot with an empty sub name and so what I want to do is create a small project to understand scope a little bit better and I want to test how variables that are defined inside of a code block work as we move outside of those code blocks and so it's going to be a very simple example at first and we'll just keep building on it but any variable whether it's a simple type like strings and integers or something more complex or custom like the car class it still applies what we'll talk about here in this lesson with regards to scope and I just wanted to make you aware of that as we get started so to begin with inside of here let's start with a console dot read line and then above that I'm just going to create a four statement so for index equals one to ten in fact I'm going to change this from index just to the letter I to stay consistent with the rest of my code I'm planning on writing and while we're inside this code block the I that is declared here and initialize to the value of one and will be incremented as we go through the for loop we can access its value inside and we can see that quite obviously we can print out one through ten but what happens if I try to access that outside of the code block in which that I was defined well in that case we go here and print it out and run our application first of all we get a compilation error we get a little red squiggly I is not declared it might be inaccessible due to its protection level its protection level has nothing to do with it or its accessibility level the fact of the matter is that I is out of scope because it was declared inside of this code block it's not available outside of that code block alright so that's the lesson here that we want to take away so we're going to look at some other common common usages and show what you would have to do to make this work so let's go outside of this and do dim J as string equal to an empty string and then inside of our code block I'll just go J equals I dot two string like so and then can we actually view it here and so actually let me do this just to make sure we know what we're dealing with here so J equals and then let's do I is alright so that should be pretty clear let's go ahead and run the application now you can see that first of all I is one through ten and then because J was declared outside of our code block our for next loop we're able to access its value its current value which was set to the last value that I was set to which was ten and it's printed out here outside of our code block right so now let's take this one step further and what I want to do is define a variable outside of sub man we've never done this before when I create it like this it's called a field a private field so it's a variable that's accessible then to all of the methods that are inside this module alright so we'll use the private key word and I'll come back to that a little bit later private K a string and I'll even initialize it to just an empty string alright so here what we'll do inside of the loop is exactly what we did here I dot two string and I am pretty sure that we're going to be able to access it here as well but we'll just make sure by doing that now outside of this we'll call or we'll create a private sub helper method like so and then inside of this what I'm going to do is console dot right line and we're going to go K but we're going to do it from our helper method like that and then we'll print out the value of K and then finally what we'll do we're going to need to call that helper method here so again I can just call helper method by giving it its name and using the method invocation operator and now let's see if we're able to access the value of K inside of this method even though we created it outside of all of the methods and set its value inside of our sub main let's run the application alright and you can see the results here when we get near the bottom K is equal to 10 and then when we call the helper method its value is 10 so we're able to access or the scope of the variable defined here outside of or as a you could think of this as a relationship as a sibling relationship to sub main and private sub helper method it's accessible then to its siblings at the same level alright so let's continue on now let's go inside of this for loop and we'll go and create an if I equals 10 then we're going to dim L as string equals I dot 2 string and I'm going to do console dot write line L and then we'll print the value of L right there I think you should probably be able to figure this one out without me telling you but I'm going to go ahead and try this anyway what do you think will happen here well you can already see we get a red squiggly line L is not declared it we're trying to access it outside of its code block now what if we were to do this we know we can't access it there can we access it in this code block well no we still can't outside of the code block in which it was declared so it's no longer accessible so unfortunately those will not work so hopefully if you've had any confusion or misconceptions around variable scope this little exercise that we just went through will help clear some of that up and now what I want to do is to move on to a more important topic of accessibility modifiers why do we use public and private for example so in the methods that we've written in the previous lessons we always started with the word public in this case I started with the word private here for this little variable and for this method and public and private are called accessibility modifiers they're used to implement a tentative object-oriented programming called encapsulation so in a nutshell classes should be little black boxes like black boxes on an airliner which record every move that the airline that the airplane makes and so if it does crash then they can find out but the black box will has no other controls on it it'll just automatically record everything and so I think maybe even a better example might be those old style television sets you may have had one in your home I'm a little bit older so I remember the days when my parents or even my grandparents you'd have to get up from your seat and actually push a button or turn a knob in order to turn the television on or off or to turn the volume up or down or to change the channel there were no remote controls the kids were the remote controls back in those days so you had only just a couple of knobs and dials and buttons and there was maybe also a place on the back to attach an antenna and then maybe a plug and you plugged in the television set but everything else was enclosed and encapsulated inside of this magic box is all self-contained and as a kid I would be fascinated whenever my dad popped off the back of the television set to replace a tube to fix one of the tubes and he used to be able to do that sort of thing it still seems like magic to me that first of all my dad could even figure that out and then secondly all the complexity inside of the box once we opened up the back and took a look at it now all I know as a kid and even to this day all I know is the public interface the buttons, the knobs the electricity I can plug it in I can hook up the antenna but that's about it when it comes to television sets and frankly that's all you really need to know about a television set to use it as a consumer of the television I just need to know the simple controls and everything else is encased inside of plastic and it's all hidden from the end user and that's the way that it should be when you create your classes classes should be like little TV sets that are all all the complexity of it is closed off you just have a couple of public interfaces that consumers of the class can utilize but everything else is hidden in private so that somebody can't get in and just start making changes to it and potentially break the class right so the behind the scenes functionality especially for methods should be encapsulated behind interfaces like public methods and public properties now classes may have private properties or rather private fields like something like we created right here as well as private methods like the one that we created here in this module and to use as like helper methods and they're used to enable all the magic that goes on inside of of our class but the consumer of the class doesn't know anything about these private these private members these private properties and the private methods it has and it shouldn't have any knowledge of the underpinnings of the actual class itself all that the consuming class needs to know about is what's publicly exposed through public properties and methods right so in a nutshell private means that the method or the property but specifically the method can be called by any other method inside of the same class definition but it can't be called outside of the class definition so that's why I use the term private helper method because typically a helper method that term helper method is used to provide some additional functionality that outside of a given class it should not be able to see it but inside the class it just provides some additional features that can be utilized by the public methods alright so anyway a public method will then be accessible to outsiders that's what they'll call to get their work done private methods are going to be used by insiders those who are those methods that are also declared inside of of the same class so here what we'll do in our car class is actually create a private helper method in fact I'm going to call this private function helper method as string and I'm just going to do something really simple howdy partner alright so all it does is just return a string nothing fancy at all but let's pretend for a moment that that's all the business logic and complexity of our application and it's all hidden there inside of a private method now I may create a public method so public sub do something important like so and here I might just do console dot right line and then I'll call the helper method so just a real quick caution you probably don't want to ever put a console dot right line inside of a class there's a long reason why we have two concerns now that are mung together in the same code I don't want to go into depth but typically you would just want to return back a string and then let module one actually print that to to screen but anyway just felt like I needed to give you a little bit of a caveat there so let's go here after we've done all of this work in fact let me select it all and comment it all out and here we'll do is go dim my car as new car and then my car dot and notice that I can see the do something important but I can't see that little helper method method okay because it's private it's hidden from me so all I can know to do as the consumer of the of the car class is to call do something important behind the scenes I don't know what's going on now you know that's a little bit of a misnomer I as a programmer can look here and see oh I see what it's doing but we're look we're talking about this from the perspective of the code that's doing the calling it cannot see into the implementation of that class it shouldn't have any knowledge of what's going on and how it's actually doing its implementation so yes in a sense is because we're the programmer we can see what's going on inside but we don't want any other objects to go in there and fiddle around and make any changes or be able to call the helper method independent of the higher level public do something important method alright so you have to kind of use your imagination and work anthropomorphically in the code looking at it from the perspective of the sub main not from the eyes of the software developer alright so here let's run the application now you probably guess what you'll see just the words howdy partner actually the example is much less impressive than the concept itself so admittedly this is extremely mundane it's a simple example that's only real value is to illustrate the notion of encapsulation so we're hiding the implementation but exposing a public interface that's available to consuming code like sub main alright so the purpose of this lesson is to better understand the notion of scope because we said once variables especially those variables that are holding on to references to objects in our computer's memory after they go out of scope then those variables values are no longer accessible the dotnet runtime gets rid of them garbage collection then will remove any of the objects in memory that no longer have any references to them furthermore it's important to understand that there are parts of classes that you have access to and then there are parts of classes that you won't have access to so there are probably many more methods in the dotnet framework class library that you don't have access to because they're hidden behind the private accessibility modifier alright now if you ever do decide at some point in the future to build your own custom classes then you should strive to expose public methods and give a simple straightforward obvious usage for your class while keeping other helper methods that implement the logic of your class privately tucked away and not available to the prying eyes of the consuming code alright you want to give the code that's calling into your class a way to use the class properly through the methods that you designed and the input parameters and the return values so this removes ambiguity whenever you're very clear about the way to call into a class it makes its usage much more clear and obvious as well and so in the dotnet framework class library methods and properties are exposed using the keyword public they may also use private methods but we would never know about that right so they might use other types of accessibility as well we only talked about public and private there's one called protected I believe internal and some others but but they're used primarily whenever you're building a much richer inheritance relationship between classes when you're building this rich class hierarchy a library of functionality and most of us probably won't need to do that not for some time so you really don't need to know those just yet but again they're available it's just kind of beyond the scope of what we want to talk about here absolute beginner topics but some of those topics I cover on dev you especially for C sharp developers so just to recap in this lesson we talked about variable scope how variables have a lifetime based on the code block in which they're defined when the current code block is a part of the current scope of the execution at runtime the variable will be available but once you exit out of that code block and the flow of execution extends beyond the definition of the code block then those variables will no longer be available we also talked about accessibility modifiers like public and private and how that impacts the way that the dotnet framework class library is accessed that we can only get to the public methods and even perhaps someday when we build our own class libraries for our own applications we might want to use accessibility modifiers to control what the consumers of our classes actually can see and we want to hide any helper methods behind private the private keyword while exposing methods using the public keyword all right so we're doing great hanging there we're getting close to the end believe it or not a lot of the complexity we've already covered you're doing great we'll see in the next lesson thanks hi I'm Bob Taber with developer university for more my training videos for beginners please visit me at dev you dot com previously I said the dotnet framework class library is just a collection of classes that contain methods filled with functionality that you can use but you didn't have to worry about you didn't have to write them somebody at Microsoft has already created those for us in fact Microsoft has spent tens of thousands of man hours writing code and we get the benefit of it by all we have to do just know that the code exists call it by its name and utilize it inside our applications that's pretty cool so since the framework class library is so large its developers split it up into multiple files so if you had to load every single line of code in the framework class library every time that you wanted to run a simple application it would be excruciating slow and it would require a massive portion of your computer's memory so these library code files are called assemblies and all of the classes and methods are split up into different assemblies in fact when you create your own projects you are creating the basis for a dotnet assembly as well in fact there are two kinds of assemblies that we're talking about here the first kind is an executable assembly and the other kind is a library so just make sure that you understand of dotnet assemblies there is a executable assembly that has a dot exe file extension and then there is a library that only has code there's nothing really executable about it you can't just like start it by double clicking it it just contains functionality and those have a dot dll file extension again it's intended to be used by other code that is executable alright so every time that we run an application here inside a visual studio what happens is that in an executable dotnet assembly is generated for us inside of the bin directory for a project so if we were to take a look at let me just pop open our projects folder and we were just working with which one were we working with here just a moment ago I think we were working with understanding scope if we were to drill into the project folder we'd see a bin directory if you drill into the bin directory there will be a debug directory if you drill into there you'll see a number of files but the most important is the understanding scope .exe if we were to double click it then we would get the results from the previous video alright so there are some other files that are included here which help visual studios debugging experience connect to the executing assembly and so you can safely ignore these they're just regenerated every time that you want to create a new version of or rerun your application and debug mode but at any rate the dotnet framework has to already be installed on the computer where you're going to actually execute this program in order for it to work because it will load itself into the dotnet framework runtime and like we talked about near the very beginning of this course and it will live inside of that protective bubble now fortunately just about every copy of windows already has the dotnet framework installed in a in a location that's globally accessible by all dotnet applications so you don't have to distribute the dotnet framework with your applications whenever you want to distribute it to other people and so that location that that location is called the global assembly cache and fortunately that's not something we have to worry about it's just sitting on everybody's computer so back to my original point whenever you create your application you indicate which of those framework class library assembly files that you intend to use and you say well wait a second I don't remember ever declaring that I wanted to create an executable versus a library but actually you did whenever you were actually choosing to create a file new object you were selecting a console application and by default it is a it'll create an executable for you however we could and we will in the next lesson create a class library and that'll allow us to create a DLL file that only contains classes with methods inside of it that we can then use from other executable applications whether it be a console application or a windows or even a web application so let me just cancel that so at any rate let's go ahead and get started by creating a new application here called resolving references you can see that I've already taken the liberty of creating a new project called resolving references and what I want to do is talk about the references to the various classes that you'll need access to in order to get work done with classes defined in the dotnet framework class library how do we add a reference to those and utilize them we've already seen this one time whenever we were trying to use the string builder class remember I try to use dim my string builder as new string builder and at that point I got the red squiggly line and it said string builder is the type string builder is not and I said well I know that it exists in the dotnet framework but what I needed to do was to actually get a reference to the namespace where that particular that particular class lives now sometimes you're going to need to add a reference to an assembly that's not currently referenced by your project but as you're getting started that will not happen very often if we take a look at the solution explorer and you were to expand references you can see that there are all of these references to these DLL files even though they don't have the DLL file extension they are actually all saved in different DLL files and you can see here in the properties window near the bottom right hand corner that in this particular case the system dot link is actually saved in a file called system.xml.link.dll and same as with system data it's saved in a file called system.data.dll alright and so there's all a whole bunch of files here system.dll these are all references that were added for us by default whenever we created a new console window application because these are common namespaces and assemblies that contain stuff that we will typically need as software developers so that's one of the functions of the project templates as we create new projects so typically you're not going to need especially as you're getting started you're not going to need to add any additional references because you're not going to use a custom DLL although we'll do that in the very next lesson most of the functionality will be in one of these namespaces in one of these assemblies alright or maybe you need to create a reference to an assembly that's created by a third party maybe not you, maybe not Microsoft maybe some other company and again in the next lesson I'll demonstrate how we'll create a reference to an assembly that's not already referenced inside of our project but once a DLL is referenced in our project we might need to then find it by its name now again I said a little bit ago that there are the .NET framework class library is massive there are tens of thousands of classes defined in the full .NET framework class library across all of the assemblies and so in a few cases there were the same class name needed to be used and so when that happened the creators needed a way to tell each of those classes apart so they introduced the concept of a namespace so namespaces like I said earlier are like last names for your classes so for example my first name is Bob and you might try to say hey Bob likes coffee and somebody else might say which Bob are you talking about I know like a dozen Bobs and there's like a billion Bobs in the world and they say oh no no no you know Robert Theron Tabor they may not use that formal language but if you were to disambiguate me by my full name my middle and my last name you could probably uniquely identify me in the world I'm pretty sure I'm the only Robert Theron Tabor that middle name is pretty unique I know there's a lot of Bob Tapers out there but anyway this disambiguates me from every other Bob or every other Bob Tabor out there by using my full name so namespaces in the .NET framework class library disambiguate class name so now you could use the full name or you can just add an import statement in this case you can see that I have the name string builder but my program doesn't know where to find the string builder class now you can see there's this little quick actions light bulb that appears off to the left hand side or if I hover my mouse cursor over it I can then select to either import system.txt we did that last time remember how it added that to this import statement then at the very top of my file but let me comment that out that should give us an error message again and this time let me just use the full namespace and you're like well that's not really the full namespace that's right the full namespace is system.txt string builder alright but since system is assumed to be part of your part of the the namespaces that are imported by default you don't need to add it you can just go text but honestly if you're going to go to that extent I would recommend that you go ahead and use the full name to remove any un-clarity so those are two ways in which you can find the classes in the .NET framework class library that you already have references to that you're already referencing the assemblies that live in the global assembly cache on the user's computer alright so by the way a couple of things that you probably need to know about number one your project will automatically have a namespace and it will be the name of the project if you want to change the default namespace for your project what you'll need to do is select the project inside of the solution explorer you can right click and then select properties and you can see if we go down to the assembly name will be resolving references and the root namespace will be resolving references now we could change the root namespace but we should probably leave it by default so whenever we're calling into for example if we had some classes it will automatically know that those classes are in the same namespace as module one if not we could import that new namespace or we could add the full name of the class so resolving references dot car for example why is this important well typically whenever you want to build applications you're going to want to do something and you're not going to know how to do it so at that point you're probably going to open up a web browser and you're going to start doing some searches out on the internet so for example say I wanted to figure out how to write text from my application to a file to a text file on my computer so what I might do is do a search in Bing so search and I'm going to just refine this search and say I only want to search microsoft.com write to a text file and then visual basic alright and this will probably get me to a good article on how to write text to files in visual basic happens to be the top answer there and so now what I might want to do and they give me a couple of different examples here alright now looks to me like the this particular article is cheating a little bit it's using the my namespace and that's not really going to accomplish what I want for this for this video we're going to talk about the my namespace in the very next video and how the my namespace makes some things extremely simple we can find most of these types of functions just by using the my namespace it's special to visual basic but this isn't a good test of the functionality because frankly we're cheating a little bit here let's go back and instead let's search for something different we're still going to search microsoft.com but this time let's go visual basic retrieve html string and let's see how to retrieve data from a website using visual basic alright so I'm sure this is exactly what I'm looking for either but I happen to know if I were to do the searches for something called the web client I'd be able to find some examples in visual basic there we go let's see this example on MSDN and here I'm going to go to the VB version of this and see if it gives me any good examples down here near to the bottom on MSDN yeah and so here we have the VB version of our code and I can kind of look through and see how this will actually work and this seems to be like a pretty advanced example what if I look for this download string I happen to know that that's the method I'm looking for um and again we're looking at the VB version here and so yeah this is a little bit more like it this is what I want so here they give us the ability to um to put in an address and then grab the content from that that address I'm just going to copy these three lines of code Ctrl C and then I'm going to go over here and um I'm going to paste these in now yes here's what I wanted to demonstrate to you when you paste in code from the internet sometimes it's you're not going to have the references you're going to need to resolve the references now you'll see that this little light bulb will pop up sometimes and it will give you the import statement or it'll let it'll automatically type out for you the entire uh namespace for the given class if it recognizes it however what I'd recommend so you can keep your fingers on the keyboard at all times is to get the control period and this will open up that little dialogue and allow you to use the uh up and down arrows to choose which of these you want in this case I want to import system.net that's the namespace where the web client class is from and then uh in this case all we need to do is pass in I think just an address as a string so I'm going to type in my uh my website debu.com and um then it should be able to give us back all of the html from my website and print it off to the console window so let's see if that worked there we go alright it took a second but we got it and uh now we've got all of the html and I'm going to go ahead and hit enter and so you can see that we're able to copy code off the internet and resolve the references by hitting control period on the keyboard in order to bring up that little menu and eventually add a import statement for uh the namespace for the class that we want to use and then we can continue on alright so that's all I really wanted to illustrate is how to work with namespaces and how to resolve references to classes that are referenced that we have references to because they're part of assemblies that are referenced in our project but that we have not yet imported the namespace into our projects consciousness alright so um we're going to continue on and take a look at the my namespace in the next video and uh we'll continue on from there and we'll see how we can utilize the my namespace to do some pretty cool stuff without having to hunt and find uh all of the uh classes that we might typically need in order to do interesting things with our applications so we'll see you there, thanks hi I'm bob taber with developer university for more of my training videos for beginners please visit me at devu.com so we saw the my namespace pop up ever so briefly in the previous lesson whenever I was trying to find a good code example uh to write text to a file and I saw uh the the help article on msdn I'm like oh they cheated they used the my namespace well the good news is that the my namespace is available to visual basic developers and it's unique for visual basic basically the uh the developers of visual basic went around and found all the most useful classes in the .NET framework class library that we'd want to use for finding things out about a computer or about the file system or working with the network or working with specific peripherals and made them all available in one concise tiny little spot so that we can always go there first to see if they've got something for us to use or if we have to go out on the internet and search to find some code snippets to actually help us uh implement some functionality so uh at any rate the my namespace is automatically available to all visual to uh visual basic projects all we have to do is kind of navigate around and find what we're looking for inside of the namespace and I'll show you how we'll do that in just a moment so in this lesson what I want to do is just is to show you a smattering of cool little things that you can do with the my namespace get your creativity flowing and then maybe you can use it for something on one of your future projects so it's great for things like getting information about the current computer that you're running on it's great for working with files and folders on the computer working with command line arguments into your uh your command window application and then also working with configuration files like the app.config file so we'll show examples of all these in a little bit more but note that there's even more that you can do with it and you just can take a few moments and navigate your way around using IntelliSense through the my namespace you can see that there are things like the application namespace the computer namespace the settings namespace the web services namespace all of these are shortcuts into the full .NET framework class library giving you quick access to some pretty cool functionality. Alright so let's start off really simple let's do a console dot write line and here we're going to go my.computer and we'll just grab out the name but notice here now that I'm in the my computer namespace I can get to things like audio and I think the screen as well you can get to the clipboard copy and and paste things on the clipboard to the clock to the file system find out information about the hardware of the computer you're currently on work with the the keyboard in the mouse and the network in the ports and so much more so very cool so in this simple case let's just grab the name of the computer and then also I'm going to do is grab the amount of memory that's currently physically available on my computer but even note that about the info class I can grab things like the UI culture what language and country that I'm currently have installed in Windows 10 the operating system name and version the platform that we're running on total physical memory and virtual memory and things like that let's just grab the whoops let's just grab the available physical memory and then console dot realign and then let's just run the application and I have a really crazy name for my computer I didn't build it myself I did build it but somebody else installed the operating system I would have had a cooler name than desktop O U L N D H D O but meh whatever and then here's how much physical looks like I have I'm sure how many gigs that is is that 1.7 gigs or 11.7 gigs I'm not sure I guess I could format that nicely with a string format and then here let's use our like that remember and let's get a better idea so yeah I have 11.6 gigs of memory I guess available nice so let's comment that out and now let's move on and look at another example here suppose for example I wanted to just take a look at all the sub directories available in my documents so I might do something like this dim files as dim files equal and I know you're not supposed to do this but I'm going to do it anyway in this case my computer dot file system and I want to see all the things you can do copy directories and files create a directory delete the directory and file determine if a directory exists search inside of files for text and so much more move open files read rename things a lot of cool features here so let's get directories and I have to supply the top most directory we're going to use and look inside of so we're going to go users bob and then documents we're going to look inside of all of the sub folders for documents I'll just do a four each through each of the items in the files and do a console dot write line and print those out so each item and so now let's run the application and you can see here are all the sub folders inside of the documents directory pretty cool great and so now let's go ahead and comment that out and the next thing I want to do for my next trick I'm going to dim actually do this inside of the code that's available for this particular lesson there should be a folder called test and it just has three three text documents with a famous saying in each one like now is the time for all good men to come to the end of the country there's a couple of others like that and I'm just going to copy that entire folder and I'm going to put it on the root of my C drive so I'll just paste it there and now what I want to do is come back in and do the following so dim files equals my dot computer dot file system dot find in files and here I'm going to give it the directory to search in that test directory I'm going to say search for the word time tell me which files have the word time in them and then I have to give it whether I want to ignore the case or should it honor the case let's just say ignore case and then finally I have to give it a search type just do this file I owe dot and then we want to choose search option dot I can either search all directories or the top level only doesn't really matter in this case but I'm going to only search at the top level and now it should retrieve back a bunch of strings will parse through the strings and print them all out to screen but here we see that only one file has the word time in it let's confirm that by opening up our test folder and looking at the fact that here is the word time in this text file it's not in this text file and it's not in this text file so it worked very cool alright next up what I want to do is actually let's comment this out for the moment and we'll stick with the file system for a moment because it is so handy to do stuff like my computer dot file system dot copy directory and here I'm just going to take that test folder and I'm going to copy it into a new folder called test 2 and this will allow me to overwrite the folder so yeah I'll say yeah go ahead and overwrite it if it already exists which it does not so now here we'll just do console dot write just to give us some feedback that we finished and we'll run the application it finishes almost immediately and then here we'll go back look at our C drive now notice that we have a test 2 folder it has the same 3 documents that the test folder has in it very cool ok so let's comment that out and let's move on to the next example what I want to do is now show you how to work with arguments that you can pass in to your application so many times console window applications have the ability to pass in extra information as a series of information that is just you use spaces to delineate between each argument you want to pass in then you use those arguments inside of your application to branch and to decide what functionality to enable and so what we can do is one of two things we want to open up a command window and navigate to our my namespace we can go documents so cd documents cd visual studio 2015 cd projects cd my namespace that will give us into the solution folder and then we're going to go cd my namespace to get into the project folder then we're going to go cd bin to get into the bin directory and then I think there's a debug directory right so we'll go cd and then I'm going to do a dir and you can see all of the files that are currently there we'll come back to that in just a moment what we'll do here now is actually do dim arguments equals my dot application and here we can get at things like the culture the UI culture info I'm not sure what you can get from info oh okay oh info about this application I get it more importantly though I want to look at the command line arguments that are going to be passed in and then we'll go for reaching our way through each item in the arguments and we'll just do a console write line to show that we can actually retrieve them out and display them on screen but ideally here we would do some logic inside of our application and change the functionality based on the arguments that are being passed in so let's go ahead and just run the application once to compile it so that will get it compiled but now I can open up here and just go my namespace .exe and then I'll just do a b c and d notice that I use different capitalization and it actually prints out each of those to have a different line using console.write line very cool now if I didn't want to go to all this work inside of the command prompt window to navigate into the project directory I could use a special feature inside of visual studio that allows me to adjust the properties of my project so I'm going to right click on the project name in the solution explorer and select the properties option and here we're going to go to the debug tab on the left hand side and type in our arguments let's go e f g h and I alright so we're giving it five more command line arguments we'll save this and then rerun our application and this time you can see that it gives lowercase e uppercase f lowercase g uppercase I h and then lowercase I and we can basically test our command line arguments right here from inside of visual studio so just so you know let's come in all this out so that's another very cool little thing we can do with the my name space let's move on and talk about one other thing let's stay in that properties editor and go to let's go to settings so here we have this little grid where we can actually add settings that we can write to and retrieve between runs of our application so we might want to save the user settings what the preferences are in this app config file and we could write and open up that app config file and look at the the XML ourselves where it stores all these values but this is a much nicer editor that we can work in so I might want to store something like first value and set that equal to Bob and then go second value and set that equal to like Conrad right so now we have two strings that are stored in our app config and I can retrieve them out and use them inside of my application using the my dot settings dot first value notice that it automatically creates a property called first value and creates one called second value automatically because we created those keys inside of our settings tab of our of our properties so let's go let's do this console dot right line and we'll do it before and here I'm going to just print out my dot settings dot first value and then my dot settings dot second value and then I tell you what we're going to do we'll have a little fun here let's grab this let's make a change to it we'll set first value equal to Beth instead of Bob and then we'll set the second value equal to grant instead of Conrad and then we'll save those changes and then we'll go ahead and print this out again except this time do after and let's just grab this and just add an empty line there alright so this should be interesting I'm going to get rid of that too or actually let's just comment it out alright a lot of typing here but hopefully you can see what I'm doing I'm going to open up and grab the current values inside of the app config and then I'm going to change the values and save them and then display what the new settings are here in my console window application and you can see whoops we get the before and the after as the same I wonder why that happened and let me try this let's try to reset our settings here and let's go ahead and run it now alright there we go now we got what we needed alright very cool okay so I'm going to go ahead and stop right there but as you can see there's a lot of things that you can do with the my namespace there's even more I'll let you go ahead and explore it and learn more on your own but at any rate I'm going to go ahead and move on to the next topic if you're still with me you're doing great keep pushing through we're so far along at this point we're just tacking on and we'll continue that process in the next lesson we'll see you there, thanks hi I'm Bob Taber with Developer University for more of my training videos for beginners please visit me at devu.com previously I said that the creator of the console window project template whenever we go file a new project and we select a console application or console window project it added references to the parts of the .NET Framework class library that we might find useful however if there was a need for some class that didn't reside in the assemblies that were by default referenced in our project template then we could add a reference to it ourselves and the way that we would do that and you can see I just have a little throw away application that I'm calling typical console application the way that you can do that is to select the references node inside of the solution explorer right click and select add reference and that'll pop up the reference manager and you'll see that there are a number of different categories here we'll choose assemblies and framework and here you can see all of the assemblies that are part of the .NET Framework class library you can see some of them already have little check marks next to them indicating that we already have references to those now many of these I don't know that anybody use has used them all there's just so many of them and you only choose the ones that you need for your specific for your specific application some of them are specific to types of application whether it be a windows or a web application some of them deal specifically with data accessing data from a database or accessing data in the cloud some of them have to do with just security some of them have to deal with everything you can possibly think of it's going to be represented here in one of these so if I needed one of these what I could do is just find it for example system.data.link I might want to create a or maybe a SQL XML I want to work with XML and save it in a SQL database I might then add that reference by clicking the checkbox next to it and then selecting the OK button and now it's added that reference to my application I can use all of the classes and namespaces inside of that if I need it now if I if I wind up not meeting it I don't have to worry about about removing the reference this is really just a convenience for compilation the dotnet compiler the visual basic compiler is smart enough to know that we really didn't need a reference to that particular that particular assembly and we didn't use any of the name spaces or the classes inside of that assembly so it'll safely ignore it on its own alright now that's one way that we can get those additional libraries that were created by Microsoft for specific purposes into our application but there's also a wealth of free open source libraries that are created by third party companies and teams of individuals that that provide many common features that we might want to add to our application and so the repository for those open source projects is NuGet and what we can do is go to tools and go to the NuGet package manager and while we could use the manager console I recommend that you starting out use the NuGet manage NuGet packages for solution this will open up a visual editor and what we can do is browse for a specific type of library perhaps we know the name of the library that we want to use let's say I want to add some login capabilities to my application I might choose this log for net and there's a bunch of different ones but I might select it and then say oh yeah I want to add that to this project this typical console application and I want to install the latest stable version of it but there are some other options that I could choose from down here I'm just going to go ahead and click install and now it's going to grab down all of the assemblies and references to other dependencies that I would need in order to use that log for net library of functionality inside of my application so I just wanted to show you how to use it we won't be using log for net but you can see that it's now been added to as a reference inside of my project it's also copied down some of those library files into the actual actual project here let me find it real quick look for typical console application and here you can see there's a packages folder where we have the log for net and there's a bunch of different versions of it and then when we go to actually utilize it and compile it in our application it'll show up in our debug in our debug directory as well at this point we haven't added any references to the DLL so there's no need for the compiler to copy the library over into our debug folder so at this point we don't even we don't see it but I just wanted to make you aware of the new get package manager but then there's a third scenario where we might want to create our own library of code to reuse within our own company or within the projects that we work on individually maybe we could even open source them and distribute them to others through new get at some point so what I want to do is create a code library we haven't done that up to this point and I want to use some of that logic from two lessons ago where we were actually able to go out online grab all the HTML off of my website and what I also want to do is not only display it in a console window but also save it into a text file we'll call that something like scrape web page so what I'm going to do is create first of all a new project and this time I'm not going to choose console application instead I'm going to choose class library and we'll call this class library my code library alright something very generic click okay and yeah we can save off the changes we made there as you can see this code library only has a class I could rename this class something like oh I don't know my class again very generic and here what I'm going to do is create a public function scrape web page as string alright doesn't like the name my class let's call it the scrape class and so then we'll create a scrape web page function and here what I'm going to do is just start off by using the web client so we'll go a dim client as new web client of course it won't be able to find it I'm going to hit control period on my keyboard the system.net namespace and the next thing I'll do is go dim reply as string equal to client.download string and we're going to pass in something into the scrape web page function so we'll go by val let's go url as string so we'll pass that url into the download string that should work and next we're going to do a I guess we won't do the console.write line we'll just return the string or actually reply there we go and the next thing we're going to do is also go file dot write all text I happen to know that that's what I need from the system.io namespace so we're going to import system.io so write all text and then we're going to give it a path so I'll just go ahead and pass in a path that'll be the second item that we're going to need to pass in by val path as string alright and so let's go ahead and pop those on different lines and I have to also give it what I want to write so in this case we'll write the reply and then we'll return the reply so hopefully that will work let's go ahead and build the solution and what I'm going to do is change this from the debug to the release version so the debug version creates extra code that allows visual studio to attach to it the release version is when I'm finished with my code and I may want to distribute it and use it in other projects or actually put it on somebody else's computer so I go ahead and select the release configuration and then I'm going to choose build build solution and it should build into the release the slash bin slash release folder mycodelibrary.dll as you can see here and it looks like it succeeded so what we'll do now is actually create a new project to utilize that class library and I'm going to call this my client and click okay and here what we're going to do is actually add a reference to that to that dll that I just created so there's a couple of different ways to do it I'm actually going to right click and select add reference again and this time what I want to do is just use the browse feature and you can see that it found that I currently have this dll in my users bob documents visual studio 2015 projects mycodelibrary and so on because it's under the recent dls that I created but if it it wasn't I'd have to use the browse feature and I'd have to go and search using the this open dialogue to find that dll somewhere on my hard drive and that's that's not going to be as pleasant there's a lot of friction in that experience this time just for the sake of illustration I'll go ahead and use this recent item but I probably would have to use the browse in order to find that dll on my hard drive alright so let's get started I'm going to need to create an instance of scrape so dim my scrape as new scrape and it doesn't see scrape in the intelligence so clearly I did something well oh you know what I need to do control period and I need to import the mycodelibrary namespace into my module dot vb why because the default name for my name space is the name of the project so I need to import the namespace for the code library I created that contains the scrape class and then it will be able to see it alright so now I have a reference to my scrape and I should be able to do like dim result as string equals my scrape dot scrape web page there we go and let's give it a URL and then a path where we want to save the file so the URL will be http://www.devview.com and then we'll use for the for the path c colon slash I think I have an example folder where I've been saving some things example devview.txt and that result will come back I'll do a console dot write line just to show that we can actually get that string back and I'll do a console dot read line and now I have hopefully successfully used the code library that I created in the previous step so let's go ahead and run the application uh oh we got a problem there's a syntax error where oh let's go ahead and add an underscore there probably should have done it like this instead and then we'll add that there okay let's try and run it now there we go alright so we grabbed all the text pretty quick I'll go ahead and hit enter to finish that and now let's take a look at the example folder there should be a devview dot txt and there is and it has my entire web page so that's how you can create a library with functionality to scrape web pages off the internet and waste everybody's bandwidth but at any rate you can see that um it was made pretty easy by the fact that we were able to add a recent item but what I'd like to do is actually recreate this project really quickly and um just show you how to create this project so we're going to call this um the scrape web scrape I'll call it web scrape and click okay and what I'm going to do is I'm going to allow this web scrape project to be the console window application and then I'm going to add another project to it so I'm going to go to file add a a new project and I'm going to create a class library which I'm going to call my code library all right it should put it in the web scrape folder and here we go I'm going to call this scrape and here we'll go public function scrape web page a string and I tell you what we're going to do I'm just going to pause the video copy and paste the code in here from the previous project so let's go ahead and pause the video now all right so you can see that I've got two projects the code library project will have a class called scrape with my scrape web page functionality in it and I have a second project that will actually be the consumer of that code library and here we'll go and utilize it by going let's go scrape and I'm going to hit control period on my keyboard and it doesn't see it well what we need to do as you can see is use one of the options near the bottom import my code library from my code library and so that will fix the issue and it created a reference all in one shot you can see it added the reference here as well very cool all because it's right inside of the same solution so let's go and do a dim my scrape equals new scrape and then we'll go dim result and a string equals my scrape scrape web page here we'll pass in here we'll pass in the url like we did before let's do let's grab something different like microsoft.com and then we'll save it here secone slash example slash microsoft.txt and then we will go console dot write line passing in result and then console dot read line like so and now let's run the application and we're able to get back the microsoft homepage and if we were to navigate over to our example folder we have a microsoft.txt that has the web page in it great okay so in larger projects it's likely that you want to keep multiple projects into the same solution when they're somehow related here we've split up the functionality and created a shared code library but we were able to access it then from another project whose purpose is to actually do the to call into that code library and then to actually show stuff on screen save it to a hard drive all that kind of stuff but this is the exact scenario where using multiple projects inside of a single solution makes sense so to recap in this lesson we talked about how to create a reference to other parts of the dotnet framework class library if they're not already added in by default depending on the project template that you've selected we talked about how to reference other free and open source assemblies that are created by other companies a group of developers or even microsoft has some of their some of their libraries out there on NuGet as well we looked at how to create our own code library which we did that for the first time and then how to access it from our app and then we looked at a second version of that where we actually created a solution containing both the client and the library in the same solution right here and we were able to easily make a reference from the client to the code library in just one step by hitting control period on our keyboard that quick access step that we got in from IntelliSense and it did everything for us in one shot it was very convenient okay so hopefully that's insightful and that helps you to understand how how you know developers really work with splitting out the responsibilities of their application into multiple files for reusability sake maintenance sake and then also for distribution through other channels like NuGet or whatever the case might be alright so hopefully that helps and we'll continue on and talk about collections in the next lesson we'll see you there thanks hi I'm Bob Tabor with developer university for more my training videos for beginners please visit me at devu.com so previously we looked at arrays which allowed us to keep a sequence or group of related values packaged together in the same container in the same bucket the analogy I've been using up to this point the same bucket in the computer's memory and we created an array by first defining the data type and then the number of items that we hope to store in the array surrounded with parentheses so if I wanted five items I would do dim something and then use parentheses for as string and I would creating an array of strings in that case and then once we had the data gathered together inside of an array then we could iterate through the array and perform other operations on all the items in the array kind of together as a group but you recall that I said that once I introduced collections you would see that they were arrays on steroids and I almost exclusively use collections over arrays unless I absolutely have to and I think you'll agree that collections are great whenever you're working with all data types not just simple data types like your strings and integers but then also with custom classes like the car class that we've been building ourselves so the Donut Framework Class Library will use both arrays and collections depending on what it's trying to do but you're often going to prefer to use collections because of some of the rich filtering sorting and aggregation features that it provides through a feature called link which stands for Language Integrated Query which is an innovative feature that was added some years ago to Visual Basic and C-Sharp for basically this very purpose if you're familiar with SQL what is that structured query language then it's going to look a lot like that or at least it was structured to look like that and we'll dive into the link in the next lesson but there are essentially a couple of different collections that we want to take a look at in this lesson we're going to look at lists and dictionaries and there's probably a dozen additional types of collections we could look at each of them have their own superpowers they're used for very specific situations however I personally feel like if you were to understand lists and dictionaries you'll use them about 95% of the time so I'm going to introduce these to you and then you can go off and learn about the other specialized lists and collections that you can use on your own so suppose that I have a number of cars on my car lot and I want to work with all of that data all of the car objects collectively as a group as opposed to just storing the data about each one of the objects individually so to get this set up what I want to do is actually point you to the code that's associated there will be a before folder and I want you to copy out the understanding collections as a starting point and if you're going to follow along let's go to the projects folder and paste that baby in and now we can open up that project and we'll both be in the same place here okay so as you can see this project has two different classes a book class which I created it has a title author and then a car class which only has a make and model property for now and then you can see here that I've already created two instances of car in one instance of book so we'll be able to start typing our code here in about line 17 or 18 but again back to the example suppose that I want to work with all of these cars collectively and put them in essentially and group them together in a collection or an array I probably will wind up using a collection because of the reasons that I said earlier it gives me so many additional options here so what I want to do is start off by talking about a specific type of collection called an array list and I want to start by talking about it because it's a lot like an array but it has some added features that are pretty nice for example array lists are dynamically sized so you don't have to say ahead of time how large you want your array to be so add and remove items really easily using some methods and the other thing about this particular this particular collection is that it will allow you to put any data type into it you don't have to specify that it's a specific type whether string or integer or car of course that's the downside as well so let's go ahead and get started by creating a new instance of of this array list so I'm going to go dim my array list as new system dot collections dot array list all right now obviously I used its full name apparently I didn't need to because it's already been added to the default collection of name spaces so I can just hit control period on my keyboard and I can choose the simplify name and just go ahead and remove that and now we're working with the array list without the full name all right so now what I may want to do is go my array list dot add car one and my array list dot add car two and then what I can do also is do a for each for each item car in my array list and I can do console dot right line and do item dot and I can print out either the make or the model since strongly typed and I know what kind it is I can say a just print out the make for both of the cars in the array list all right and you can see that I get the list here now one of the dangerous things about the array list is that it is so flexible so what we could do with the array list is actually add that instance of book that I created or actually it's just b1 is the name of it I can add that to my array list as well and when I run the application I'm going to get invalid cast exception in other words you can't convert a book to a car so on the third iteration through I try to take the book and say this is actually a car and it says no it's not and it won't let me proceed alright so I can easily break my application let me see if I can do something here and just remove that and now I'll try to run the application again now I get a different exception I said let's not call this a car let's just make it an object so that it passes that test and we're not going to check whether it's a car or something else however I attempted to access the make property of the book well there is no make property of the book and so I get a different exception missing member exception so I guess the moral of the story is that the bad news is you can add anything you want to the array list it's very it's very accepting which is both good and bad now the good news is that I can honestly remove an item as easily as I can add an item to my array by using the remove method and now the application works again because we both added but then removed that item from the array list so I just wanted to show you what's possible now I already noted some downsides about the array list while it is extremely useful and flexible and probably better than an array the fact that you can put anything inside of it is kind of a problem so what I want to do is actually use two better collections they're called generic collections they're generic because you have to define the type for the collection to make it specific so let me go ahead and just type in some code and then I'll explain how this works we'll use a list of T generic collection so here we go dim my list as list of car equals a new list of car my list.add car 1 my list add car 2 and now we can do a 4 each so this is going to require a little explanation let me just make sure it works and it does what is this list of car well its formal name is list of T where T represents a data type any data type that you want to make it specialized so in other words its a generic collection but we're making the generic collection specific by saying it can only be a list of cars and nothing else so you'll remember that I was able to break my application at runtime but it passed at compile time by adding a book B1 but this time we're going to get an error whenever we try to add the book to our generic collection our list of car because value of type book cannot be converted to car alright so its better to catch these things while we're doing our software development and by using a generic list in this case a list of car we're narrowly defining the collection and saying it can only work with cars if we try to add anything else to it generally speaking whenever you're working with data in software development being very restrictive is better than being unrestricted now some people would disagree with that and say for example javascript allows you to be very dynamic but then again a lot of people shoot themselves in the foot with javascript whereas with C sharp you're going to get those compilation errors ahead of time if you are putting those restrictions on your types upfront okay and that's what we're doing here so now let me show you one more type of collection generic collection is called a dictionary and think about a dictionary that you're familiar with like webster's dictionary you have a word that you need a definition for so you go and you turn the pages until you find the word and then next to the word is usually a sentence or a paragraph that explain or is associated with that word okay and that's the idea of a dictionary the same thing is true here you're going to have a collection that will have a key in this case you know in the case of the webster's dictionary the key would be the term that we're looking up and then the value would be the definition itself which would be the sentence or paragraph explaining the key so we can create that same sort of situation by creating a dictionary so here we'll go um dim my dictionary as new dictionary of car whoops I got to give it two things I have to give it first of all t key and then t value so the type of the key and so in this case I'm going to use a string as the key and then I'm going to give the type of the value which will be a car so we're going to give our dictionary whenever we create a new a new item in our dictionary we're going to give it two things first of all we'll give it the key which will be the car so car one dot make and then we'll give it the actual car one itself so now we can find any item any car in our list of cars by merely using the make so here we'll go my dictionary dot add car two dot make and then car two all right and so let's go ahead and go a console dot write line and let's look up my dictionary and we'll look up the I think we have here we have the geo prism okay so we'll look up the geo and then we can get to its make or its model like so so I can index into the dictionary by supplying the make which is the key to get a specific instance of the entire object so let's go ahead and run the application and you can see that now we're find that the prism is the model because geo is the make all right now we can attempt to go my dictionary dot add and we can go ahead and give it be one dot author as a key and then attempt to give it the book itself as the actual object that will be saving in the dictionary however we're going to get an error the value of type book cannot be converted to car so while author is a string and would probably pass unfortunately or fortunately rather the book is not a type car and it cannot be added so it's restrictive and that's a good thing because we catch those kind of problems while we're writing our code very nice okay so moving on from there we've got two generic collections we can work with the list of T and the dictionary of T key T value let's talk about objects and collection initializers so did you remember from before where we did this dim names as string equal to and then I gave it I think Eddie and Alex and David Lee and Michael all right and then we were able to now in one line of code both create and initialize our array we can do the same thing with objects and with collections of objects so here we'll create a new car so let's do this dim my car as new car all right and then I can use the with keyword and I can just do this dot make equals let's make this a BMW and then dot model equals 745 Li okay now I've created a new instance of the car object and populated its properties all without the use of a constructor like we did previously when we were looking at creating constructor methods I'm able to create an object and initialize it all in one line of code looks very similar to what we did with arrays right very cool then to kind of top it all off I can use the same kind of process to create many instances of car and add them all to a new list of car all in one line of code even though it'll be separated on different lines it's essentially one instruction that we're passing individual basic so here we go dim my list of cars as new list of car alright so that's the first part now we're going to use the from keyword from and then opening and closing curly braces and I'm going to go ahead and just make some room for myself here and then use my arrow keys to kind of navigate around new car with and here we'll go make equals Aston Martin and model equals db9 then I'm going to use a go to the end of that object initializer and go to the next line and create another new car with .make equals Audi .model equals EA8 comma new car with .make equals a dodge and then .model equals the dart okay alright so then at the very end we'll just go ahead and collapse those last two curly braces so it can start get confusing because you know what curly brace belongs with what curly brace but typically what happens is if you select one you'll see that it's slightly grayed out and it'll show you it's corresponding opening or closing curly brace by giving it a little gray background as well so whichever one you've got selected it will show you it's corresponding beginning or ending curly brace by highlighting it in light gray color okay but essentially this is one line of code now what we can do is we can for each our way through for each item as car in my list of cars and here we'll go console.write line we'll just go item.make or model actually we'll do item.model let's go ahead and save it and run the application and you see there are the three models of cars and essentially we were able to in one line of code create a new list of car and create three new car objects and add them in to initialize that collection with new instances of the car object as well all in one shot wow that's pretty crazy right so any rate that's all I really wanted to tell you about let's recap what we talked about in this lesson we talked about collections both generic collections and non-generic collections we talked about why you want to use a collection especially a generic collection and we talked about in the dictionary of T key T value how to create those why they're better than just your normal collections because they enforce types and so they restrict the types that can be used inside of the collection which means we can catch errors since it's strongly typed at compile time rather at run time then we looked at it in an object initializer here and then we looked at a collection initializer here all right and next up what we're going to be able to do is use the link extension methods in the link language in order to filter and sort and group our collections and so that's one of the reasons why you want to use collections over arrays when we're working with lots of data and so let's do that in the next lesson we'll see there thanks and so that's it for today. Let's go ahead and do some other group related functions on collections like we just learned about in the previous lesson so link stands for language integrated query and it comes in two forms and we'll look at both of those in this lesson there's first of all the query syntax itself which resembles SQL the structured query language so if you're already familiar with SQL you will see some but there's also in addition to the query syntax there's a method syntax so it's just calling a series of methods just like you would any other method and you can chain those methods together like we learned about previously now the only little wrinkle here is that they use a special feature of visual basic called lambda expressions which are these like many tiny functions that you pass in as a parameter argument into those methods and that can sometimes bend your mind a little bit if you're not familiar with looking at them but we'll take a look at them and I'll try to explain what each of the little lambda expressions do for us and I'm only going to show a few examples of link in this lesson frankly you could create a whole course just around using link inside of your applications just to demonstrate all the features of link so it's a pretty extensive topic we started for this lesson and introducing link I want to grab the source code for this lesson from the before folder and I'm going to copy that and put it into my projects directory and paste it there great now let's open that up and if you take a moment to catch up with me you will be looking at the same thing I'm looking at right now as you can see I have a car class it has make model year and sticker price and then I'm creating a new list of car creating several cars using that object and collection initializer syntax to what create five cars so that we can start filtering and sorting these cars and displaying them on screen ok so first of all let's just take a look at how to do a simple query syntax for a to find all of the cars that are from BMW so let's go dim BMWs equals from car in my cars which is the name of the collection you can see here then where car dot make equals BMW select car ok and then here what we'll do is just do a for each for each item as car in BMWs and we'll just do console dot write line and here we'll just make it easy we'll go use the replacement syntax and just use item dot make item dot model and item dot sticker price and we'll go ahead and just format the sticker price alright so let's run the application and we'll see now that we get from our link query only three BMWs out of the possible five cars on our car lot and we're also displaying the model and and the price awesome ok so that's a simple case where we're just looking for and filtering by a single property of the objects inside of our collection let's go and make this a little more advanced in fact I'm just going to copy the previous example pasted here and we're going to say that this is almost identical but instead of just filtering on one one of the properties I'm going to filter on two properties and find those BMWs that were created in the year 2010 alright so what I want to do is just to add another item here and we'll go item dot year ok and so now let's save it and run it and we can only find one BMW that is a 2010 model in our list of cars alright so by using the and keyword we're able to add additional filtering criteria in our link query alright so far so good what if we look for just those newer cars so let's start off by going dim new cars equals from car in my cars where the car dot year is greater than 2009 let's just go ahead first of all and just select the car itself and then we'll come back and do this a little bit different the next time through I'm going to change this from BMW since we have the name of the collection we're retrieving back to new cars so let's run the application and you can see now we get two cars back that were newer than 2009 and now let's go one step further and say we only want to select out certain attributes so instead of select car let's select just a couple of attributes and put them into a new data type so car dot make and car dot model and those are the only two attributes that we're going to use now already you can see that we've got a small issue here when I added this select new with it doesn't like it here because I'm no longer working with a collection of cars I'm working with a collection of something that resembles a car because it has two similar properties but this data type that I'm actually creating here on the fly it will only have two attributes I'm making a model in other words I'm creating a new data type I'm projecting the data from car into a new data type what's the name of the data type I have no idea we're just making it up as we go along it's has no name it's anonymous so we're creating or projecting out only a couple of properties from our query into a new anonymous data type a class that we're creating on the fly that has no name now internally visual basic will give it a name so that's one of the the problems here that we see that we are instead of working with a collection of cars we're working with a collection of something called prime a the little dash in the a so all you need to know about this is we're just going to remove this as car park here and it should work now you'll see that we're going to get some more errors why because this new anonymous data type doesn't have the idea or any definition for a sticker price or a year so we're going to need to delete those attributes as well but now that I've done that whoops ah okay we got to also remove the replacement syntax here associated with it and now we can run this there we go so I realize that I threw a lot at you in that little code example but just reason with me here if I don't need to pull back all of the data because I only want to display just a few properties of the data then selecting the entire object out of the collection and putting it into a new collection might make that new collection just as large as the old collection so I can be a little bit more savvy about only choosing those attributes that I really need and putting them into a new anonymous type now you may never do this I just wanted to show you what was possible alright so again this is called projection and we're projecting into an anonymous type in this example but there were some ramifications from it it was a little more complex and I don't want to throw you too much so let's just move on from there and let's talk about instead of filtering and projection let's look at how to order and this will be a simpler example so ordered cars equals from car in my cars order by car.year and then select car and so let's just call this ordered cars and then let's also add back in item.year and let's go ahead add back in the as car and let's go ahead and run it and so we should see a list of all 5 cars and let's also add back in the display of the year so we can see that alright so now we're going in order from the oldest to the newest so what if I wanted to actually sort them in the opposite fashion I can order by descending there we go and now when we run it it will start with the newest cars and go to the oldest cars great alright so we saw a few examples of the query syntax and I didn't emphasize it at the time but if you are familiar with the structure query syntax things are in a little bit different order like for example in a structure query language syntax you would see the select first and not last however the syntax is close enough that you can easily adapt your thinking to remember it and fumble your way through with the help of IntelliSense alright so let's start back over and remake a few of these examples except not using the query syntax but rather the method syntax so here we go let's start with just finding all BMWs so let's go dim BMWs equals my cars dot so look we're already using instead of we're using methods instead of using a syntax that looks like a sequel so here's where things get a little funky I'm going to have to find all cars that what was the criteria again here that are BMW ok so here what I'm going to do is pass in what's called a lambda expression which is a mini method or a mini function so I'm going to say the criteria we're going to use for the where clause is I'm going to create a little function and I'm going to pass in each car in my list of cars and I want you to pass me back those cars where the make is equal to BMW alright see how we did that so again just think of this as a mini method I'm not going to give the method a name I'm just going to say in every car in my list of cars you pass me back all the cars that match this functions body this the criteria that I'm defining here where the make is equal to BMW and then at that point we'll be able to then iterate through and look at each of the cars inside of that collection that we're getting back from the where clause so we're in the application and we get back all BMWs alright so what if I wanted to extend this and say not only do I want you to give me back all BMWs but also all BMWs and we'll do the same sort of thing where so I'm just chaining on another method another where clause here and I'm going to pass in another little a lambda expression another little mini method so function and I'm going to pass you back of all the cars that were passed back whenever we eliminated some from being just BMWs now we're going to further refine that and we're going to pass in each of those cars into this little mini function and say only return back those cars where the year is 2010 alright so we're going to filter the original list and then we're going to filter the list that came out of that and then return back that list and then we're going to iterate through each of the items one item that meets that criteria a 2010 550 I okay great alright so now let's take a look at the ordering of cars so let's go dim ordered cars equals my cars dot order by descending so there's a whole method just for order by we'll start off with the order by or order by descending so here again I'm going to say we're going to pass in a little mini method to tell you what I want to order each car by and I'm going to want you to order it by the year alright so let's go ahead and change this to ordered cars and furthermore I think we can yeah print out the year great alright so we've ordered them from oldest to newest and then we can do the order by descending to create from newest to oldest great now I personally prefer the method syntax once you get past what a lambda expression really is once you can rectify that in your mind and you can look at examples online for help for a given link extension method which are these wares and orders and order by those are extension methods that are added on collections by the link functionality then I think it's the easier syntax frankly and you can do some interesting things with a little bit less code so one of the things that I I want to show is in fact let's go ahead and comment that out you can perform operations on the entire group as a whole so say for example I wanted to get the total of all the cars on my car lot their total value so I might do something like this dim the sum so my cars dot and notice here that there's a some method and I'm going to say and give it one of the many many functions passing in every car from the list of cars I'm going to say summit by the car sticker price so go through every car and add up the sticker price and then return back the total amount for me here we'll go console right line and put in the sum and here we'll say total value and zero C to format it like currency and the total value of all the cars on my car lot are $250,000 cool let's take a look at some of the other methods and text options that we have so for example we can aggregate items we can get an average of of for example each cars value we can cast or convert each object from one type to another we can get a we can find out if an item exists in our collection and we can find the first item or the last item we can do the for each which will be pretty cool we can group by items just like we could in sequel we can get the max and the min we can do even complex unions between two data sets so it can get pretty hairy but let me just show you one other thing just so you're aware of it I want to use before each and what I want to do is actually take every car and add $10,000 we're going to have the opposite of a sale so instead of a function I'm going to pass in a sub because I don't want anything to be returned back I just want to operate on each item inside of each item that we pass in so each car in my cars I want to take the car and add $10,000 to the sticker price and let me do this so sticker price let's do plus equals $10,000 and then let's go ahead and print out and get a sum of all the cars and then print that out here and let's see what we come up with there we go alright so there we go we have increased the value of our car lot by $50,000 why because we've added $10,000 to each of the individual cars in fact I could even make this a little bit shorter by just going here with the total value let's just go mycars.sum we can do it right here in line and function car and inside of that we'll do car.stickerPrice alright so we're able to reduce that down to two lines of code but I'll bet you I could even reduce this down to one line of code let's do inside of this we can get pretty silly here and do stickerPrice plus $10,000 let's see if that'll work I'm going to get rid of that and it's not a permanent change but we're able to do it all in one line of code you can see how crazy this gets let's go ahead and split that up into multiple lines here just so you can kind of see it all I'm sure with the right way to split that out but there you go so we can get pretty crazy with this and do some really interesting things all in a very compact syntax it makes your code less readable but you can do some powerful querying, filtering sorting and also group operations on your data with using link both the query syntax and the method syntax alright so that's really all I wanted to show you in this lesson let's continue on if you're still with me you're doing great follow along and then go ahead and do some experiments and even search for link visual basic examples online or on microsoft.com so we'll see you in the next lesson thanks the if and the conditional the IIF methods work great with a limited number of use cases but when you begin to evaluate many potential cases and you need to branch off in one of you know 10 or a dozen or two dozen different directions then the if and especially the IIF method they start to become cumbersome they're very wordy and they're very flexible powerful but it might be overkill for that particular situation I'll show you an example here in just a moment of where it makes sense maybe to use a new decision statement called the select case but first I want to talk about a special data type called enum and specifically you know what I said earlier with regards to working with data as a programmer you typically want to restrict the values or restrict the kind of data that can be stored in a variable or any kind of any kind of data that you're working with so admittedly we're already limiting the kind of data that you can store in a variable given its data type right but even within the data type I might want to limit the possibilities to just a few options a few possible values so typically again in software development you want to limit and constrain your data to ensure its validity and its usefulness within the software system so an enum or enum is a data type that limits and constrains all possible values to only those that are valid for our application so we may want to keep track for example of a series of to-do items we might be creating a to-do app and each to-do item could be represented by an instance of this to-do class as you can see here in my understanding enumerations project so we might want to keep track also of the current status of an item and maybe it should only be one of several different statuses like maybe not started or in progress or on hold or completed now as I'm going through and I'm developing my application I certainly could use a string and then start comparing strings against each other but the problem with strings is that you can potentially mistype a string and so especially if it's going to be input by an end user there might be some fat error correctly or you within your own software development efforts you might not have typed it correctly in one spot and subtly introduced a little bug whenever you're checking to see if my to-do dot status equals not started something like that in this case as it's represented right now you might miss the fact that you are missing a T and this would never get executed so you typically don't want to work with strings when you're doing comparisons these are often called magic strings because they hold values and because of the flexibility of a string it can hold any value but it might not make sense in our application and so you typically want to constrain values not use strings for purposes like this anything like maybe a title or description sure use string because you want that to be any potential value but a status you want to limit statuses to only a few possible statuses because you might be doing some business logic based on the current status right so an enumeration will help us by eliminating all of the possible values to just a few possibilities so in this case what I could do is to actually create a public enum and call it to-do status and then I'll just type the possible values for a to-do status so here we'll go not started and you can't put spaces in between these I might be able to use a dash or an underscore but I'll just go ahead and use camel casing in progress hold completed or deleted and those are the only options for to-do status now I'm going to change the status of my to-do class from a string to type to-do status and notice that this is almost like a data type in and of itself I can use it as a data type for my variables or my properties inside of a class however it's constrained and it can only be certain values now notice that behind the scenes not started is equal to zero in progress equals one on hold equals two so if we were to save this to a file or save this into a database what would be stored in the database is zero one two three or four in the case of deleted so it's zero base and each of these options have a value from zero in this case to four however when it's being used here in our application we can do something a little safer than what we currently are doing now we could do to-do status dot and we can only select one of these items from the list of possible enumerated values so now I can do a safe comparison see does my to-do status equal to do status and you can see here in IntelliSense the options not started and in that case now these types they're strongly tight I know that it can only be one of these five statuses and it can never be something else and I can never fat finger it because at run time or at compile time it'll do that type checking and make sure that if we come up with something crazy like something crazy or we just were to type it incorrectly we're not even going to be able to run the application it's not going to build it's going to give us a compilation error because something crazy is not a member of the to-do status enumeration okay so hopefully that makes sense enumerations are used all over the place in the dotnet framework for example the console window class has a foreground color and you can set that to one of several different enumerated values defined in an enumeration called console color so I could make this for example dark red and then whatever I type in so console dot right line and we'll say hello world console dot redline it'll be limited to just those colors and see hello world very dark red just those colors defined in the console color enumeration alright so again enumerations are very good thing whenever you're working with data because it limits the possible values let's go ahead and create another quick example here working with a different data type instead of an enumerated class to do items let's let's work with superheroes and create a little application that allows us to see for a given superhero what their nickname is and so I'm going to add another class to my existing project and I'm going to call that class superhero and in the superhero class actually I'm not going to make it a class I'm going to actually just make this an enumeration so I'll just make superhero not an entire class so to change a class into an enumeration you just change the word from class to enum and then you start typing the names of superheroes like Batman Superman Green Lantern and so on and then here in our main program what we'll do is ask the user to type in a superhero's name to see his nickname and we'll go console.readline and we'll set that into a user a value as string equals console.readline so now we have the user value so what we can do is attempt to compare that to one of the possible values here so I'm just going to do an if statement to begin with but we'll come back and we'll replace this with something a little superior to an if statement so if a user value equals we could just use magic strings right and say if it equals a Batman then console.writeline you know caped Crusader or Dark Knight or one of the other nicknames Batman has but we don't want to do it this way again because we don't want to work with magic strings we want to work with enumerations instead and so there's going to be a little bit of a disconnect because whenever we get content from the user we're going to try and convert that into one of the enumerations and if it doesn't convert then we're going to need to let the user know that there's an issue so what we're going to do is use this if superhero dot and then we're going to do this try parse method of our enum and I'm going to give it the user value and I'm going to try to let's look at the second version of this yeah I'm going to ignore the case and then I'm going to attempt to convert that into a into my value now I haven't created my value yet let's go ahead and dim my value as superhero so what we're going to attempt to do is take the user value that they typed in and we're going to try and parse that string that they type in into a type of superhero and if we can do that successfully then we'll go ahead we'll go if my value equals superhero dot Batman then console dot right line caped crusader else if my value equals superhero dot Superman then console dot right line man of steel else if my value equals superhero dot green lantern then console right line emerald emerald knight I believe and I think it's complaining because it wants things on separate lines like this console dot redline and so let's run the application and we'll type in superhero's name and I'll just say Batman and it types out caped crusader now obviously I don't have a lot of checking here because if I put in Wonder Woman I'll get nothing because we're just skipping over this we were not able to successfully parse what the user typed in and convert it to one of the enumerated values all right and this is not that great of an example admittedly because we're allowing the user to type in and then we're having to attempt to convert it but I just wanted to show that concept of how you would do it the to do examples probably something you're going to find more often because you'll have complete control of the data and you may want to present the data options to the user in some sort of either selection select one for Superman two for Batman or some drop down list box in a web based interface or in a windows user interface whatever the case might be but let's go ahead and just leave this the way that it is for now and what I want to do is come back to this example in just a little bit because I'm going to pair this up with the new with a new type of of decision statement instead of using the if will try something else which will be a little bit more elegant than what we did here all right so I want to introduce a new decision statement the select case statement you know the if then else if else and if it's really powerful you can do a lot of really cool things with it however if you need to do something simple it can sometimes be overkill here's an example of something you can do which with the if statement that is actually pretty interesting so I'm going to show you a complex if statement example and you should be able to find that in the code folder wherever you're currently watching this video and so as you can see here I can do some interesting things like use or inside of my if statements to look for ranges of things so in this case if the value that the user types in is less than one or greater than a hundred I can give some specific feedback that the option that they chose was out of the normal boundaries now if they select specific numbers 42 or 23 or anything greater than 90 then we can give them a message that you found one of the special numbers otherwise and find one of the special numbers so we can get pretty complex using the or in the and like we saw at the very outset when we're looking at various operators and here let's just choose like 86 you know you didn't find one of the special numbers but if I type in 23 you found one of the special numbers okay very simple example but you can see that with an if statement you can get very complex and test a lot of different cases let's close that down and close that out what I want to do however is create a new project so let's save what we have here and understanding numerations and we'll go file new project and we're going to create one called understanding select case and let's create a similar example to what we did before except we're not going to use the numerations this time around so console dot right line and then type in a super heroes name to see his nickname alright and then let's go a dim user value a string equals console dot read line and then now we're going to use select case and I'm just going to hit select tab tab and you can see the format of the select case statement and so what we'll do is evaluate this user value and in order to make sure that we are comparing apples to apples I'm going to call the two upper function like so so that and here I'm going to hit tab we can select and check for Batman for example or for Superman for example and I could continue to add additional cases like green lantern alright now here I can just do you know the console dot right line and type in caped crusader console dot right line man of steel console dot right line emerald night alright and then the case else we could just say console dot right line not found okay and then here we'll do the console dot read line and that should end the program so now let's run the application and yes admittedly we are using magic strings but you can see the elegance of and how quickly we were able to create a select case statement couldn't find it because I didn't type it correctly see therein lies one of the problems but how quickly I was able to create a select case statement as opposed to using the if else if else end if statement alright so now let me do this let's combine these two ideas together the select case our so let me close this project down and reopen up the previous project that we had the understanding enumerations and I want to take a different tact than we did here I'm going to comment all that out fact I'm just going to push it down here below whoops I'm going to actually use that and so go select tab tab we want to check my value tab tab here we are going to go superhero dot superman superhero dot batman we will go another case superhero dot green lantern and here we would go the console dot right line or I can just do something like a little bit easier we'll just do dim result string and then we'll do result equals superman or we could just do steal result equal crusader result equals green lantern and finally let's just go ahead and go here at the bottom console dot right line result and we should get the same results alright so it's a little tidier you can see there's just a little bit less code involved than if we do the else if my value equals each time and so for simple cases this will suffice we could also just put everything here on one line to even make it more compact using that line ending character the colon so we can keep it real nice and tight like that but at any rate you can see how they're used together then in these situations okay so that's really all that I wanted to demonstrate here we talked about the value of enumerations to limit and constrain the kind of data the amount of data that can be assigned to a given property we looked at a couple of examples of that then we looked at how we were able to utilize the select case as opposed to the if statement in those situations where we just want to evaluate one particular value against a number of potential cases as we saw here and then take some action some simple action based on that it's a little less verbose than the if statement if else if else and so on and we looked at some complex if statements of two other things like try parse which allows us to attempt to in this particular case take a string that the user typed in and find a match for it in our enumerations if it returns true that we did find a match then we'll execute this code but if it didn't find a match it'll just skip over the entire all the logic that we wrote inside that code block okay great let's continue seeing the next video thanks hi i'm bob taber with developer university for more my training videos for beginners please visit me at devu.com in this lesson we're going to talk about handling exceptions that occur within our applications we're going to discuss what can go wrong why things go wrong and how to build resilient applications that are impervious to crashing through the use of the try catch and try block in visual basic so whenever the compiler catches a data type mismatch an unresolved reference to a class or some malformed visual basic instruction it will refuse to compile your source code into a dotnet assembly until you fix the problem we've already seen this happen a number of times we usually get the red squiggly line will get the error list pop up those are called compilation errors and those are good because we can catch those and and fix them before we release the application to others right but there are other kinds of errors that happen only during run time in other words they happen when the compiled dotnet assembly is actually in the act of executing on somebody else's computer so there are countless reasons why this could occur but many times it occurs to do due to situations that are outside of control of the software developer for example if you're creating an application that cannot read or write to the disk for some reason maybe it's because there's a folder or a file that's missing or the file is corrupt or because the network access to that resource is unavailable or perhaps your application attempts to connect to a database and that particular table in the database that you were relying on is no longer there maybe the columns of change names maybe the structure in general has changed these and many more could cause your application essentially to crater to experience an exception at run time now in some cases the developer may not have foreseen a problem and therefore didn't account for it for example maybe the developer allows the users to type in their country but the user misspells the country name and you know as a result we can't find a matching country and we have bad data in our database as a result or perhaps the user is maliciously trying to break the application maybe they type in numbers instead of alphanumeric characters or alpha characters so as a software developer your job is to make sure that you account for every possibility everything that could potentially go wrong with your application a friend of mine was fond of saying that 80% of all code exists to solve 20% of all potential problems that can happen so generally software developers should be pessimistic about the reliability of any input into the program especially input that's human in nature somebody types in a value and hits enter be suspicious about that value because it probably is wrong it's probably not what you need it's not what you need to accept and you need to be tested to make sure is this really valid information that I can use in my application so if you rely on a file or a network resource trade it with great suspicion because it may not be there if you rely on a user to type data into the application treat that as absolutely evil alright you have to be very suspicious about anything you cannot absolutely control in your application and this is the software developers equivalent to defensive driving you should always code defensively so the way that a visual basic developer codes defensively is through the use of the try and catch and and try statements in visual basic which we're going to demonstrate in this lesson so let me give you a quick example of the kind of things that can go wrong here we'll create a quick example in our project gracefully handling it's exceptions and I'm just going to go dim content astring equals and we'll use the file we've used this once before I'm going to go ahead and hit control period on my keyboard and import the system that I own namespace file dot read all lines or read all text that's what I want read all text and if you recall we had a a path that we created earlier when we were going through the my namespace project we created a folder called test and there was a test one dot txt and let's go ahead and write that out to our console window and let's do that and now let's run the application now in this particular case I know that that file is there and the folder name is there alright but what if for example we were to either fat finger the name of the folder or the file name and what if we didn't account for that possibility that that folder the test folder and that file test one dot txt does not exist on our hard drive well at that point then what the developer sees when running in visual studio is this little nice message that says the director is not found or directory not found exception was unhandled so it will create a data type of an instance of a data type called the directory not found exception and that that object will have information about the exception that we encountered and it will tell us and give us information about the issue couldn't find the directory okay so as a developer I can see this and I can fix the issue however as an end user you're not going to see this you're going to see something much more ugly and let me just go ahead and quickly build this and then I'm going to open up our projects go to gracefully handling exceptions and look in the bin directory and run the application and this is what a user would see they're going to get this ugly error message that says gracefully handling exceptions was stopped has stopped working a problem has caused the program to stop working correctly windows will close it and notify you if a solution is available and then it gives you all that error message stuff in the background right so it's a it's a pretty ugly situation for your end users you want to make sure that whenever you release the application to an end user that you are accounting for all the potential problems so that they never see that ugly error message pop up all right well we can do in when to kind of mitigate this is to take into account in our application anything that we don't have absolutely complete control over now we have control over writing lines to screens and reading lines okay that's not the issue with the issue here is is attempting to access a resource that we as programmers do not have access to or may not have complete access or control over so in those cases what we may want to do is to wrap a try around our our code that could potentially be an issue now I deleted a little bit here but I'm going to go ahead and put it back in and just leave it the way that it is and I'm also going to just take this dim content a string and I'm going to move it outside of the try catch put it right here and then just do content equals all right and now I'm going to run the application again and this time well we don't get any error messages at all but we don't get any results either because we know that there was an issue alright so we can improve this by giving a little bit of feedback and that's what the catch is for what we can do at a minimum is just go console dot right line there was a problem and this is the bare minimum we'll run the application at the very least we'll get the message this was a problem so we attempted we tried to execute this code in this code block but we encountered an exception and as a result of that I executed this code block okay and then we could continue on and at least the application didn't die I think we can improve this a little bit more though by telling the end user what the problem actually was so let's go ahead and then use this error object or this exception object that has been returned back to us so like I said before whenever an exception happens the dot net run time will create an instance of an exception object an exception is kind of the grandfather of all exception related issues we'll look at some others in just a moment and so every unless we specify a more specific exception it will always roll up to this exception object we can take a look at the properties of the exception object things like the inner exception the source the message and so let me just use the message and display that then to the end user now in a real application I might choose to log that exception into a log file so that we can diagnose the problem maybe I'll even take that message and send it if I can to a database where I as a developer can look at all the exceptions that have been thrown by the various users across all the users of my application and be able to proactively find bugs and fix them but in this case all we're going to do is just report the message of the exception to the end user whenever we encounter it so at least we're giving some feedback here could not find a part of the path and so if a very savvy user looked at this and said I wonder if that that exists on my file system they go and look for tests and they're like oh there's no test directory maybe I need to change the name of my directory or maybe I need to report this error okay I think we can even improve this a little bit more and if we were to take a look at this read all text method I hover my mouse cursor over it notice that it gives me a list of potential exceptions in below this alright so there's an argument exception there's argument no exception path to long exception directory not found exception IO exception and if we wanted to learn more about these we could just do actually copy this and then go and open up our browser and in MSDN I might go site Microsoft.com and then just paste in file.readall text that should bring me to the MSDN article for that particular method and let's see yeah here we go let's click on this version of it there were two versions of that method an overloaded version and this will show me how the how the method is declared but the most important part of this are the arguments the list of potential exceptions rather that can be thrown from this and why they would be thrown so for example file not found exception the reason why this happens is the file specified in the path was not found maybe the files in an invalid format maybe the user doesn't have the required permission maybe there was some sort of issue when attempting to open the file maybe the disk is corrupted maybe the directory was not found or it was inaccessible or maybe we just didn't pass in the right argument so there's a lot of possible exceptions here and as I'm looking through and understanding how to call this method I can then account for some of these possibilities so instead of catching just an exception what I can do is this catch ex as and then here I'll go directory not found exception and then we'll go console dot write line and I can give a very specific message here there was let's say we could not locate the c colon slash test directory please ensure that it exists alright so now we're giving very specific feedback to the end user by checking for the most specific exceptions first and then the most generic or general exceptions last let's go one step further from this if we found the directory but we didn't find the file so here we go catch ex as file not found exception console dot write line could not find locate the file test one dot txt in the directory c colon slash test please make sure the file exists so it's a little bit more specific here now what happens when I run the application well the directory not found error is going to fire first because it's going to first of all look for the directory before it attempts to look for the file itself but now let's go ahead and modify the contents of our c drive here well actually let's do this we don't have to modify anything there we'll change this to test and then we'll just change this to test for that file does not exist I'll go ahead and make the appropriate modifications here inside of the text just to make sure that everything looks correct okay so now we've got the directory correct but we're looking for a file that I know does not exist and this time we're going to give a descriptive error could not locate the file test four dot txt in the directory c colon slash test please make sure that that file exists alright very cool so the key here is to look for the most specific exceptions first and then the most general exceptions last or catch them in the order in which we know that they'll be performed we begin by catching the most specific which was the fact that we couldn't even find the directory and then we move on and say okay well next up can we find the file itself no well if it's not that then it could be one of a number of other issues as we see here as we hover our mouse cursor over but we'll just not account for those necessarily we'll just say there was an issue alright and let the user figure it out on his own alternatively we could go and implement a catch for every single one of those potential exceptions the last thing that I can do here is it's not really necessary in this case but I'm going to add a finally statement and so here you want to add any code that should execute no matter what so for example maybe you need to close database connections so that you're not you know you don't have a lock on a database file or close file connections for the same reason because you don't want to keep a lock on a file so that another application can't access it maybe you want to clean up any work that you've done previously and just make sure that it's adequately destroyed maybe you want to set your your values and maybe set content equals something like no data found maybe something like that see how what that will do alright so there we go not only do we print the error message but then finally we'll always execute no matter what of course that might be a problem if we actually did find the data so that might not be the best one maybe something like maybe to do an if statement so console dot write if content dot length equals zero then no data found otherwise just print out the content I was doing this off the top of my head hopefully it'll work so let's try that alright so that case it works let's see if we move this to test three it did not it didn't print it in that case oh it did it actually printed it a second time so maybe we just need to put nothing in that particular case alright that would probably be the better course of action so there you go we just get it printed one time instead of twice alright very good so as we look at the entire structure of this try catch finally and try block on the surface it might seem to make sense to you to just wrap your entire application in a try catch and frankly that's a little bit on the lazy side some developers have done that in the past but they often will be ostracized by their end users because you wind up doing something very cryptic like we did here where we just create a general exception because we're not taking the time to understand all the specific exceptions that can pop up and we just say there was a problem here you figure it out alright that's not advocating for the end user and typically whenever you do something like this you're going to be printing out messages that the .NET framework will generate they're intended to be understood by developers not end users and so you'll see some error message that no normal human would be expected to understand except for the guy who actually wrote the application so the reasons that developers do that and sometimes take that approach where they just wrap an entire page in a try catch is because you know they leave the exception handling to the very end the software development process and that leads to this catch all situation where you're just like oh we're pretty much done with the app I just need to wrap everything in a try catch and this is a lazy approach to just slapping some code up at the problem and hoping that it takes care of it but in the meantime when users run into issues it's maddening for them and very frustrating and I'm sure you've been there and you've seen those maddening error messages before you have no idea what to do next you want to try to avoid that as a software developer take pride in your code take the time to understand the kinds of exceptions that can happen ask yourself when you type in code what am I relying on here what are the potential problems that could pop up and account for them the way that I've done here in these but then also be reasonable you don't have to implement every single exception the ones that are probably the most likely all right so you should try to put the same amount of attention into protecting your user from having to guess what to do next or how to fix a problem if you the developer can fix the problem then and the end user doesn't even have to know about it then awesome that's what you should do but if you can't well then at least identify the exact problem like we've done here in these lines of code and then tell the user what they could do to try to diagnose the problem on their own and at least you'll help them from not feeling stupid the worst thing you can do is make a user feel like they've done something wrong or that they feel dumb whenever they're using your application that's what makes your application polished and it's what users expect a reliable experience no surprises tell them what they need to know in order to self-diagnose and fix problems all right so to recap in this lesson we talked about defensive coding through the use of the try catch and finally and end try statements and the plan for how to plan for the inevitable problems that will pop up during the execution of your application we talked about handling the special cases first and then moving on to any general cases last and we talked about the mindset of the conscientious developer who seeks to advocate and protect the end user from maybe losing data or even having to make tough choices or feeling dumb and not knowing what you're supposed to do next with your application so using this that catch all strategy and just trying to wrapping it around everything like just only using this catch ex as an exception and nothing else that's not an ideal it's not a perfect solution and you should strive to examine every part of your application that relies on some exterior resource that is not directly in your control as a developer and then apply the try catch and finally judiciously in those parts of your application so you see here that I'm not wrapping it around the right line the red line because I'm not expecting those parts of my application to fail only those parts that rely on something that I cannot control awesome we're making great progress and if you're still hanging in there with me you're doing great I'm so proud of you we're almost to the end don't give up now we're almost there so see in the next lesson thanks hi I'm bob taper with developer university for more my training videos for beginners please visit me at devu.com in this final tutorial video we're going to be discussing event driven programming event driven programming is really at the heart of most of Microsoft's presentation apis whether you're building web or windows applications and for that matter it's at the heart of just about every other api in the dotnet framework class library this allows you the developer to plug in and respond by handling key moments or key events in the life cycle of an applications execution so up to this point in our simple windows console applications there's really been only one event that occurs the application startup event which in turn triggers the sub main inside of our module one where we wrote the majority of our code in this course however in a modern user interface whether it be a native windows application or a web based application users can interact with various elements on a screen whether it be buttons or text boxes they can move their mouse cursor around and hover over elements they can press keys on the keyboard they can type text into into text fields they can drag and drop various elements around the user interface and so on and so a software developer will write code that responds to those interactions that they want to enable so a given component let's say a button it might define an event let's say it's the click event for a given button but it may have other events too like hover over or drag over but let's say we're only going to consider the click button event the developer says I want to write code that performs this business logic whenever somebody clicks on that button and whenever that button event that click event is raised then I want to handle that event write code that will respond to that event so the developer creates a method and attaches it registers it with that event and says hey whenever you happen let me know because I'd love to run some code whenever that button gets clicked so as the application is running the user interacts with the application eventually they click that button the .NET framework runtime raises the event and notifies any methods that were asked to be notified and it would then execute that code as well that's attached to the event and I'm going to show you how events are used in a very very simple Windows application near the end of this lesson but first I want to start with the absolute basics and I'm going to create a timer example and the great thing about a timer is that it has an elapsed event so you give it how many milliseconds you want to run before it says I finished elapsing I finished elapsing I finished elapsing alright so it'll keep doing that until you tell it to stop and so what we're going to do is write code that'll say whenever you finish elapsing I want to know about it because I'm going to write some code and we're going to do something interesting like write something to a console window alright so let's go ahead and get started here by creating a new project called understanding events and inside of the sub main what we'll do is start by creating a new system.timers.timer and I'm going to call it so dim timer as system.timers.timer and I'm going to pass in how many milliseconds I want it to run between each elapsed event that it will raise alright so in this case I want let's see new keyword I want a thousand milliseconds or one millisecond to elapsed between each raised elapsed event okay so what we could actually do is simplify this right by hitting control period and just simplify the name selecting that option actually simplify I could actually add an import statement but hopefully get the idea okay let's continue on next what I want to do is attach to the elapsed event or register a handler for the elapsed event so here's what I'll do um we're going to go and use the add handler keyword we use the name of the timer and then the event that we want to handle so elapsed comma and then what I want to do is give it the address of a method in the computer's memory okay so methods have in memory and we want to say hey whenever the elapsed event happens I want you to add a handler and then call out to that event in this address in the systems memory so here we're going to just create something called module one dot and we'll give it a name let's just call um elapsed one or tell you what handle the timer one alright and then I'm going to hit control period on my keyboard and one of the options is to generate a method called module one dot handle the timer one and notice that we created a method stub a private sub handle the timer one and notice that it automatically creates the correct method signature for the event so it's going to send two things to us it's going to send the object that created the event and then it will give us additional arguments that we can take a look at and one of those arguments will be something that will actually print off the screen now because it's generated code it adds this throw new not implemented exception let's go ahead and get rid of that because we don't need it right now instead let's do this let's go console dot right line and then inside of here we will do handle the timer one event and then I'm going to put in the our minute second and millisecond when the event was signaled or when the event was raised so we're going to use the sync signal time all right so the next thing we'll need to do now that we've wired up our event to occur whenever the timer lapses after a thousand milliseconds now will do is simply go timer dot start and we'll just keep running until somebody hits the console dot read line and hits enter on the keyboard and then we'll go timer dot stop and then we'll just exit out of the program all right so let's see how this works on the application all right and so you can see every second forty seven forty eight forty nine fifty fifty one we are hitting our handle the timer one event now what I can also do is wire up additional event handlers in fact I can have two five ten different handlers that say hey let me know to whenever you raise all right not just that guy I want to know to so you can add multiple event handlers for every single event and to demonstrate this let's just do this and add handler timer dot elapsed and this time will go address of module one dot handle the timer to a hit control period on the keyboard to generate the method handle the timer to and it adds it right here and I'll just copy what we did here and I'll paste it here except I'm going to rename this so we can clearly see it handle the timer to so let's run it and now we're going to get every second we will get to entries fifty two fifty three fifty four fifty five fifty six for handle the timer one and two and we could keep adding additional handlers for the elapsed event of the timer if we wanted to now what I can also do which is kind of interesting here let me write this console dot right line whoops right line press enter to stop handling both or stop raising or stop yet handling the event twice all right we'll just say that and then here what I'll do is just go timer dot start and console dot realign and timer dot stop and then in between here what I'll do is do this instead of add handler will move whoops remove handler timer dot elapsed and this will do the exact opposite this will say hey I have this method that we're currently calling in or whenever we've we hit the elapsed I want to stop calling it just just unregister it and it's no longer going to be used so as a handler for our elapsed event so here let's watch how this works so I can press enter to stop handling the event twice and right now I'm adding two entries every second so I'll hit enter and now we're back to only handling the event once okay all right so I say all of that to say this I wanted to show you how to respond to events how events work and the various parts of an event a object will declare and raise an event and then we as developers can attach our code or add handlers to the various events that are raised by objects and then write any custom code that we want to in response to those events we can also say no longer do I want my handler to handle that event instead I just want to remove it so it's no longer listening for that event all right so events are natural to every type of app that you'll build I think I said that already and to demonstrate this what I want to do is build a really simple hello world application using the windows presentation foundation API to build windows applications so let's do this I'm going to go file new project and we're just going to call this WPF events I'm going to select a WPF application that's important all right I'm going to call this WPF all righty and what I want to do and I'm not really prepared to talk about WPF there will be entire courses on Microsoft Virtual Academy that will explain what you need to know about it but all I really want to do here is just drag and drop a button and then drag and drop a label or actually a text block that would be better let's put a text block right below it okay I'm going to select the button and I might change its content and say click me all right and then in the text block I might change the text and remove it just make it empty by default but I want to rename it to my text block and I'll rename the button as well to my button something memorable all right all right now the next thing that I want to do is come over here to the properties window and I want to have make sure that I have the button selected on the design surface that I dragged and dropped from my toolbox and here I'm going to select the little electric lightning bolts thingy over here on the right hand side and this will show me all the available events for an object in this case make sure it says my button type button and then you'll see all of the events that this button can handle you see wow there's a ton of events yeah many of these you'll probably never ever need or use but the one that you'll always use is the click event so what I'm going to do is just inside of this little white area here I'm going to double click and when I do notice that it adds a my button underscore click event all right and here I could write my label or my text block in fact sorry dot text equals hello world and so let's run the application and we're just going to click the click me button and notice it says hello world now you might say well this wasn't very satisfying because I don't see anything similar to what we did previously where did it actually wire up the relationship between the button and the click event my button underscore click well let's do this I'm just going to go and select the form itself so the entire window all right just the entire visual area in fact I'm going to make sure to select just outside of that because if you select just the inner part it'll be a grid that's used for layout purposes I want to select just outside of it and make sure that the word window is visible then I want to go down to initialized and I want to make sure to double click it so it creates this window initialized handler and then what I'm going to do inside of there is go ahead and do add handler my button click comma address of and then we're going to go main window dot and we'll give it a name handle the event one just like we we called it before I'm going to hit control period on my keyboard and select generate the method and leave at one all right and we have to do something a little bit funky here so just stick with me private shared um let's just call this result as string all right and then here I'm going to need to put um set result equals um string dot format and then here we'll go uh happened at and then hh minutes seconds and milliseconds and we'll pass in date dot now all right let's see if that works and then what I'll do is uh show the results in here let's see if that works and you can see it works now the first time you click it nothing will happen because the very first time you click it result will be an empty string but then every subsequent time the handle the event one will have fired second and it will be populated with values okay now what we could do is just make it happen one time and then we could do something like this remove handler uh my button click address of uh module one or I'm sorry main window dot uh handle the event one see if that'll work uh it doesn't work we'll have to put that someplace else maybe here after the very first time there we go that should work so let's run it and now the first time we click it nothing happens the second time we click it nothing happens but then every subsequent time it does not change the the date or rather the time why because after we run through this block of code once we've removed this handler so it never updates the string result okay so hopefully that's as clear as mud uh there are some things there hopefully I know that it probably didn't make a lot of sense uh with regards to dragging and dropping items and modifying them and using the properties window but at a high level just understand that everything in dot net is event driven and so events are what move the action of the application forward and here we were just handling an event that's wired up automatically for us through the beauty of the Visual Studio IDE but we can take control of adding and removing events to or event handlers to specific events ourselves by using the add handler and remove handler keywords and pointing them to the address of methods that we implement in our source code alright so hopefully that's uh that's the uh one of the main takeaways the main takeaway really is that events are everywhere you look and that if you can dream up an action that you want your application to respond to your first thought should be what event should the application be responding to uh what should I be handling as the developer and then you do your research at MSDN Microsoft dot com to find uh the specific events for the given objects that you have in your web page or on your windows form and then you implement those uh using techniques that I demonstrated here okay so uh that pretty much wraps up all the instruction content I'll have a couple closing words in the next video and uh then uh you'll be finished so congratulations for seeing the net that next video thank you hey congratulations you did it you're awesome it's a huge accomplishment to make it all the way to the end of one of these long form uh video courses and so it's a huge accomplishment a feather in your cap congratulations you know whatever I look at the the views for uh a course that I've created uh typically see the first two or three videos have an enormous number of views and then it starts to drop off rapidly from there and I used to be concerned about that but the good folks in Microsoft Virtual Academy assured me that that happens with every course and I believe that everybody has the best of intention to follow through and see something to the end but then life gets in the way uh and there's distractions and changes in priority uh that will interrupt even the best of intentions and completely halt progress but that's not you you are able to push it all the way to the end and now you're well mastering visual basic or at least learning more about visual basic uh from this point maybe it's learning more about dot net in general or picking a user interface technology whether it be for web or windows applications learning how to access data from databases using dot nets data access APIs and more and I have a pretty strong feeling that before long you'll be uh you'll be ready to build your own applications whether for yourself or for a company that you work for but whatever the case might be congratulations you earned it but let me encourage you to not stop there keep pushing forward you have the momentum keep taking daily baby steps uh daily progress no matter how insignificant it might seem is how you make real improvements in your life and how you add skills and your skill set there's a little sign that I have in my in my closet over here it just reminds me uh of this fact it says what you do every day matters more than what you do once in a while so please take that to heart and just make sure every day you get your hands dirty in the code and you write some code every single day but this was a great first step you've taken a great step in the right direction and I'm proud of you and you did a great job so in this last video lesson I want to wrap up the series and provide a few suggestions about really what the next logical steps for you are as you learn more about .NET from this point on so I want to assure you that some of the ideas that I presented in this course especially the more advanced concepts that I hinted at or I briefly discussed like object-oriented programming working with collections link some of those sorts of things they could require weeks or months of thought work before your mind is really able to truly digest them I know I personally spent many hours just staring at the wall thinking about something that I'm trying to wrap my head around the mind needs quiet time to reflect and you need to put yourself in a position to succeed by giving your mind time to discover to ask the right questions to allow those little neurons to make those vital connections inside of your noggin so honestly there are things that I learned about 10 years ago that I'm still trying to wrap my head around that's the nature of this business and the complexity of software development it's easy and it's as hard as you want it to be so many times I often find myself needing to read many different blogs and books and watch many different videos and see what they have to say about a given topic before it really starts to finally resonate with me I like to hear it from many different authors not just one how I can use a particular technology how I can apply that technology each author talks or writes about a given topic saying things in a slightly different way and sometimes that finally unlocks the idea for me in my mind but ultimately I hope you realize that you don't really need to know every single thing there is to know about visual basic or about programming or .NET in order to be productive today right now you don't have to be an expert first to write software and to do something meaningful I mean many of the websites and the applications that you see that were you hear the stories about kids starting these in college whether it be Facebook you know they didn't have all the skills they needed before they started they acquired those skills as they went along so I encourage you to do the same sort of thing in fact some concepts may only make sense to you after you have more experience after you've made some mistakes and a good example that's object oriented program you really never know how useful that becomes until you've seen one or two or three projects collapse under their own weight and you think there's got to be a better way I've been approaching this all wrong so at this point you have a good basic knowledge a visual basic the programming language but there's still a lot of opportunity to practice and to grow from here so no matter what type of applications that you'll probably wind up building there are other few fundamental ideas that you really need to become familiar with to be productive as a software developer first of all you're probably going to want to learn how to work with relational database like SQL server you should learn how to access data that's been stored in a database how to add or create tables and rows to those tables how to design tables correctly you'll also want to you know learn some of the visual tools that are available to you in visual studio that can help you to drag and drop and configure your settings your settings and selections for your data access and your database and then you're going to want to quickly grow past that and rely less on the visual designers both for user interfaces for databases for the data access and grow past that and rely less on the visual designers and visual studio however those are a great crutch as you're getting started the next thing that you're going to want to do is choose a presentation technology to master so you have no lack of options fortunately or unfortunately depending on how you look at it including ASP.NET web forms and ASP.NET MVC core MVC the latest the latest version of that framework for building web applications then on the desktop side there are windows forms which is an older technology and then there's WPF which is a newer technology of course you can learn the universal windows platform which is the newest API for building windows store applications and then there's also tools that are available to you that allow you to write visual basic or C sharp and create applications for many different platforms like Xamarin for example to create cross platform apps that will run on iOS, Android and Windows phone and you know if you're not sure let me suggest that at the very least in my opinion you should learn HTML and CSS and JavaScript in the past those have traditionally been considered web technologies however I think you're going to see increasingly that there is this convergence between those two things where you can write web apps that can be compiled into mobile apps or you can write HTML that can be used as desktop applications so I would encourage you even if you don't plan on doing formal web development for a career you still need to know the lingua franca of the internet which is HTML, CSS and JavaScript and I've created several fundamental series on Microsoft's channel 9 and I believe they're also available on Microsoft Virtual Academy for each of those topics HTML, CSS, JavaScript, jQuery and so on and then I recommend you learn you get deeper into how to build applications the right way and so you look at topics related to application architecture particularly how do you format or how do you separate the concerns of your application splitting up your code into layers of responsibility and why you would even want to do something like that when you take the time to learn how to architect your applications correctly you're hoping to split up your code into logical layers of responsibility that will help you withstand the impact of change on the software system so change can come from many different places as you're building software whether it be from changing business requirements changes in technology, changes from defects in software and required bug fixes and so on but in each case you can mitigate the impact of change in making changes in your software and your code by encapsulating responsibilities behind well established APIs it's just a next step beyond some of the things that we talked about regarding encapsulation earlier in this course I spent a lot of time thinking and talking about that on my own website oh there it is right there, DevU and so I'll have the last plug for that here in just a moment but from application architecture you're going to want to learn more about basic software design patterns and tactics and techniques and so I'm going to give you a list of keywords that you're probably going to want to jot down and add to your to do list and frankly each of these could spawn a whole book or video series and I've already alluded to object oriented programming that's the biggie there's also object oriented analysis and design obviously those two go hand in hand and if you can just get your mind wrapped around that first that's a huge step in the right direction but beyond that you're going to want to learn about the principles and patterns that guide you towards writing code in an object oriented fashion so there's a set of principles known by the acronym SOLID which are a set of five principles that help you realize the promise of object oriented programming in your application you're also going to want to learn about workflow so specifically you're going to want to learn about working in a team environment with other software developers sharing code using the source code repository using a tool called get or visual studio online I think they call it visual studio team services now you're definitely going to want to learn about unit tests building unit tests these are tiny little code tests that are continually testing your code to make sure that what you wrote today you know a month from now still working as you make changes to your code and some people have even gone as far to say that you should be writing those tests first before you actually write the production code to satisfy those tests that's called test driven development or TDD you'll see it the acronym sometimes you're going to want to learn about agile project management agile software development techniques defining requirements in something called user stories playing planning poker in order to determine the amount of effort required for given tasks in a software iteration iteration using agile boards to manage tasks between software developers can ban boards can be and boards and you're going to want to learn about the nature of iterative development you want to learn about developing a spike of functionality all the way through the layers of the system an architectural spike that will then help all the members of your team understand more about the intended architecture and so that you can all speak the same language as you're beginning to work on a project together so I've given you probably a couple of dozen terms there that you could probably spend a year or two just looking up those and learning more about them and fortunately you don't have to know it all to get started you know it's only in the last few years that I've even learned some of those terms and I've been doing this for about 20 years now so unfortunately there's so much to learn there's so little time and you just have to decide to either go deep or go broad my advice to you is to go deep and learn as much as you can about one single platform and be an expert in that platform and Microsoft is a pretty safe bet because they've been around for a while they're continually tearing apart and rebuilding their frameworks to keep them modern and relevant and they have so many desktop installs their server technology their cloud based technology their web based technologies they're all state of the art so again if you want to bet your career on Microsoft that's a pretty safe bet now you know again so much to learn so little time it's a challenge for everybody you have to really commit and make your full-time job the job of learning I've had friends at Microsoft who have confided in me that it's a challenge for them just like everybody else nobody just knows all this stuff automatically because it keeps evolving and new ideas keep being thrown into the arena of ideas but this is what makes software development so fun and so challenging also a little daunting but at least you'll never get bored as a software developer you might get burnt out but you won't get bored and there's a bunch of great resources on the internet not the least of which is Microsoft Virtual Academy also Channel 9 great place to learn as well however one final plug if you're ever interested in learning about C sharp and more about .net more about architectural topics for software developers more about web-based development then you'll definitely want to check out my website developeruniversity at http colon slash devview.com that's designed specifically towards somebody who's a beginner helping them get up and running as fast as possible I spent a lot of time pointing out what I feel are the most important topics the key ideas that you need to master including homework exercises interaction with me be a Q&A and even I have a live service where you can we can chat a couple times a week over go to webinar and so check it out when you have a chance so as I close I hope you found this course to be valuable if there's anything that I can do to help you out let me know I'll try but most of all I wish you great success in your career good luck and thank you for watching