Main

C# Fundamentals for Beginners

Classic Throwback Series with Bob Tabor | Originally published in 2019 Install the latest version of Visual Studio at https://visualstudio.microsoft.com/?WT_mc_id=dotnet-58793-cxa and follow along at home too. C# is a powerful and widely used programming language that you can use to make websites, games, mobile apps, desktop apps and more with .NET. In this video, Bob Tabor shows you the tools, how to write code, debug features, explore customizations, and more. More and newer videos: https://dotnet.microsoft.com/en-us/learn/videos?WT.mc_id=dotnet-58793-cxa Free self-guided learning for .NET & C#: https://docs.microsoft.com/en-us/users/dotnet/collections/yz26f8y64n7k07?WT.mc_id=dotnet-58793-cxa Download .NET: https://dotnet.microsoft.com/en-us/download?WT.mc_id=dotnet-58793-cxa 00:00:00 – Start 00:00:09 – Course Introduction 00:08:08 – Installing Visual Studio While Bob uses Visual Studio 2015, you can install the latest version of Visual Studio at https://visualstudio.microsoft.com/?WT_mc_id=dotnet-58793-cxa and follow along at home too. 00:13:50 – Creating Your First C# Program 00:30:22 – Understanding Your First C# Program 00:47:24 – Working with Code Files, Projects, and Solutions 00:58:50 – Understanding Data Types and Variables 01:26:53 – The if Decision Statement 01:50:24 – Operators, Expressions, and Statements 02:05:36 – for Iteration Statement 02:24:04 – Understanding Arrays 02:41:42 – Defining and Calling Methods 03:12:51 – While Iteration Statement 03:30:54 – Working with Strings 03:54:24 – Working with Dates and Times 04:04:51 – Understanding Classes 04:28:47 – More About Classes and Methods 05:03:16 – Understanding Scope and Accessibility Modifiers 05:20:02 – Understanding Namespaces and Working with the .NET Class Library 05:37:46 – Creating and Adding References to Assemblies 05:58:06 – Working with Collections 06:21:21 – Working with LINQ 06:45:48 – Enumerations and the Switch Decision Statement 06:58:58 – Gracefully Handling Exceptions 07:20:02 – Understanding Events and Event-Driven Programming 07:40:58 – Where to Go from Here #CSharp #beginner

Microsoft Developer

2 years ago

>> I am Bob Tabor with Developer University, and I welcome you to this course covering the fundamentals of the C-sharp Programming Language and Programming topics in general. Designed specifically for absolute beginners to programming. Now, if you're already an experienced Software Developer coming from another Software development platform programming language, then frankly, this series of lessons will move much too slowly for you. You might be better served to find another resource to use as a
starting point. One with you the experienced beginner to C-sharp in mind and Microsoft Virtual Academy has many great courses designed for people and all skill levels, so I recommend that you start your search there. However, if you are completely new to programming and you're new to the C-sharp 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 C
-sharp, but I'm going to take the time to walk through everything that we do together. I'll explain what we're doing, but more importantly, I want to explain why we're doing it, the thought process behind it. I'm going to try to anticipate the questions you might have anticipate the problems that you might run into as you're typing your very first lines of code into the code window or as you're working through some of the exercises that we'll work through together. I've literally taught hundreds
of thousands people, maybe even millions of people C-sharp over the past 14 years. That's no exaggeration. This includes children as old as eight years old and as young as eight years old from virtually every corner of the world. They've all learned from a version of this course, and I know you can learn too. In fact, this is the sixth generation of this very course, dating all the way back to 2005. And over the years, I've incorporated feedback from thousands of students feedback and suggestio
ns on how to improve the course. I've incorporated those in an effort to make sure that this is the very best effort that I can put forward to help you get your feet well with C-sharp. Now I'll only make one real assumption as we begin this course, and that's that you already have some version in addition to Visual Studio already installed on your local computer and you're ready to write your very first lines of code. Now, if you don't already have Visual Studio installed, then please by all mea
ns, visit Visual Studio.com, where you'll learn about the many free and commercial editions of Visual Studio that are available. What the differences are. Now, personally, I used Visual Studio 2015 Community Edition, one of the free versions of Visual Studio that are available on Visual Studio.com, and I want to emphasize that you can use any additions and version of Visual Studio with these lessons. Now, there might be tiny User Interface differences between what you see on my screen and what y
ou see on your screen as you work through the videos. However, I'm not going to be focusing on any specific features of Visual Studio, so hopefully that won't prevent you from following along, no matter what. There will be other courses on Microsoft Virtual Academy that will demonstrate the power of Visual Studio, all the features that Visual Studio has to offer and explain the differences between editions and versions of Visual Studio. But I won't be focusing on that in this course. I'm going t
o focus specifically on the basics of the C-sharp Programming Language itself. And what I will demonstrate will be true no matter which version or edition of Visual Studio that you choose to use, and that's great news, because as long as C-sharp exists, these lessons should still be valid and useful to you, no matter what. So to get the most out of this course or any course that you find online, you really should become an active learner and that takes several different forms. First of all, you
should attempt to follow along closely and do what I call getting your hands dirty in the code. Actually writing the code that I'm writing on screen, you're writing it along with me. All right, there's no better way to learn how to code than actually write code yourself. It's like suggesting that somebody learn how to play the guitar without ever touching a guitar. You'd think, Well, that's virtually impossible. Typing in the code yourself will give you insights that merely watching videos won't
, so pause the video, rewind the video, re-watch portions of the videos as you need to. I'm going to make the code available for download, and you're welcome to it, and you can use that to compare the code that you write versus the code that I've written in the videos. But you really should be typing in everything on your own, in your own local copy of Visual Studio running on your desktop. Also, don't rush through this course. If something doesn't make sense again, pause the video. Rewind the v
ideo. Re-watch those portions that don't make complete sense at first. Sometimes a second or third viewing, focusing more specifically on what's going on around the screen and on the words that I'm saying can help. Being an active learner also means that you're taking control of the process of learning so if I say something or do something that doesn't completely make sense, by all means find a second or a third resource that can help you. Maybe it's an article out on msdn.Microsoft.com or other
videos on Channel nine or Microsoft Virtual Academy, but make sure you search out those resources that resonate well for you. If you're interested in even more comprehensive version of a C-sharp training course that covers a lot more ground in more depth, complete with dozens of coding challenges and over 30 hours of video instruction, then please visit my own website. Devu.com Developer University You'll also find many other training courses that I've created, designed specifically to help you
become a professional C- sharp developer someday. Furthermore, over time, as we go through this course and as I begin to fill questions about it, I might add some study resources and additional free content related to the topics in the course that you're currently watching right now. That's another reason to be sure to visit me at devu.com, now like I said earlier, if you're new to programming, I'm really excited for you. Learning to write applications is really one of my life's passions. It's
extremely gratifying to breathe life into your imagination and watch your creations come to life and watch other people actually then use your applications. You're embarking on a really exciting journey that's immersive. 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're at right now, and they might even be working professionally, writing code for a living or building real applications that are being sold in
App Stores like the Windows Store. If you've ever gotten stuck in the past when trying to learn how to program, I promise you that if you put in the time and you put in the effort and you work along with me as we work together, we're going to build the knowledge of C-sharp that you need to be well equipped to move on to more advanced tutorials where you can learn how to build your own Web Applications, Windows Applications, Windows Store Applications, Cloud Services, Video Games and even applic
ations that will run on iOS and Android using C-sharp. Now, assuming again that you have some version in addition to a Visual Studio already installed and you're ready to go, then we're going to begin writing C-sharp in the very next lesson. I hope you're excited because I really am. This is so much fun. Let's go ahead and get started. We'll see you there. 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 option 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 we
b 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 2017, to ensure that you're getting the packages and libraries that you need to create the applications you may wish to use. By selecting ''Custom'' and clicking on the ''Next'' button, we are now brought to the screen and we can sele
ct 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 Fsharp 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 Clas
ses and then windows XP support for C++. For my purposes, I'd like to have all of my programming languages available to me, because I create projects using the different languages all the time. I'm going to select ''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 ClickOnce Publishing Tools, SQL Server Data Tools, PowerShell Tools or Visual Studio, Silverlight Deve
lopment, 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 a Visual Studio, and then come back and Install the Windows 10 SDK at a later time, and that will include the tools, the SDK and the 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 toolset will be much larger. Again, depending on what it is that you want to do, you may want to select ''Universal Windows App Development Tool Kit'' PowerShell Tool 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 y
ou 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. Again remember, it will increase the size of the Install base for Visual Studio. You might also notice that because I se
lected 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 SDK, 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. 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. We can install Git, which is your source control, GitHub extension for Visual Studio, so that you can integrate with GitHub source control projects, and then an extensibility tools update three for Visual Studio as well. You'll notice that by selecting all of these options, set up can require up to 48 gigabytes across all of the drives that you will Install it on. Again, review each of the items that you have selected to ensure you have all the necessary compon
ents tools SDK for your development tools of choice or platforms of choice, and then select the ''Next'' button. Once you do, you basically see equipment or selected features screen that will tell you, all of the different items that you have selected, and by clicking ''Install'' you 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, clic
k the ''Install'' button in Visual Studio starts installing all of the components that you have selected. This is a quick overview, of how to perform a custom installation of Visual Studio 2015. >> 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 build a super simple C-sharp Application. I want you to follow along. It's a Hello World Application, meaning that we're merely going to print out the words
Hello World to a Console Window, and the point of this exercise is just to show you the basic workflow. I'm not going to attempt to even explain why we're doing what we're doing. The focus will be on, what I'm going to do next and how I'm doing it? In other words, I want you to focus on the basic workflow that'll be the same for all the applications we will build in this course, and pretty much every Application you'll ever build using C-sharp. Things like how to create a new project. Where do
you type in your C-sharp code? How do you test your application to make sure that it's running correctly, and what do you do whenever you have an error in your code? How do you save your project? Things of that nature. For now, just try to follow along. Don't worry if something doesn't make a lot of sense at this point, that's really what the rest of this course is for. In the next few lessons. After this one, we're going to dissect this tiny little application that we built, and I'm going to ex
plain at that point why we did what we did and then what does the code mean and why it's doing what it's doing. Just a quick reminder, like I said in the previous video, the introduction of this course, I'm going to assume that you have some version and some additional Visual Studio already Installed, even if your Visual Studio looks a little bit different than mine does on camera here. Don't be overly concerned about that. The basics are the same, no matter what, I promise. Let's go and get sta
rted here. To begin, we're going to create a new project. There are a number of different ways to do this, but I'm going to keep it simple and go to ''File'' ''New'' ''Project'' and selecting that menu option will open up the new project dialog. Now, chances are, the number of items that you see here in the center part will be dramatically different than the items that I see based on which version, in addition, a Visual Studio that you have installed. However, you should be able to select ''Temp
lates'' and then select ''C-sharp'', and one of the options should be a Console Application. I want you to select that, and then we're going to rename this project to HelloWorld. Now notice I use a little naming convention, where I use a capital H in Hello, and a capital W in world, and I don't use a space in between the two words. Now that's just the naming convention that I came up with to help me identify projects a little bit easier. Something I recommend that you follow. Shouldn't have to m
ake any other changes in this dialog. I'm going to go ahead and click the ''Okay'' button, and Visual Studio will go off and now create the starting point of a Console Window Application for us, and so now you should see in this main area, in this text area, a file opened called program dot.cs and there's some code here that is already generated for us boilerplate code. We're going to ignore most of that, except we're going to find this innermost set of Curly Braces. One of the first things you'
re going to need to do when you're learning how to develop Software is tell the difference between a parentheses, curly braces, square brackets, angle brackets and I don't know that I left out any. But here we want the curly braces look like little mustaches turned on their side. These are important, and I want to go inside of those two that opening and closing curly brace and make some room for ourselves. This is where we're going to type our code. It's approximately Line 13 and 14, at least in
my copy of Visual Studio. Then I'm going to type in the following, type in Console and you may notice now this little window pops up below what I'm typing. You can safely ignore that for now. Eventually, this becomes our best friend. But for now, it might be distracting and give it away to try to ignore it and type in everything by hand to the best of your ability. Console, and then I want to use the period on the keyboard, I'm going to call it the dot. Console dot, and then capital W Write cap
ital L Line. Next, I'm going to use an opening and closing parentheses, so that's not a curly brace. These are just the characters you'd use for a smiley face, and an emoticon. Then inside of there and use the arrow keys on my keyboard navigate around here. I'm going to go inside of the opening and closing parentheses, and I'm going to use two double quotes, so it should look like that. Make sure you don't use single quotation marks like that. That's not what we want. We want double quotation ma
rks like that, and inside of there, we're going to type in the words Hello and World. Make sure that you have an open parenthesis, a double quote, the words Hello World, then another double quote then another parenthesis, a closing parenthesis, and then at the very end of this line, I'm going to use a semicolon and it looks like that. It's not a colon and it's not a comma. It looks like that. Then I'm going to use the Enter key on the keyboard to go to the next line, I'm going to type in Console
.ReadLine opening and closing parentheses. Now you may have noticed that as you type in the opening parentheses that Visual Studio will automatically type in a closing one for you. You don't let that throw, you can continue just to type through that, but make sure that you have exactly what I've typed into my code window here for these two lines of code. Make sure that the capitalization is correct. Make sure that you're using a period not a comma for the little mark that comes after the word Co
nsole. Make sure you're using parentheses and not some other type of bracket, or brace, and then make sure that both lines of code end with a semicolon. The next thing that I want to do is save my project, and there are a number of different ways to do this in Visual Studio. Again, I keep it simple and go to File, Save all. Then the next thing I want to do is now see my application actually running. To do that, I can either find this little green triangle that has the word Start next to it or if
I don't see that by default in my little toolbar here at the top, I can go to Debug and select "Start Debugging." Either way should work. I'm going to go ahead and click that, and you'll notice that some windows pop up and Visual Studio changes its appearance a little bit. Now, off to the side of my screen, the console window popped up and we see the words, Hello World with a blinking cursor below it. I'm just going to hit the Enter key on my keyboard and then the console window disappears and
I'm back and the Visual Studio resets itself and we're successful. However, maybe your experience wasn't successful. Maybe you saw an error message, so what I want to do is take a moment and look at some common errors that people that are new to C-Sharp might run into and how to remedy them and this is a good opportunity to learn some of the syntax rules of C-Sharp as we make mistakes. I'm going to pause the video, make a mistake, and then we'll talk about it, pause it, and so on. When you attem
pted to start the application, you may have seen a little dialogue pop up from Visual Studio that says, "There were build errors. Would you like to continue and run the last successful build?" Always select no for that. What you'll see next is a list of errors. Now, in some cases, the error messages will be obvious to you, and they'll make a lot of sense. Sometimes they won't. Like the verbiage might be something we're just not familiar with yet. Invalid token and class structure interface, what
does that mean? Typically what you can just do is double click on these and that'll put your mouse cursor on the line where the problem is. Notice that Visual Studio also gives you another visual way to tell that there's a problem with your code. Gives you these little red squiggly lines. Sometimes you see a blue squiggly line. They're a little bit different but essentially this is an area of the code that probably deserves your attention, something you need to fix. Now, in this particular case
, the problem is that we didn't type our code in between the innermost opening and closing curly braces and so this is an issue with regards to defining a code block in C-Sharp or a block of code. Different C-Sharp commands belong in different kinds of code blocks, and I'm going to spend a lot of time in this course talking about the different types of code blocks and what belongs in each type of code block. But to remedy this issue, what you need to do is use your mouse and just drag and highli
ght these two lines, or you can use the Shift key on your keyboard in the arrow keys to highlight that area hit Control X, then move up in between the opening and closing curly brace and paste Control V that code in there, and then it should run correctly at that point. That teaches us the first thing about C-Sharp. It matters where we type our code. Or when you try to run the application you may have seen the same build error dialogue, except you see the message, "Semicolon expected." Hopefully
, this is an obvious remedy for you. If you double click on that error in the error list, it should take you to the end of the line of code where you forgot to add a semicolon. That's the second thing about C-Sharp that we're going to learn. Is that just like a properly formed English sentence has to end with a period or a question mark or an exclamation mark, a properly formed instruction in C-Sharp has to end with a semicolon, or maybe the error that you saw was something like a syntax error,
something expected, the name Hello doesn't exist in the current context. The name World doesn't exist in the current context. If you were to double click these, you'll get to the vicinity of the problem and you'll also see that there's red squiggly lines beneath the words Hello and World in between our parentheses. Now, remember, we needed to use double quotation marks around that string of characters Hello World and so alphanumeric characters that we want to literally write to screen, or presen
t in some way, we need to surround them with characters that indicate that we want to use this string of literal characters. To do that, we use double-quotes. Or perhaps you see the error, something like, "The name console does not exist in the current context." You look at the word and you say, well, looks spelled correctly. Remember that I told you you had to type exactly what I was typing and so C-Sharp is case sensitive, meaning that a lower case C and an upper case C mean that you're typing
two completely different things into C-Sharp and that is tricky because many of us are not used to that degree of precision whenever we're communicating. But when communicating with a computer, you have to be precise. In this case, all we needed to do was change the capitalization of the word console and we're back in business. Perhaps you see something like console does not contain a definition for either write line or read line, and again, you're looking at it and you're thinking it's spelled
correctly. Well, what could the problem be? Here again, capitalization is important. r read line is different than R read line, and l read line is different than L read line. Again, things have to be spelled correctly and have the correct capitalization in order to be processed correctly by the C-sharp compiler. We'll talk about compilation in the next lesson. Now, if you're not good at spelling and you're not good at typing in capitalization and you're just not as precise in the way that you w
ould type a letter or an e-mail message or even a text message, fortunately Visual Studio can help you out. There are tools that will help you not only write your code more quickly, but also more accurately. If you utilize those tools, the chances that you will miss some of these really simple syntax things like capitalization, will almost be completely eliminated. We'll talk about some of those tools in an upcoming lesson. All right, but assuming that you got all of this to work correctly, you'
re really well on your way to building applications, you've already crossed over one of the big first steps. As you undoubtedly learned in this lesson, writing C-sharp code is an exercise in precision. Again fortunately, the Visual Studio IDE will help you out a lot when it comes to that. It will give you clues and maybe some of the phrases in the words that they use to explain the issue might not be familiar to you. Yet with experience, it will be. But generally, it'll point you into the right
direction and with the red squiggly lines in the message, you can typically figure out what the issue is. Now throughout this course if you run into a wall and you simply can't figure out what the problem is, do this. Compare character by character, take your time until you develop a vision for the problems where your eye will jump to the problem and code. Compare what you wrote versus what I wrote. I'll supply the source code to you. Open it up in a second copy of Visual Studio and then just lo
ok character by character. What did I do different than what Bob did? That will usually help you figure things out if you can't do it on your own. In the following the lessons, we're going to focus on two things. First of all, we're going to talk about why we did what we did and what was going on behind the scenes that turned our code into a working application, all be it a small application. What happens whenever we create a new project? What happens whenever we choose to save our project? What
happens whenever we choose to start or run our applications? Then secondly, we're going to talk about the syntax of the C-sharp code that we wrote, and we'll learn more syntax rules and more keywords as we go along. If precision is so very important in C-sharp, then you're going to need to have some explanation as to what all those little words and symbols actually mean and some rules to guide you as you're writing your own code. It's really easy once you get a few of the basics under your belt
. Being completely honest, many people learn how to write code in C-sharp. It's a fairly easy language to learn, you can do this. Just you got to put a little bit of time, a little bit of effort to figure it out. We'll begin that process in the very next lesson. Will see you there, thanks. Hi, I'm Bob Tabor with Developer University. For more of my training videos for beginners, please visit me at devu.com. Now in this lesson, we want to start the process of dissecting that little application th
at we wrote in the previous lesson. Now previously, I wanted you to focus on the workflow. What we did and how we did it. But now what I want to do is focus on why we did what we did. It's really crucial at this point that we cement some really important ideas in your mind because they're going to provide the basis, the foundation for everything that comes next. What I want to do is start on the inside and work our way out. I'll start by talking about the nature of writing code. When you learn h
ow to write applications with C-sharp, really any programming language, learning the syntax of C-sharp or in other words learning the nouns and the verbs and the punctuation of the programming language is really just half the battle. The other half of the battle is learning about related, pre-built functionality that's available to the code that you write. Now in our case, Microsoft has created something called the .NET Framework, which sounds spooky and mysterious, but it's really not that bad.
It's actually pretty large, but we're only going to focus on two specific portions of it for our purposes. The first part that I want to focus on is something called the class library, which is simply just the library of code that Microsoft wrote to take care of difficult tasks so that, as software developers, we don't have to worry about them. There's library code to help with many common things that many applications will need, things like working with math, or working with strings and text,
and working with dates, manipulating dates and times, maybe displaying things to the computer screen or transmitting information across a network. A lot of that foundational stuff that would be difficult for us to write and is utilized by many different applications. That's really the first part. It's taking advantage and understanding the class library of the.NET Framework. The second part of the.NET Framework is called the runtime. It's also known as the common language runtime, you'll see it
called as the CLR as well. Really, it's just this protective bubble that wraps around your application. Your application lives inside of it. It runs inside of that protective bubble and it essentially takes care of a lot of the low level details so that you, the software developer, you can focus on what your application is supposed to do, not worry so much about how it's actually accomplishing it under the hood. You don't have to worry about the computer's operating system, interacting with it,
and interacting with memory, and interacting with the hardware, the computer itself. Many of those things are abstracted away from you. You don't have to worry about them. Furthermore, the seal are that runtime also provides a layer of protection for the end user so that you, the malicious evil software developer, you can't do something really bad to somebody's computer without them at least giving you permission to do it in the first place. So without their knowledge and their approval, you're
not going to be able to wipe out their entire hard drive, for example. For right now, it's the.NET Framework class library that I really want to focus on because it's what we used, whether you realize it or not, whenever we were writing our first application. For example in line 13 or 14 where we did our work, you see Console.WriteLine and then we used open parentheses, close parentheses, and so on. We were using code in the framework class library that knows how to display text into a console w
indow. All we got to do is say hey, use this text, stick it in a window. We don't really care how it does its job, we just care that it did it. The next line of code, this console.ReadLine. It was also really important. We're telling the application to wait for input from the end user before continuing its execution. Again, here we're calling code in the.NET Framework class library that knows how to accept user input. You recall that I use the "Enter" key in the keyboard, and then the applicatio
n continued on. It exited and we were back in the Visual Studio. So in both of those lines of code, we were utilizing methods that were created by somebody in Microsoft to handle that interaction with displaying and retrieving data from the end user. What were to happen if we were to comment out that line of code? Here to comment out of line of code, I use two forward slashes on my computer, it's over the question mark. Commenting our code simply means that I want those instructions to be ignore
d. Now, I could have just deleted that line of code completely, but I might want it later. Maybe I don't want to remove it completely, I just don't want to ignore it for now. I also might use code comments to write myself some notes to remind myself of something about the application in the future. We'll talk about code comments a little bit later. But if we were to run the application now, watch what happens. It ran and it's already done. What happened? Well, you may have seen a flicker on scre
en for a fraction of a second. The reason was because, hey, it executed this one line of code and it said looks like I'm done here, and it exits out of the application. By adding the read line, we're now stopping execution, waiting for the end user to do something before exiting out. Hopefully that makes sense. All right, so next let's talk about the position of the code that we wrote. I made sure to emphasize that you have to write the code in the correct place, and the correct place was in bet
ween the opening and closing curly braces of that innermost set of curly braces as defined by the level of indentation that we saw in the boilerplate code. If you don't add the code there, we saw what the ramification of that was. The application, you'll try to run it. It'll give you a runtime error. The correct place for that code was where we have it right now, in between that opening and closing curly brace that you see on screen. Now as you can see, there are several sets of curly braces, an
d so it's important that we talk about what these do. I need to oversimplify things here. We will come back and fill in some of the details later. But essentially, you have an opening and closing set of curly braces and those define the code block. Code blocks typically have names and they have purposes. In this particular case, we have a first code block and this code block has the name Main. This particular code block is known as a method, and this particular method by convention is the very f
irst method that's called whenever your application is executed. I don't want you to worry about these other words static and void and even the string and the args for right now, we'll talk about those later on. But this entire code block here, as well as the line above it, they define something called a method. A method is simply a block of code that has a name. Now, later on, you're going to come to realize that a method is so much more than that. But I want to use that as a working definition
as we're getting started here. The method has a name, and when you have a name, you can call a name and say, I want you to execute. We'll talk about methods again a little bit more a little while. This main method lives inside of another set of curly braces, and that set of curly braces also have a name. The name is program, it's a class called program. You can think of a class as simply a container for all of the methods of your application. You can keep the methods that are related to each ot
her in separate classes. Now what do I mean by related to each other? Well, that's really for you the developer to decide as you get deeper into programming, you're going to come to understand the thought process behind organizing your code. But that's a little ways off for now. Just trust me on that. Now I said that a class was merely a way to organize your methods. It is so much more than that. Again, I'm way over simplifying this as we're getting started here. But the main takeaway for right
now is that code is organized in curly brace containers and you have some blocks of code that reside inside of other blocks of code. To emphasize that again, here we have another set of curly braces, and this set of curly braces has a name as well. In fact, it's a namespace called HelloWorld, which happens to be the name of the application that we gave it. Again, key things extremely simple here a namespace is just another way of organizing code again. At some point it becomes so much more than
that, but let's keep it simple for now. Let's take a look at these lines of code and illustrate these ideas about classes that contain methods. Here what we're doing whenever we're calling Console.WriteLine is we're actually making a call into the dotNet Framework class library. Remember, it's that library of code supplied by Microsoft. We're saying in that entire library there's a book and there's a chapter inside of that book that I want to reference. In this case, we're saying, that book is t
he console book, the class. I want you to look at the chapter named WriteLine that has the definition for this method. Hopefully, that analogy works for you, but we're looking inside of a library to find a class, and we're going to call a particular method inside of that class. By using its name, we can execute all the code that was written inside of that method. Same with the method that we're calling below it as well. Notice that there is a period that we use between the name of the class and
the method name, and we use that. It's called a member accessor it allows us to access a member of the class or in other words, now that we know what the book is, we can find out what chapter we want to reference. Hopefully, that analogy works for you. Now, notice also that both whenever we call the WriteLine method and the ReadLine method, that they both have parentheses following them. Now, in the case of the WriteLine method, we're actually sticking something in between the opening and closin
g parentheses, whereas in the ReadLine method, we're not. But essentially, those parentheses are saying, not only do we want to reference that particular class method name, but the parentheses mean I want you to actually invoke it, execute it, do it now, so that's the purpose for those parentheses. Now we can say, do it now and pass in information. Do it now with this stuff, with this argument. We're passing in an argument to the WriteLine method and saying, we want you to do it right to screen
and here's what we want you to write. It's an input parameter to the method named WriteLine. Now don't worry, we're going to come back to the notion of methods in the future, as well as passing values into a method like we did and as we passed in the literal string HelloWorld into our method here. Just know that whenever you see parentheses after a given word in your code, you should be thinking that code is being called right now as we step through the execution of the code. Next up, let's talk
about the semicolon. We've already explained it in the previous video, but just to emphasize it. Notice that almost everything, even these statements at the very top have semicolons, with the exception or whenever we're defining a namespace, a class, or a method. We said at the time that the semicolons are actually similar to the period or exclamation mark or question mark at the end of an English sentence. It completes a thought in C-Sharp. Now, some programming languages like Visual Basic, fo
r example, they don't really have this idea. They only allow one complete thought per line of code. However, with C-Sharp, you could do this, what I'm about to do watch. Now I have both of those lines of code on a single line. If we run the application will work just as it did before. The way that you separate or indicate that you have two different complete thoughts, is through the use of a semicolon. Furthermore, we could put lines of code on separate lines like this. Now, it wouldn't make sen
se in this case because the line of code is so short, it actually makes it difficult to read. But sometimes when you have a very long line of code, you'll see me split that line of code into multiple lines, and still the application will execute. Now, in other programming languages, you wouldn't have that behavior. Because really whitespace in line feeds and things of that nature, they don't matter to C-Sharp. The only thing that really matters is to indicate a complete thought is a semicolon at
the end of the line. Let me go ahead and get rid of all that. The other thing that I want to mention here that you may have noticed is the level of indentation that you get automatically from Visual Studio. Now that's completely optional, and Visual Studio nudges you in the right direction. But essentially, even if you were to come out here and we'll use the tab key several times and write the word Console.WriteLine, something like that. Notice that Visual Studio reinvented it for us. Why do yo
u suppose it did that? Well, many people believe that indentation helps the readability of the code so that you can see what code container where code resides inside of the other curly braces inside of your application. Along those same lines for readability sake notice that there are many different colors that are used as text inside of this text editor window. You have these royal blue colors, and these are my default colors. Yours might look a little bit different, but by default, I think you
have some royal blue, some black. You have aqua color here. This is a dark red. You have some light gray and light blue. All of those are used to help you identify the parts of speech, I guess you can say inside of the code that you write. We'll talk more about that as we talk more about the syntax of C-Sharp in an upcoming lesson. Now that we've talked about the code that we wrote and its position and formatting and whitespace and tabs and all that stuff, what I want to do is stop right now fo
r this video and in the next one, I want to talk about the files themselves. The file that we typed our code into, how that relates to projects and even solutions. What happened when we saved our project? What happened when we actually ran our project? We'll do that in the very 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 EW.com. Next, we're going to talk about how code files are organized int
o projects and solutions. Then where you can actually find these projects and solutions on your hard drive. Whenever we created a new console project, the program does see a file was opened for us automatically in the main area in Visual Studio. That's one of the things that project templates do for us whenever we choose File, New Project and we see the new project dialog and we choose a project template. They provide a great starting point for the type of application that we want to build. It i
ncludes files with boilerplate code, important settings and other resources that we might need whenever we're building that type of application. As you can see, we're working inside of this file in the main area and there's a series of tabs. Again, this is an intended to be an overview of Visual Studio, but it's important to note that the names of the code files that you're working on are contained inside of those tabs. If you take a look over to the right hand side, here is the solution explore
r window. It has a tree like structure of all the items that are contained inside of our projects. Now again, as I said at the outset of this course, this isn't intended to provide a tour of Visual Studio per say. There are other resources on Microsoft Virtual Academy that can really help orient you to using Visual Studio in the various Windows and functionality that it contains, but the solution explorer is probably the most important part of Visual Studio next to this main area, where you'll u
sually see the text editor and other designer windows. Simply put, the solution explorer is our main navigational device to the other files and settings that comprise our program. You can see here that there is a program, that cs file. Now, if I were to close the program, that see us tab in the main area, I can always get back to it and open it up again by double clicking it inside the Solution Explorer. You can see it's open once again. The files and important settings are organized into a conc
ept called projects, so you can see here this word "Hello World" is actually a project. You can see there's a little C-sharp icon next to it, letting us know that this is a C-sharp project specifically. Projects get compiled into a single.Net assembly, which we'll talk about later. Furthermore, one or more projects are organized into solutions, and you can see in the Solution Explorer, we have one solution here at the very top solution also named HelloWorld that contains one project. Now, in man
y cases, as you're getting started, you're only going to have one project inside of one solution. But as you come to build more complex applications over time, it's highly likely that you're going to need to manage multiple projects that are somehow related. Now again, the reason might not be obvious at this point, but as you continue to learn C-sharp and how to build more complex applications for large companies or for yourself, this becomes a crucial code management strategy. But just for now,
accept the fact that there's this extra layer of a solution and one solution can contain one or more projects and the projects will contain then all of the code files in the settings and the like that will be used to create an actual executable program. Trust me, these concepts will become more important after we get past the basics. Now, the big question at this point should be, where are all these projects and solutions and files actually stored on your hard drive? I mean, can we see them? We
can see them in the Solution Explorer. Where are they actually on your hard drive? Well, when we created this "Hello World" project, we merely provided the name of the project, you'll recall. Then I said, go ahead and accept the other defaults. By default, Visual Studio will put your projects into your documents folder. If you take a look here and we navigate into the documents folder, it will put your projects into whatever version of Visual Studio you're currently using, so you can say I have
side by side Visual Studio 2013 and 2015. We're using 2015 for this series, but it could be a future version of Visual Studio. You'll look in that particular folder for your version of Visual Studio. As we drill in, there will be a projects folder and as you drill and you can see that by default, when we created a new project, it put it here in our document slash visual studio, whatever version slash projects folder. As I add more projects, this obviously will be filled up with folder names for
those projects. It's important to note that whenever you create a new project, you don't have to create it and put it right here. You can put it anywhere. To keep things organized, you're typically going to keep them in the same place. Now, furthermore, you can actually open up a project that saved anywhere on your computer as well. For example, in this course, I'll supply the projects. After I record the video, I'll zip them up and you'll be able to download them and then open them up on your
own hard drive and then walk through them and to better understand them. Just to demonstrate how you do this, I have this project zipped up into a file called example.zip. What I'm going to do is actually right click this and select Extract all, and then in the extract compressed zip folders. I'm just going to put this on my route. C;/Example, and then click "Extract". Now you can see that on my local hard drive I have an example folder. Inside of that folder there is another folder with a file
called Example.sln, I'll talk about that in just a moment. But I can either double click this.sln file to open up the the solution inside a visual studio, like so. Or I could go to "File", "Open", "Project/Solution", and then navigate to that directory using the open project dialog if it'll let me. Unfortunately, it's a little bit too large for the recording area, but then I would just simply select the solution that I wanted to open from this dialogue and then click the "Open" button. Let's go
ahead and close that, and let's shut down this copy of Visual Studio. I want to get back to where we were just a moment ago in our Documents, Visual Studio, in my case Visual Studio 2015 Project folder. Here are a list of all the solutions in our Project folder. Just want to walk our way through this. This first folder here will contain our solution files. There's this.sln file, which is a solution file that contains information about all the projects, that are under this umbrella solution. We c
ould actually open this up and look at it inside of notepad, and it's simply just a configuration file. There's nothing all that special about it. You certainly don't want to make any changes to it, but it's going to have information about all of the locations for the various projects that are associated with this solution, any global settings and some of these things won't really be useful to us until we get deeper into our understanding of compilation and things of that nature. But inside of t
he solution folder, is a second folder which is actually going to contain the project files. Here we have a HelloWorld.csproj, which is the C-sharp project file. Let's open that up as well with notepad. It'll contain references to things like all the files that are associated with this project, any of the settings and any other metadata. Again, information in here that you certainly don't want to edit, you don't want to accidentally make any changes to it whatsoever. But I just wanted to make yo
u aware of it, that there's really nothing magical going on. There's just these configuration files that contain information about your project. As you make settings on the project level, those will be saved inside of that cs project. Then finally, there's this bin folder here. The "Word" bin typically is short for binary, which denotes that this is where a binary version of your application will be stored. The process of compilation it takes your source code, which is human readable, and it's g
oing to convert it into a format that is machine readable, or understood by a machine, your computer. If we were to take a look inside of this folder, we would see that there is a debug folder. This folders created for us whenever we started debugging our application, it creates a temporary version of our application for debugging purposes, which we'll talk about later. If we drill into that you'll see that there is actually an executable file and several other helper files for the purpose of de
bugging. We'll talk about these later. If I were to double click the HelloWorld.exe, it actually executes our application. Compiling your code into a working application is the end goal. But I don't want to talk about compilation just too much yet or about creating a debug version versus a release version of your dotnet assembly of your compile code. I think you're going to get a better appreciation for those ideas, after we get past some more of the basics. What I want to do is stop our convers
ation about the directory right now. We'll come back to that a little bit later. But you're doing great. Let's continue on. We'll start learning more C-sharp now that we have some of these tangential topics all the way. I'll see in the next lesson. Thanks. Hey. I'm Bob Tabor with Developer University. For more my videos for beginners, please visit me at Devu.com. Now in this lesson, I want to get back in to talking about C-sharp the syntax. We're going to talk about declaring variables, how to c
hoose the right data type, for your new variable and then also how to initialize variables with values. To begin, let's take a look on screen. If you've ever taken an algebra course, hopefully you've seen something like this, where you're asked to solve for the value of x, and hopefully without a lot of thought, you're able to see that x equals 7. Using that same thought process, take a look at this little snippet of code on screen. x equals 7, y equals x plus 3. Then we're going to do a console
.WriteLine with the value of y. Hopefully you look at it for a moment, using your existing knowledge of algebra and you think to yourself, then it's going to output the value of 10 to a console window, right? Exactly. So my point is that C-sharp, first of all, is human readable. It's got a few things that might be a little formed like the semicolon at the end of the line. However, for the most part, I'm willing to bet that as we go through the series of lessons, you'll be able to understand what
the code is doing for the most part. Even before I explain it to you. It's really not that hard. Then secondly, it's probably very similar to things that you've done in the past like working with math and algebra and things of that nature. If we're looking at the C-sharp code, the x and the y in this context, are referred to as variables. A variable is simply under the hood, a bucket. I guess you could call it in the computer's memory and you put things in buckets and you dump things out of buc
kets. We can put values into a given bucket in the computer's memory, and we can retrieve the value out of that bucket. We can even replace what's in the bucket with something different. That is what you use a variable for. This particular situation that we see on screen, these buckets are just holding numeric values. However, we could create buckets that are just the right size for almost any type of information, whether it be individual alphanumeric characters, or strings of character, strings
of alphanumeric characters like even entire sentences and paragraphs, and even books. We can also create buckets that are just the right size for dates and times, buckets that are just the right size for really, really, really massive numbers, or even create buckets that are just the right size for numbers that have a lot of values after a decimal point. Now, in this case, what we would expect to see here is that these two buckets, the bucket that's labeled x and the bucket that's labeled y, wo
uld hold numeric values. Because we want to add numeric values together. We know that. But how do we express that intent in C-sharp? The instructions that we write in C-sharp were ultimately after a compilation step, they will ultimately be executed by the dotnet runtime that we learned about in a previous lesson. In part its responsibilities are to make sure to allocate memory for our variables in memory to hold the right kind of data. Here we have two data items, are x and y, and we have to te
ll the runtime that we want to allocate some space in memory that sufficiently large enough, to hold numeric data, like the type of data that we want to work with here and our application. But how do we do that? Well, that's the topic of this lesson. To get started, what we want to do is create a new project. Here again, I'm going to go to file, new project. We will go to the new project dialogue and make sure we select the Console Application project template. Here we're going to rename this an
d call this project variables and then click the "Okay" button. Visual Studio goes to work, uses that template and creates a new solution with a project and as you can see on screen here we are back in our familiar program.cs. Obviously we want to work inside of our static void main in between the opening and the closing curly brace just like we learned about in our previous lesson. Before we get started, there's one big takeaway from this lesson and that is that a variable is simply a bucket in
memory that you can put data into and retrieve data out of but we have to tell the compiler, we have to tell the.Net runtime what size of buckets that we want to create. We have to declare our variables, we have to create those buckets and then give them some label that we can refer to them with from that point on. Now, before we get started here typing some code, all the same rules apply in this video that applied previously. You have to type the code exactly the way that I type it. Take the t
ime, develop the skill of identifying even small differences, different in capitalization, or spacing, or the various special punctuation marks that we use while we're writing code. Develop that skill to identify the differences between what I write on screen and what you're writing in your copy of Visual Studio. If you see a little red squiggly line, you already know that there's going to be a problem there. That gives you the clue necessary to go and focus either on that exact character or in
that vicinity and use your detective skills to figure out what it is that went wrong. Now let's go ahead and we're going to create two buckets, two variables and define them in such a way that they're going to hold numeric values. We'll start with int x and int y as simple as that. Here to borrow the explanation that we used earlier, we are asking the.Net runtime to allocate space in our computer's memory sufficiently large enough to hold numeric values. Now, we're asking it to create these two
buckets and eventually we're going to put values into them and read values out of them but at this point we're just declaring their existence and saying, here's what we need to work with. Then after we've declared that, after we create them in this manner, then we can begin to work with them and assign values, retrieve values from them. But most importantly here I'm telling the computer that I want to assign integer values into those variables. An integer is really just a mathematical term that
refers to a whole number that's within a certain range. No values after the decimal point and as far as C-sharp is concerned, the values have to be between a negative two billion, 147 million and a positive two billion,147 million. That's the size of the bucket that we have to work with. If you need to work with much larger numbers then the in data type is not the correct data type for you, there are other data types to choose from and we'll learn about some of those a little bit later. If we ne
ed to work with like money values where you have dollars and cents or pounds and pence, then the integer is not the right data type to work with. Let's continue in our application and this is basically just to continue what we did in Notepad a few moments ago. X equals seven, y equals x plus 3, and then we want to do a console.write line with the value of y. Then remember we want to do a console that read line so we can actually see it on screen without it just flashing and going away immediatel
y. Let's run the application and make sure we get the value that we're expecting. Hopefully you got the value 10 in your copy of Visual Studio just like I got in mine. If not, again, make sure you double check your work against mine. After we declared the variables in lines 13 and 14, then in lines 16 and 17 I'm doing assignment using the equals sign. Now, in this case we don't really call it the equal sign, we call it the assignment operator. We'll learn about operators in the next couple of le
ssons. This particular operator, the equal sign means take whatever is on the right hand side and assign that into whatever is on the left hand side. We're going to say give me the value of seven and assign that to a variable, a bucket named x. The same thing would be true here with y, we're assigning a value into the bucket named y but we have to do something interesting here. We have to actually retrieve the value of x from memory. Where's that bucket again? Oh, there's the bucket, dumped the
value in the bucket out, you're holding the value seven. Add that to three and then we assign that to the value of y. Now, here we're retrieving the value of y saying, give me the bucket with y in it and you dump it out into the console.write line which we know, then we'll print that to screen and that's essentially assignment and retrieval of variables. This is a very simple case. What I want to do now is comment out this code. If I were to begin commenting out the code like we learned about in
a previous lesson, I could use the two forward slashes. I'm going to show you a different method in just a moment but notice when I do that, something interesting happens. I commented out the declaration for the variable named x. When I do that, notice these little red squiggly lines underneath x's and if I hold my mouse cursor there, it says the name x doesn't exist in the current context. We might say, well, there it is right there. It's in our code comment, but remember we're telling the the
C-sharp compiler and ultimately the .Net runtime to ignore that instruction. The compiler is looking at our code and saying, I have no idea what you're talking about X. I've never heard of X before, I don't know what you want me to do with X, and so it raises the red flag and say, I can't continue on under these conditions, you have to give me more information. Obviously we can fix it by removing the code comments. Now, what I want to do is comment out several lines of code and instead of just
doing two forward slashes in front of every line which can be laborious, I'm going to comment out multiple lines at the same time using a forward slash and a star character over the number 8 on your keyboard to begin a lengthy comment. Then right here before that read line, actually let's go ahead and keep it all together. After that I'm going to do a star forward slash. Now we're going to type another code example beneath that. This will be a little bit more interesting. Follow along. Pause the
video if you need to catch up with me, I'm going to try and type fast just to save time. Before I forget, let's go "File", "Save All". Now let's begin here at the top. You can see that this is a different style application with some different commands or different uses of commands that we're familiar with. We're just going to play a little name game and we're going to ask, what is your name, and we output type your first name. Now notice in the first case, I'm using a right line, which will pri
nt what is your name to screen and then use a line feed character to go to the next line. However, I'm using yet a third method from the console object, the console class, which we'll talk about classes and methods later. But this method is different than write line. This will just write out the statement type your first name, whatever's in between our double quotes there, and it won't go to the next line. It'll just wait there on that line. Then what we're going to do is create a new variable u
sing a different data type, a string data type. We're not interested in individual alphanumeric characters, so a-z, 1-0, and the special characters. We're interested in a string of them or a collection of those characters. So not just the individual character B, the individual character O, and the individual character B, we're interested in them as a string or a collection as Bob B-O-B. That's what we're declaring a bucket in the computer's memory sufficiently large enough to hold a string of ch
aracters, however long that it is. Then what I'm doing is calling our Console.ReadLine method that we're already familiar with. But there's a twist on this. Up to this point, we said we're using the ReadLine method in order to stop the execution of the application to wait for the user to hit the "Enter" key in their keyboard, then to resume. However, now we're using it for its real intent, which is to retrieve data from the end-user. In this case, we're asking the question, what's your name? The
user types it in and hits "Enter", and then whatever they typed in is assigned using the Assignment operator to the variable we created called first name. Hopefully, that makes sense. Now we're going to create a second variable of type string called my last name. We're going to do the same thing here, Console.Write, and then we're going to allow the user to type in their last name, and then whatever they type in when they hit the "Enter" key on their keyboard will be saved or assigned to the va
riable called myLastName. Now that we've done assignment to my first name and my last name, I'm merely going to concatenate the values together. Let me point something out. There are several things we need to talk about here. Notice here we were doing actual math where we were adding values together. This is the arithmetic or arithmetic operator. We're basically adding things together right here. We're kind of adding things together, but that connotation is different. We're not adding Hello and
Bob and Tabor with some spaces in there. From a mathematical perspective, we're concatenating strings of characters together to make one really long string. It's the same operator, but it's used in two slightly different contexts. Kind of does the same thing, but we need to understand that there's a fundamental difference in how operators interact with different data types. You'll see why this is important as we continue on through this course. But at the very end here we're expecting to see, He
llo, Bob, notice that I have in here a additional double quote with a space in between to give some space in between the first name in the last name, and then obviously, my last name here. We'll get that one more line of code to write because we need to do another read line so we can see the value on screen. Let's run the application. Then we have some things we want to talk about here. What is your name? Type first name Bob, Enter, type your last name, Tabor, Enter. Hello, Bob Tabor. Awesome, s
o very simple application, but hopefully, now we're pushing the envelope a little bit more, learning a little bit more about additional data types that we can use for our variables and learning about assignment that it works with all kinds of variables, and then also learning about operators that work differently with different data types. Now, before we get too far, in the previous example, we used merely X and Y, which we might expect to see in some mathematical context because we're used to s
eeing those characters used in algebra problems. But whenever we start writing business applications or even games, we need to give our variables names that are meaningful inside of the program that we're writing. I could have just called this x and then done something like this x and then done something like this x, and you'd look at this and you'd say, I have no idea what x is supposed to do. It's because we used a very vague description of the bucket in the computer's memory. Instead, you don
't have to worry about keystrokes, make it human-readable. Write your code in such a way that somebody can read through it and understand exactly what the variables are doing and what the logic of the application is doing. Then also notice as I go and change some of these things back here to my first name, I used a little feature of Visual Studio that allowed me to say, now that I have changed the name of x to first name, let me rename it everywhere that I've used the word x. Did you notice I di
d that? I hit the "Control" and the period on the keyboard here. Let's do that one more time. I'm going to change this back to x. Notice that I get a little light bulb here off to the left-hand side, which is Quick actions, and then I hit "Control" period on my keyboard. Now it gives me the option to rename my first name to x and it even off to the right-hand side shows me all of these changes. This is called a refactoring. I'm changing the code just ever so slightly by renaming things to give t
hem more meaning. In this case, I'm doing the exact opposite, but we'll come back to that. Do I want to rename every time I use the variable name, my first name to x? Yes, so let's rename everything bam just like that. Let's rename it one more time. So myFirstName, Control, period, and now I want to rename everything from x to myFirstName. You might look at that phrase, myFirstName, and then again, I used it down here, myLastName, and you're thinking yourself, that's a crazy naming convention. W
ell, it's a naming convention that's called camel casing, where you start with the first letter in a list of words that you're munching together to describe a variable or something along those lines. Use a lowercase for the first letter of the first word and then an uppercase letter for the second and subsequent words in variable name. Ideally, it makes it human readable. I can read it fairly easily that way. At this point, I think it's important also to do something like this. I'm going to rena
me this to myfirstname all lowercase. Remember what we said in the previous video that C# is a case sensitive language. So if you were to use the wrong capitalization, then you're going to get a red squiggly line and it says my first name does not exist in the current context. Do you remember seeing that just a moment ago when we removed the declaration for x up here when we commented it out? The same thing is true here. Myfirstname, all lowercase is different from the variable defined called my
F Name, First name. Capitalization matters. Make sure that you remember that. In this case, let's just go ahead and change everything back correctly, and we should be good to go again. Great. Now you might be saying to yourself, well, this degree of precision seems pretty difficult. How am I going to remember exactly what I named things in the past? There are a couple of different tricks for them. Keeping your code and methods small, and we'll talk about that later, that's one way to do it. But
then the other thing is to rely on IntelliSense, which is that little code window that I told you to ignore before. It's actually pretty important. As I start typing my, notice that it pops up beneath what I'm typing, the correct capitalization, correct spelling for any of the variables that I've defined up to this point that start with the letters m, y. Now, at this point, what I can do is simply hit the equals sign on my keyboard and it will type everything else out for me. So I don't have to
worry about spelling, I don't have to worry about capitalization. You may have noticed while I was typing, I was typing and then using arrow keys on my keyboard, and then you couldn't really see my fingers moving, but I wasn't typing every single keystroke. This is what allows software developers to write code very quickly. Once you get used to relying on IntelliSense, one of the tools that Visual Studio gives you in the text editor to make your typing more accurate and allow you to type much f
aster than maybe you normally could. We'll come back to IntelliSense later. The other thing that I wanted to tell you about here or talk about is that we cannot define the same variable two times. Let's try this. I'm going to go and view myFirstName and say I want another bucket in the computer's memory with the same name, myFirstName, and the compiler says, you can't do that. We've already got a bucket. We're going to confuse buckets in memory if we give two buckets the same name. it says a loc
al variable name, myFirstName, is already defined in this scope. You can't do that. Now we could do this, but I highly recommend you don't do that because, again, myfirstname all lowercase is different than my first name with camel case. But this would cause a high degree of confusion, so never do that. Be descriptive with your variable names, don't repeat variable names, always stick to a naming convention, and never break that rule. If you follow those little rules, I think you'll find some of
these initial issues they'll just dissipate, you won't have to worry about them. What I want to do now is take a look at this second set of code. Then not only are we in line number 29 declaring the variable, but then in line number 31, we're actually giving it a value. What if we were to rewrite this little passage of code? I'll go ahead and comment all of this out, and I'm going to make this smaller. In fact, here's one we'll do, string myLastName equals Console.ReadLine, and then I will say
above that Console.WriteLine, "Type your last name." You can see that I took these two lines of code 29 and 31 and I combined them together. What I'm doing here is not only declaring the variable, but then I'm initializing its value to whatever we retrieve when we call Read Line. This is called initialization, and initialization is important because you want to give your variables a value as quickly as possible. This puts your variable into what's called a, valid state, which will be an importan
t idea as we learn to write real applications. But also experienced developers like to write less code, and they're always looking for a convenient way to reduce the number of keystrokes that they have to type and reduce the amount of code that they have to read. Usually you want to declare your variables as you're using them and not declare them like some people used to do a long time ago, put them all at the very top of a given method or or section of code. You should get into the practice of
two things, declaring your variables as you need them in the body of your code, and then secondly, if you can, give them an initialized value immediately after you declare them, like we've done here in line number 34. Tell you what, let's stop right there. I think we've covered a lot of ground for one lesson. Let's do a quick recap and just talk about over a dozen things that we discussed. We talked about what a variable is. We talked about how to declare a variable, how to choose the correct da
ta type. We talked about the int data type and the string data type. We talked about assigning values into variables and then retrieving values out of variables. We talked about the assignment operator. We looked at the arithmetic operator and also the string concatenation operator, which is both just the plus sign. We looked at Console.Write versus Console.WriteLine. We looked at the other life of the Console.ReadLine method that we can actually retrieve the values that the user types in. We ta
lked about camel casing and naming conventions for our variables. We looked at IntelliSense. We talked about how to rename things, how to refactor our code using the little quick action. Remember the little light bulb that we could make changes to by hitting "Control" and "Period" on our keyboard, and then using our arrow keys to make selections and to rename all uses of our variable name throughout our entire code base. We probably talked about a lot more than that as well, but that's going to
wrap it up here and we'll start again 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. In this lesson, things are going to get a little bit more interesting. Based on user input, we're going to write logic to execute either one block of code or another block of code. When I use the term logic, I mean that we're going to make a decision and execute some code based on some condition
that could be the user's input from the keyboard, maybe the state of the computer system itself, maybe some of the data that we have access to are available to us, but somehow we're going to make a decision on whether to branch out and execute this code or execute this other code. Let's begin the way that we normally do by creating a new project, and I'm going to go to "File", "New", "Project". Make sure to choose a C-sharp Console application, and we'll call this project decisions and click "O
kay." What I want to do is we're going to create a little game and we're going to do it right here in static void main. I'm going to go ahead and start typing. You can pause. Try to catch up with me. Hopefully, most of this will make sense. Let's go ahead and run the application, and here we're going to play Bob's big giveaway and we can choose a door. What's behind door one, two or three? I'm going to choose what's behind door number one, and I said, hey, you won a new car. Awesome. Let's play
again, I'd like to win something else. Now we can type in the number two and, well, nothing really happens at all. I'm going to hit "Enter" again on a keyboard and the application just ends. We can try the same thing for three, but I suspect the same thing will happen with number two, and I can just type something randomly and again nothing really happens here. But let's start at the basics and talk about this if statement that we've created here, which is really the purpose of this lesson in th
e first place. The if statement is called the decision statement because we will decide whether to execute any of the code inside of this inner code block based on this evaluation that we're going to do after the if keyword. In this case, what we're doing is evaluating whatever the user typed in and we're gathering that from the Console.ReadLine like we learned in the previous lesson. The user typed something in then hit "Enter". We got that now and the user value variable. We want to perform an
evaluation to see if what the user typed in is equal to this literal string number one. Here's where hopefully, I want to call your attention to this, you can see that I'm using two equal signs next to each other. We already learned previously that a single equal sign is actually an assignment operator. We're assigning the value of whatever the user typed in, and in this case in the Console.ReadLine to the variable user value using this assignment operator. But whenever you use to equal signs n
ext to each other, you're going to do an evaluation for true or false. Whatever's inside of this opening and closing parentheses, we're going to perform an evaluation. Is user value in fact equal to the number one or rather the string character one, or is it not equal to the string character one? It can only be true or false. Based on that, if whatever the evaluation of that expression is, if it turns out to be true, then and only then will we perform the code defined in the code block immediate
ly after that if statement. If that's not true, if this turns out to be a false statement, then we'll just ignore whatever is inside of this code block and we'll continue the execution of our application to Line 23 and then beyond. That's how it works. But I tell you what, this is a very interesting example because obviously here we have we have no prize for door two or three. Then what happens if somebody just types in four, five, six or SDF or whatever on the keyboard? We need to account for a
ll of those scenarios in our application. Let me continue typing in some code here, and you can again pause the video if you need to to follow along. But we'll start by using an else if statement right below our code block for the if statement, so here we go. Let's stop right there for the moment, and you can see that in order to evaluate additional conditions, I can use the else if statements. In fact, I have two of them here. If this first evaluation is not true, then we'll continue on and do
a second and a third and maybe a fourth and fifth, how many other evaluations you want to do. However, if this is true, then will no longer run. Any of these additional checks will just continue on to line number 33, the same is true here. If this is not true, then we're going to evaluate this next expression. If this is true and we execute the code inside of the code block immediately following it, then we'll just go ahead and skip over this last else if statement and continue on to line number
33. If we were to run the application, let's go ahead and just quickly run through scenario number 2. Hey, we want a boat and scenario number 3, which obviously would allow us to win a cat, but then we still haven't accounted for the situation where we type in four or anything else, like the word or just random letters on the keyboard. Nothing really happens in those situations. What we really need is what I would call a catch all case. To do that, we'll just create an else statement below that
at the very end of our if else, if construct, and so here what we'll do is just that string message equals, sorry, we didn't understand, and then Console.Writeline(message). Now, we're catching every other case possible, no matter what the user types in. Let's go ahead and run the application. Again, I'll just type in some junk from the keyboard. Hit "Enter" and says, sorry, we didn't understand, and we continue on. That's how and if decision statement work. It also has these optional parts of
the else if and the else statements for either additional evaluations or what I call the catch all just in case none of the conditions are true. Now, there's a couple of things about this, and we're going to continue on to talk about one other type of decision operator that we can use a conditional operator. But before we do that, here's an opportunity to clean up our code. Let's look for areas where we've essentially got the same code repeated over and over and over again, and I can see a coupl
e of of instances where this is true. The first would be where we have this Console.Writeline(message). You see, we've repeated that in line 20, 25, 30 and 35. Wouldn't be great to keep our code a little smaller and only use that once at the very end of our evaluation. Like, put it right there outside of the if else, if else, decision statements. Let's go ahead and just remove those from there completely. But when we do that, notice that I'm getting a red squiggly line under the word message. Th
e name message doesn't exist in the current context. We're going to talk about scope and declaring variables inside of certain scopes and a little bit, but just to lead up to that conversation. Essentially, when we defined a variable inside of an inner scope, it's not available outside of that scope. In other words, if we define a variable inside of a code block, inside of the curly braces, it's only available inside of those curly braces not available outside of those curly braces. What we'll h
ave to do is define that message variable outside of our if statements so that it's accessible to all of the inner code blocks, as well as our Console.Writeline(message) here in line number 35. It's a very simple fix. We'll just do this. String message equals and then we'll just set it to an empty string to begin with. Now, you'll see a different message, a red squiggly line. But we've seen this before. You can't define the same variable twice, even if it's in an inner scope. What we'll do is ju
st say, instead of defining the variable message there, we'll just set our existing string variable called message to the value like so. Great. Now, our applications should run, we've eliminated a lot of code, and admittedly, I created a straw man here. I wrote more code than I needed to, but I wanted to illustrate this point. Again, if we were to run the application. It works correctly. But there's one other change that we can make. Code blocks as we're using them inside of, if else, if and els
e statements. If there's not more than one line of code to execute, then we don't even need to use the curly braces. In other words, since there's just one line of code here underneath my if statement, I can just remove it and make it small like that real compact. Same is true here, and same is true here. Now, in this case, maybe just to illustrate why you would need the opening closing curly braces if I were to do this message equals the message plus, you lose like so, and I'll even add a littl
e space here to make it look correct. Let's go ahead and test that else case just real quick, and I'll type anything in there and hit "Enter" and says, sorry, we didn't understand you lose. Notice that we were able to concatenate two strings together. I did it on two separate lines you don't really need to. But if I were to attempt to remove the opening and closing curly braces there, we're going to get a very different result when we run our applications. For example, if I hit "3", notice that
you want a new cut, you lose weight. Why did that happen? You want a new cut, but you lose. Well, there is no such thing as a free cut, but anyway, it's because what it's really seeing is this like that. If we want these two to be evaluated together inside the same code block, we have to include them in the same code block. Otherwise, this being outside of that code block will execute no matter which of these, if or else if conditions are true. Let's go ahead and put that back in there to illust
rate that idea. In fact, if we were to do something like this, I can even make this a little bit smaller. Let's comment that out, and I'm going to show you a new operator, which is just this. Now, instead of going message equals message plus you lose, essentially, I'm saying, give me whatever's in the variable message, concatenate on the word you lose, and then assign that into the variable message. That's what I did here. I just do it all in one step right there, where I say, whatever's in the
variable message on the end of that concatenate, you lose. This is the assignment and concatenation operator combined into one. Just a little shortcut there. Now let's do this. Let's talk about another style of decision statements. It's actually an operator called the conditional operator. This works well if you have an if or else scenario and you don't have multiple items to evaluate like we did here. I'm going to copy some code from lines 14-15 and line 16 too, I'll just copy all of those, and
we're going to paste them down below our command area. Then what I'm going to do is this. Will do this a little bit different this time. There we go. Now I've written a lot of extra code that I need to, I'm going to show you how to shorten this up in just a moment. Here, the key to this is this little evaluation that I'm doing on line number 42. Remember that we're going to evaluate anything in between the parentheses. Whenever we see the double equal sign, that means we're doing an evaluation.
Is the user value that they typed in and submitted through the previous line of code, line number 40, is that equal to the literal value 1? If this equates to true, then what we want to do is, everything after the question mark, we're going to take that value and assign it to our new variable called message. If the user types in one, will find the literal string boat and will assign it to the variable message. However, if this equates to false, so they type in something different, then anything
after the colon will be taken and assigned to the variable message, and we'll use that below. Let's go ahead and run the application, we'll run it twice. We can choose the door and if they choose door number 1, they win a boat. However, if we run the application a second time and we choose anything else, then you'll only win a strand of lint. Again, this is only useful in a if, else condition, not when you have multiple conditions to evaluate. Now, let's address this last little part here becau
se I can shorten this up considerably. Notice, in order to get it all to print out on one line, I only use Console.Write, then I typed out the literal string, and then I have a second line where I'm actually then printing out the actual message from line 42. Then finally, to add a period at the end, I'm having to do yet another Console.Write statement in order to add a period. I can shorten all that up in one line of code. Watch how I do this. In fact, let's go ahead. I'll comment out these line
s individually, like so. Then I'm going to use a replacement character inside of the Console.Write line in order to shorten this up a little bit. We'll use the WriteLine instead, and we'll fill you one a and then I'm going to use what I call a replacement code of zero. Then after I give it that literal string and you use a comma and then give it the actual message variable that I want. Whatever's inside of this, I want it replaced in here. Eliminate the curly braces with the zero and put the mes
sage variable value inside of there. Let's run the application again just to see this working. I'm gong to type number 1 and get the same result. Now, what if we wanted to expand on this idea here? Let me comment that out. What if I wanted to replace two values inside of that Console.WriteLine string? Let's do something like this. You entered and then we'll go 0. Therefore, you won a. In this case, after the comma, I'm going to enter the user value and then the message goes, make sure you can se
e that. Hopefully, you can see that on screen at one time. I need to do one little thing here, is change that to a 1. This says, take the first item. In software development, typically you don't start with the number 1, you start with the number 0. I don't know. We're going to see this pop up again and again. The first item in the list will be at element 0. The second item in the list will always be at element 1 and so on. The very first item, this will be matched and replaced by the very first
item in that comment a limited list of input parameters, after the literal string that little template that we've created for ourselves. Then here we're going to do a second replacement and replace that with whatever is inside of the message variable, when we run the application. We type in number 1. It said you entered 1; therefore, you won a boat. Awesome. That's enough for one lesson. Hopefully, you've learned a couple of important things in this lesson. First of all, we talked about the if d
ecision statement, as well as the else-if and the else, and how to do a comparison and evaluation between two values to determine true or false. If we're using an if statement and we're doing that evaluation, then the code that is in the code block below it will get executed if that evaluation is true. If it's not, it'll either drop down to a second subsequent evaluation or even do a catch-all in the else statement. We talked about using curly braces for a code block versus when you don't need t
hem. We talked about keeping your code nice and tidy and small. We talked about declaring variables inside of scope and inner scope and outer scope as defined by our curly braces for code blocks. We talked about the conditional operators, being able to all in one line do a check for true or false, and if it's true, assign one value versus a different value to a new variable. We talked about format codes inside of literal strings for our Console.Writeline and how to replace those replacement code
s with variable values that we then also pass in our Console.Writeline statement like you see here at the very bottom in line number 49. Again, we covered a lot of ground. Hopefully, this all makes sense, if not, rewatch the video, just watch those portions that didn't make sense. Make sure you're typing in the code yourself so that you can come to some of these epiphanies as you're typing. We'll pick it up in the next lesson. See you there. Thanks. Hi, I'm Bob Tabor with Developer University. F
or more of my training videos for beginners, please visit me at devu.com. In this lesson, I want to spend a bit more time talking about some smaller syntax elements of the C# language that you need to master to understand how a properly form line of code is constructed in C#. In one of the previous lessons, almost like the first lesson, I said something to the effect that just like you use a period or question mark or exclamation mark at the end of a sentence in English to complete a thought, yo
u also use a semicolon at the end of a line of code and C# to denote a complete thought. To extend that analogy a little bit, I may have briefly referred to C# syntax as having nouns and verbs. So I want to elaborate on these things and clarify what I mean by that in this lesson. I'm going to talk about the basic building blocks, and I guess you could say, parsing the parts of speech in C#. Let's start off at the beginning. Statements are what you call complete thoughts in C#. Typically, one lin
e of code. A statement is made up of one or more expressions and expressions are made up of one or more operators and operands, so we've seen a number of statements and expressions and operators and operands already, whether you realized it or not. As we're taking a look at some of the previous work that we've got here, I've got the variables project from a previous lesson opened up. For example, you can see that essentially each line of code is a statement. Each of them are made up of one or mo
re expressions. Here, for example, is an example expression. This happens to be a variable declaration statement made up of a operator, which in this case is a keyword Int for the data type integer, and then an operand, in this case, a variable name. We also use another operator, the semicolon for the end of the line of code. Another example would be here where we have an assignment where we're actually calling a method. Here is an operand. It is the name of a class, and we're using the open-clo
se parentheses. Remember, these are operators. This is the method invocation operator. Then we're using another operator here, the assignment operator, to assign the value of this expression to another operand, the name of the variable that we created. We were to look through the code, we could continue to parse out and understand what makes up operands, operators, expressions, and then entire code statements. Now, operands are similar to nouns. They are things like objects and classes and varia
bles and even literal values. These are the subject, I guess you could say, of your statement of code. They're pretty easy to remember because typically you give them names, you define the values yourself, and so on. Now operators are similar to verbs. They are things like the addition operator or the string concatenation operator. These are things that act on the operands in order to perform some action. Typically, you're going to use the built-in operators, although you could create your own o
perators. A little bit of an advanced topic, but there are actually quite a few built-in operators and you're going to need to memorize many of them. That's how you come to express yourself in C#. Fortunately, as you start out, you probably only need to know a handful to be productive. What I want to do in this lesson is to focus on a few that I think you're going to use probably 90 percent of the time as you begin learning and you can obviously add to that list as we continue. I'm going to actu
ally present these in a rapid-fire fashion. I created a very nonsensical application. You can open this up, download it from wherever you're currently watching this video or wherever you originally downloaded it from. I called this project OperatorsExpressionStatements, and the application itself does absolutely nothing meaningful at all. All it really does is show you some examples of the various operators and expressions that you'll come across whenever you're working in C#. At the very outset
here you can see that I have a variable declaration. We talked about this already. I did something a little bit different this time where I've declared several variables all upfront as integer. So x, y, a, and b are all defined as integers. Just wanted to show you something a little bit different there. By separating them with commas, it's an easy way to declare several variables of the same type, all on one line of code. I typically don't recommend this, but you might see this around in use in
books and on the Internet. Next up, assignment operator. We've already seen the equal sign at work in that capacity. Note here in line number 22 and following that there are actually many different mathematical operators. We're only looking at the most basic ones, but there are also some advanced ones as well. But here we have addition, subtraction, multiplication, and division. As I demonstrate here, you can use parentheses to actually change the order of operations. In this particular situati
on, the parenthesis is not a method invocation operator. It's actually how you would typically use it in an algebraic or mathematical sense. You would use it in order to specify the order of operations. So perform this expression first, then this expression, and then take the result of those two and multiply them together in that third expression and then assign them to the value of x. Then there are operators that are used to evaluate. We've already talked about the equality operator, where we'
re using two equal sign next to each other to make sure that these two items are in fact equal. Here, again, we're using parentheses in yet a different capacity to define the boundaries of our expression that will either equate to true or false. X equals Y is either true or false. We can use greater than we can use the less than operator. We can use greater than or equal to less than or equal to. All of these, again, should produce a true or false result. There are also two conditional operators
that can be used to expand or enhance an evaluation, and they can be combined together multiple times, as I say here in the comments, so I could ensure that both X is greater than Y is true and A is greater than B is true by using the logical and operator. There's also an or operator to say either X has to be greater than Y or A has to be greater than B in order for this outermost expression to be true. So here is the logical or two pipe characters next to each other. Then I guess we've already
talked about that in-line conditional operator where we have some item that's being evaluated. Then if it's true, then we'll take the first value and if it's false, then we'll take the second value. In this case, we're assigning either car or boat into this message variables value. Then also wanted to talk about member access and method and vocation. We're going to talk about object oriented programming quite a bit later on in this series of lessons, but we've already said how the console was a
class and classes are containers, for lack of a more robust definition, for methods. The way that you access a member method of a class or an object is by using the dot or the period that is the member access or operator. Furthermore, we talked about the method and vocation operator. Here we are, invoking a method called WrightLine by using the opening and closing parentheses. In this particular case, we're passing in an input parameter. Again, we want to hold off and talk about input parameter
s and methods a little bit later. But as you can see, here's a number of different operators, and these are just what I would call a very baseline set. You need to memorize these so that you can express the most basic of C# commands and understand exactly what it is that you're trying to do. It's not an exhaustive list by any stretch of the imagination, but you will probably need these about 90, 95 percent of the time. Then you can expand your vocabulary of other operators and keywords over time
. In each of these cases that we just looked at, an expression is made up of a combination of operands, which are things like the literal strings and variables and objects like the console class itself, and operators. Things like the addition operator, or shrink incantation operator, or equality assignment operators and so on. You use expressions then to form complete thoughts, statements in C#. Which are how the actions or the instructions of an application are expressed to the compiler and ult
imately to the.Net runtime, which executes your application. Why am I telling you-all of this? Why go through this little English lesson, passing out the different parts of speech if you've ever had to take an English class? Well, it will help you to understand why this is not a valid statement in C#. You can't just type x plus y and then give it a end of line character and expect it to do anything. The C# compiler will look at that and say, what are you trying to accomplish here? Have you lost
your mind? What do you want me to do with all this? Fortunately, in situations like these, as you can see, Visual Studio can catch these syntactical mistakes even before you attempt to run the application. If we were to hover our mouse cursor over the visual guidance here, the red squiggly line, you can see that the fundamental problem with this line of code is that only assignment, call, increment decrement, and new object expressions can be used as a statement. What's the problem here? Well, t
his is not a properly formed statement. We're not assigning, calling, incrementing, decrementing, or creating new object expressions. What? We're not formulating a complete thought, a good sentence. I could create an English sentence like this, the red ball. You would say the red ball does what? Who has the red ball? You can understand that just because you use words doesn't mean you're creating a complete thought or expression inside of the English language. Same thing is true with C#. That's a
ll I'm trying to say here. For beginners, understand that there's a proper syntax, just like there's a proper grammar in the English language. Understanding this is really a big step towards solving your own problems whenever you're phrasing C# instructions that the C# compiler will understand and accept and ultimately compile into code that will be run by the.NET framework. Here, let's recap what we talked about in this lesson. First of all, statements are complete instructions in C#. They cons
ist of expressions and a statement is like a sentence in the English language. Expressions are composed of things like nouns and verbs, in other words, operators and operands. The operands are things like nouns, they're the subject or what we want to do something with. Then there are the operators, which are more like the verbs. These will act on the nouns to perform some action. We said that operands are like variables and classes, literal strings. These are things that we get to name ourselves
. They give the meaning to our application where as operators are, for the most part, built into the language and we have to memorize them. To start off, you might use something like what I've given you here in the form of a project for a cheat sheet. But I think you might just be able to walk your way through and rationalize your way through. Now that you understand that there's a proper way to format a line of code, you might say, okay, what do I need to do here? You might be able to reason yo
ur way through the operands and the operators. I'm going to need a variable to contain some values. Once I have created that variable in memory, now I'm going to need to assign it to something now. How am I going to get to that something? I'm going to need to take another variable and this literal value, and I'm going to need to add them together with an operator. Hopefully you get the idea there. I hope that this was a useful exercise. I think it's useful for beginners to understand that there
are syntax rules, and they're not so unlike what you're already familiar with. Maybe they look a little bit different than your typical English sentence, but they still have to make sense and they have to perform an action or to do something. When you see errors, sometimes it's because you typed something incorrectly. Then sometimes is, you may not be using the right forms of speech in a sense in order to express that complete thought at C#. Let's pick it up in the next lesson, will see you ther
e. Thanks. 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 focus on iteration statements; a specific iteration statement called the forlteration statement. Sometimes you're going to need to loop or iterate through a sequence of things to find something that you're looking for, to find a successful match. Actually, you're going to do this data manipulation more than you realize. You'll have to t
rust me that this is a very important tool in your toolbox that you're building. As you can see, I've already taken the liberty of creating our project. I called it forlteration, pause the video, go through the steps that you already know how to perform to create a new console window project, and catch up with me. I'm going to begin to add some code here on line 13 in just a moment. Now, the syntax that we're going to write here in just a moment is possibly the most cryptic of anything that you'
ve seen yet. I'm going to be completely honest, sometimes I get things a little bit mixed up myself, but don't worry. After we struggle through it once or twice, I'm going to share the little secret that I used to get it perfect the first time, every time. Having warned you about the complexity of the syntax, I'm still betting that you could figure it out and read it even before we actually attempt to run the application, even before I take the time to explain what each little bit of the applica
tion is doing. Let me write it out here and then we'll try that. Very simple, at least very compact section of code here. Actually, you need one more line of code, Console.ReadLine. There we go. Now, ready for action. What do you think that this code does? Got a theory in mind? Well, let's go ahead and run the application and see if your theory is true. You can see that we have a list of numbers from 0-9 and then we can hit ''Enter'' to continue on. We're using C-sharp to execute this little blo
ck of code right here until a certain condition is true, at which point we will stop executing that line of code and continue on to line number 17. This for statement says that we should begin by declaring a variable. We're going to call it i. We could call it anything we want to, and we're going to initialize its value to zero. Now, as long as i is less than 10, we're going to continue to execute the code below it in our code block, defined by our curly braces. Each time that we iterate through
, we'll increment the value of i by one. This little bit right here is probably the part that you probably wouldn't completely understand unless I explained it. You remember how we use the plus equals sign in order to automatically take the value of message and add something to the end of it and then assign it back to the value of message? Remember that a couple of lessons ago? We're essentially doing that here. This is the the increment operator, so we're going to increment the value of i by on
e. Again, we're going to declare a variable and initialize the value. Then as long as this middle part is true, we'll execute the code below. Once we finish executing, then we will increment the value of i and then do that evaluation one more time. If it's still true, then we'll execute this code again. We'll increment i. If this is still true, we'll increment it again and so on.. That's how it works. Yes, this is cryptic syntax, but if you can just separate the three parts in your mind by remem
bering that there semicolons that separate them, that can help. You know you're going to need to start off with some counter of some sort. You're going to need a condition and then you're going to need an incremental at the end. Again, I'll show you a way to remember this so you never forget it. But before we do that, let me comment out this line of code and give you a variation on this idea. This would be fun. Here we go. You can see that I simply added inside of our code block for the for iter
ation statement, another if statement with its own code block inside of it. Here, we're checking the current value of i, and once we find something we're looking for where i is equal to 7, then what? We'll perform this code. What is this code do? Well, this part's obvious, but this break statement may not be so obvious. You use the break to bust out of or break out of the forlterations. We're going to make it to the value where i is seven, and then we're going to hit the break statement and then
we'll continue on to line number 23. Let's see it in action. It's not going to look all that exciting, but I got an idea. It found seven and it pretty much finished. I have an idea. Why don't we watch this execute line by line? To do that, we'll use the debugging tools inside of Visual Studio, which we have not even talked about up to this point, and yet is probably one of the most important features of using Visual Studio as opposed to just using a text editor and a command line compiler. To m
ake this work, what I'm going to do is actually set a breakpoint here on this line of code. Now, how did I do that? I just went to this left most column and I clicked in that gray column and it created a little red dot and off to the right hand side. You see that that whole line of code is outlined in red. There are, truth be told, a number of different ways to set a break point. Probably the easiest way to do it is is what I just showed you. But there's also keyboard shortcuts and there's menu
options as well. For example, with my blinking cursor online number 16, I'll go to the debug window and I'll select ''Toggle Breakpoint'. ' If we look over to the right hand side, you can also see that the F9 key will accomplish the same thing. Great. Now, let's go ahead and run the application and see what happens. Immediately the application pops up before anything can be printed out to the console Window, notice that we have paused the execution of our code and we're paused right here on this
breakpoint. Now, at this point, I can do a lot of cool things. First of all, I can see what my local variables values are currently. I can also change the value of those variables. I can monitor those values. I can change which line of code will get executed next and a bunch of other things. Now, this is not a series on debugging. I could easily spend an hour showing you a lot of cool little features. However, what I do want to do is call your attention to this little window at the bottom. Curr
ently, right now we're in what's called debug time, and with the application execution pause on this line of code, the next line of code that's going to execute is that line right there that's highlighted in yellow. I can look at these little windows like this locals window, for example, and you can see that the locals Window will contain any variables that are currently in scope at the moment. Obviously, args is something that we haven't talked about yet. Let's ignore that one. But what I want
to focus on is the value of i. Current value is zero. How do I know that? Because I'm looking here in the value column. I can also see what the data type of I is. It's an integer. I were to hover my mouse cursor over I you can see I'd be able to see it there as well. If I were to go and pin down that value, I'd be able to monitor it as well in this little helper window. In fact, I can drag it around here. Now watch what happens. Let me readjust some things here. I'm going to step through this li
ne of code. Now, there's a couple of different ways I can step through the code. I'm going to recommend that we only talk about step over for right now. When we learn about methods we can step into and step out of but for right now this middle button right here, the step over or the F10 key on your keyboard is what we want. I'm going to click it once and notice that we jumped from line number 16 to line number 22. Why was that? Well, the reason was because I was not equal to seven, so we didn't
execute the code inside of the code blocks underneath the if statement and we jumped to the end of the 'for' code block. Now let's continue just to step through this. You're going to see that we'll increment I by one. Now when we do that, notice what happen. The value of I change from zero to one, and that change is indicated by a change in color. Whenever you see the color red that means something changed in the previous line execution. The value of that variable changed from some of the value
now to the value of one. We can also see this in this little mini window right here as well. How it is now turned to the color red. Now that we've incremented, we're going to do the next check to see is I still less than 10. Here we're going to step one more time into our program. Here we're going to step and in the Line 14 which opens up our code block and we'll do another assessment is I currently the value of one equal to seven? No. So we'll jump out of that if block and continue on, and we c
an just continue through this exercise until we reach where I is equal to seven. Now, truth be told, I don't have to keep hitting the step over button. I can just use this continue button and this will just keep bringing me right back to the break point. This basically says, continue running until you hit another break point. Here at this point now I see that my I is equal to seven, and that's what I'm checking for. Things should get interesting right now. I'm going to go back to start stepping
line by line through my code. Here's where I hit the console that right line and if I look now on screen it actually did write that to the console window. Now I'm going to step to the next line of code and notice that it jumped out from the brake statement outside to line number 23 outside the 'for' statement to the console that read line we can hit continue from that point on. Our application is still running until we hit the enter key on the keyboard and then we've exited out. Very cool. Now,
you may have found it laborious to step through a number of times or even hit the continue button a number of times until we found just the right conditions. What we can do is make this break point into a conditional break point. To do that, I'm going to hover over the little red stop sign I guess you could call it in the left most column and I'm going to click this settings. Here this will open up a little break point settings window right in line in my code, it pushed all the other code down.
Notice that it goes from Line 16 here to Line 17 way below it. I'm going to add a condition. Whenever a conditional expression is true, then we'll break at that point. In our case, when I is in fact equal to seven, then we'll break on that break point. You can see that when I hit "Enter" on my keyboard, it's saved, and now I can close this. You can see that the little icon changed from just a red stop sign to having a white plus symbol inside of it. Now when we run the application notice that I
is seven and that I is seven in our little window here before we even stopped into our break point. Now we can continue stepping line by line through our code and continue on. We got our result, and we can continue on. Again, I could spend an entire hour just showing you other cool little features that will help you debug your applications but understanding how to set a break point, how to run your application to a break point, how to step through line by line and then how to resume, at least re
sume temporarily or continue by using the continue button. Those are the key concepts in debugging. In using the Visual Studio debugger. Now let's go ahead and it'll turn off this break point. From now on what I want to do is just eliminate it I can do that one of two ways. To completely turn it off, I can just click and it'll go away. Or I can temporarily disable it by using this little icon that was next to the gear that we clicked earlier. Now, you can see there's a little outline in the left
most column and an outline around the line of code that had the break point, but no longer are we actually going to break on that line. Let's do this. Underneath the 'for' statement from before but above the console that read line, I want to do what I promised to at the very outset which will show you a way a foolproof way that you can get the syntax right for a for iteration statement, and truth be told for just about anything else by using a little secret code snippets. It's not that much of
a secret but you probably didn't know about it, did you? To do this it's real easy. If you can remember I need a for iteration statement just type in the word for. You'll see that it pops up in the IntelliSense. If you look after the IntelliSense pops up a little message to the right there, code snippet for 'for' loop. Note: Tab twice to insert the 'for' snippet. Let's do it. Tab, tab, and there we go. Notice that it went ahead and pretty much set it all up although there are some parts that we'
re going to have to change like, for example, the length. I don't have to use the value I for my iteration statement as my placeholder, as my counter, whatever you want to call it. I could call something like my value and notice as I'm typing, and then I hit the tab here on my keyboard, it changed everywhere that was using the I variable label to my value. Very cool. Hitting tab also took us to the next spot in our code that we're going to need to replace, which was the length. Or in other words
, how many times should this 'for' loop iterate? I'm going to say we'll do it until my value is less than 12. Now, here again, we can use a number of different equality or inequality operators so we don't have to use the less than we could use the equal or we could use the greater than whatever makes sense for our application. But I want to keep simple and leave it just like that. Once I'm done making changes I can see the "Enter" on my keyboard. There were some highlighted areas that were highl
ighted in gold color that indicate that these are replacement areas that go away. Now my mouse cursor is right between the opening and closing curly braces and at this point then I can continue to create my application, write line, and then my value like so and then we can run our application and we would get the following results. Just to recap. It was a short lesson but we learned a lot. Not only did we talk about for iteration statements and why you might want them and we'll see them at use l
ater, but we also talked about the debugging tools just briefly, and how to step through a code, how to monitor the value of variables, how to use the break statement to bust out, to break out of a iteration statement. We looked at code snippets and how to replace values in a code snippet in order to make it our own. We'll use some of these techniques that we learned here throughout the rest of the series, very important video. Let's 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. In this lesson, we're going to talk about arrays, and I'm going to start by making a case for why you need arrays in the first place. Often you're going to need to work with several related variable values. But how do you work with multiple variables and treat them all as if they're part of the same group? Well, let me show you how not to do it. You can see an example of that on scree
n. First of all, I've taken the liberty of creating a project called understanding arrays, so make sure you catch up with me. Create a new console window application and you can just follow along. You don't need to type this part in. It's wrong anyway. You can see what I've done here. I need to keep track of five numbers, and I need these numbers to be related to each other, so without any better tools in my toolbox, I might just create something called Number 1, Number 2, Number 3, Number 4, an
d give them each a value. Now I want to find which variable holds the value of 16. I love to be able to loop through them like we learned about previously, to find which of the values hold Number 16, but I can't really do that. I'm forced to create an if else structure. As you can see here below, in order to ultimately find which variable has the value of 16 inside of it. This is not the right way to go about working with multiple values that are somehow related and you want to treat them as a g
roup. There's a better way and that, as you might assume, would be with arrays, so we comment all of this out. Previously I talked about a variable as being a bucket in the computer's memory that will hold some value. But let's expand our thinking about this for just a moment and talk about an array. Think of an array as like a bucket, or maybe even better, a tackle box. Ever seen one of those? If you go fishing, there's a lot of little compartments inside of it, and each one of those little com
partments can hold something. Usually a little worm or whatever the case might be. What if we were to use that instead of a bucket? What if we were to put values in each of those little tray areas inside of the tackle box and store that up in memory? Then whenever we needed a value out of that tackle box, we just need to take it and look through and find the particular compartment with what we're looking for, in order to work with it. That's the idea of an array, at least if you want to overexte
nd the bucket analogy. Another way to think of an array, it's a sequence of data, a collection of data, although I'm hesitant to use those specific terms, because they have very specific meanings in.NET. Think of it in a very general sense. You have a collection of data you want to keep together, how do you do it? Well, one of the ways you can do that is with an array. Let's do this and I'm going to go ahead and create my first array here. I want you to follow along and notice that I'm using squ
are brackets, I'm not using curly braces when I'm working here. First of all, let's take a look at the declaration of our array called numbers. It is an array of integers. In other words, there are going to be multiple integers all collected under this same umbrella named numbers. You can see that not only am I creating the declaration for this array, I'm also using an equal new in five. Some of this, like the equal in the new part, we're going to talk about what that really means a little bit l
ater. But for now, just accept it as how you go about creating an array. Then notice next to that, I have int and then inside the square brackets, I have the Number 5. So that's how many elements that I want inside of my new array. I want a new array of integers that can hold five integers inside of them. Next what I do is I begin to access each element of the array and put a value inside of that element of the array. Here's the 1st element of the array, the 2nd element of the array. Remember we
're zero based? Here's the 4th element of the array and the 5th element of the array. Five elements inside of the array, just like we defined here in line Number 31. Now what if we wanted to access the value inside of one of the elements of the array? Well, I would do something like this. It's a Console.WriteLine, obviously. Now what if I wanted to get to and print out the value that's in the 2nd element of the array? Well, then I would use the correct index of the array to access that element.
Here's the numbers, and I want the 2nd element, which means I'm going to use the Index 1. So I'm going index into that array to get to the correct element. In this case, the 2nd element is at index Number 1. I can print that off the screen and we do a read line here. Like so and we can quickly run the application. You can see that we are printing to screen the Number 8, which in fact is the 2nd element of our array. Now the other thing that we can do is actually determine how many items are in t
he array by looking at the length property of the array itself. Console.WriteLine, and I'll just go numbers.Length. Let's see what that will output. In fact, let me go ahead and comment that out and run the application. You can see that we're able to programmatically determine how many items are in the array by using the length property of the array. There's five elements inside the array. Great. Now what would happen if we were to attempt to insert data into another item, a 6th element of the a
rray? What do you suppose would happen here? Well, we'll try it. We'll run the application and you'll see that we get an exception and IndexOutOfRangeException was unhandled. In other words, we are outside of the boundary of the space that we defined inside of our array. We're trying to access compartments that were never created in the computer's memory inside of our little tackle box. In order to remedy this, we can either redefine our array at the time of declaration that we need actually six
items or we can go ahead and we can change at runtime, the number of items in our array. That's a little bit of an advanced topic. I don't want to talk about how you would go about doing that, but it is possible to do it programmatically at runtime. Let's move on from there, and let's talk about maybe a simpler approach to creating new arrays, and that is to not only declare the array, but then also initialize its values at the time of declaration. So let me comment out everything I have here a
nd we'll do this. Now, instead of giving it a specific size, we're going to let the compiler figure it out on its own. Because we're just going to start typing in the values of the elements that should be stored inside of our array. Now in this case, I can create it or just put all the items I want to put in there, and I can trust that the new array that will be created in memory will be able to hold all six items this time. Let me comment that out. We've been working specifically with integers,
but what if we were to work with strings? How would we go about doing that? Well, same idea here. In this case, we want to give it a number of literal strings. Like so, and so let me move this over a little bit. You can see that we are able to create an array of strings. We don't have to declare upfront how many elements we want in our new array, we'll let the compiler figure that out. It will create four items. Now there's a number of different ways that we can loop through to access each of t
he items in our array. Let me show you two ways, and one of them is going to be what you're already familiar with the for loop, right? I'm going to go for tap ''Tab'', and so we'll start with an integer I equals zero, and now let's do this instead of names dot Length. Right? Then inside of here we'll go and do this Console.WriteLine and we'll go names. What do you suppose we'll put in the middle here? We'll use the value I. So what we're going to do is start at zero and continue iterating throug
h until we reach the length of our array and then we'll stop and jump out of our array. But until then, we'll do a Console.ReadLine here, and you can see that this will allow us to print out all four items inside of our array to the Console window. Great. Now there's a lot of management of this, I hear, but there's an easier way to go about this. Let me comment this out real quick. I'm going to show you a second style of iteration statement. In this case, we'll just do this. We'll do foreach and
I'll go ahead and use the code Snippet. I'll just go tap ''Tab''. For each string name and names I made up the term Name as singular in Names is actually what we called our array right. So now I'm going to hit ''Enter'' on my keyboard twice and I'll just do Console.WriteLine name and let's go to Console.ReadLine. What this will do is it'll allow us to essentially loop through every single name in our array of names and for each item, it will copy the current element into this temporary variable
code name of type string. Then we can use that to do whatever we want. In this case, we're just going to print it off the screen so much easier, that is, but we can use either technique in order to iterate through our sequence of data. All right, now, let me show you one last thing you can do, it will be pretty powerful stuff and we can create arrays of different things. What if we wanted to take a string and reverse the string? How would we go about taking, for example, the name Bob Tabor and
reversing that to Robert Bob? How would I change that? Well, what we can do is take a string and convert it into an array of individual characters. Once we have an array of individual characters, we can then say, go ahead and reverse the order of those items so that the last becomes first. In the first becomes last, so let's do this, I'm going to I'm going to create a string called Zig, and it's going to contain one of my favorite speakers quotes that I have a patterned my life after ''You can g
et what you want out of life if you help enough other people get what they want." Now that's a very long line of code. What I would probably do is I would try to chop this up into multiple lines of code. We said this before that you can do something like this in C-sharp. All I'm doing is going to just break it in half and use this concatenation operator to marry the first string and the second string together, so that's all really one line of code. Now that I have this, what I want to do is crea
te an array of characters. I'm going to use the Char Keyword, which is the data type Char, meaning I want one character, but I'm going to create an array of characters called charArray, and then I take this zig string and I'm going to call a helper method on it called ToCharArray. Every data type has some helper methods that are built into it by the dot NET Framework. What this will simply do is take a long string and we'll split it up into individual characters and put those into an array of ch
aracters. Now that we have our statement here in an array of individual characters, I can do something like this. I'll call Array.Reverse and I'm going to pass in the character array. Then finally, what I want to do is we'll do a foreach tab tab for each char, and I'll just call this a ziglarchar in my charArray. Console.Write, not WriteLine, but just write, and the zigChar, hopefully all this makes sense. Let's do a Console.ReadLine. This is just to show you some of the flexibility of working w
ith arrays. Let's run the application and now we were able to write that whole string backwards. That's pretty much it. There's a lot more that you can do with arrays, however, and as we move through C-sharp, you're going to find that your use several arrays will diminish over time and you'll start using something a little bit more elegant. Think of it as an array on steroids, or maybe like Super Array. It's going to be called a collection. There's a bunch of different types of collections, and
we'll learn about those near the very end of the series of lessons. But at anyway, that's how you work with arrays. Remember that you have to declare an array by giving it at the time of declaration its size. Then you can access individual elements of array by using indexes into the array to access or to set the values in a given element of an array. We can loop through elements of an array using a four or a foreach iteration statement, and we can even use some cool utility methods like Array.Re
verse to swap all of the items in the array, or there's also ways to sort items and so on. Let's continue on the next lesson. We're doing great. See you there. 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 create and how to then call simple methods. Now, creating methods are going to help us with a number of different things as we write more interesting applications. Methods are going to
help us organize our code better. They're going to eliminate duplicate code and the need to copy something we did earlier and paste it later in our code base. They're going to allow us then to take a certain feature or functionality in our application and give it a name and then call it by its name anywhere in our application. Then if we were to ever need to update or fix an issue with our method, with that code that's encapsulated in a method we have to do one place instead of changing it every
where, we copied and pasted our code. Remember what we said at the very outset of this course that a method is merely a block of code as defined by curly braces, and it has a name, and since it has a name, we can call it by its name in order to invoke that code defined in its code block. Methods are actually one of the most important building blocks that we're going to learn in this course, and it will allow us to build more interesting and complex applications. This is definitely something that
we need to understand thoroughly. To begin, you'll notice that I've already created a project called Simple Method. Please take a moment, create a new console window project and catch up with me. What I'm going to do is build the most simple example. I can possibly imagine a simple ''Hello world'' application again, but this time using a method. We're going to define our helper method inside of our class program, because remember, we're going to keep methods inside of the context of a class. Re
lated methods go together in the same class, we'll expand on that later. But it should be outside of the definition of our previous method, the static void main. I'm going to go right to the end of the closing curly braces for static void main, and I'm going to hit ''Enter'' a couple of times on my keyboard that should put my mouse cursor after static void main's definition, but before the end of our class programs closing curly brace, so somewhere in this area is where we want to work. We have
to define things in the right place, just like we learned before, and here, let's create our first very simple helper method. That's all it takes. Now I'll explain the word private when we talk about accessibility modifiers and classes. We'll talk about the word static much later in this course. However, just to let you know, it has more to do with building console window applications than typically what you might find yourself using in a different style of application. But we'll talk about it l
ater. The void is something that's important. We'll talk about that in just a few moments here. I'm going to create a block of code and then I'm going to give it a name. In this case, the name is simple HelloWorld. Additionally, I'm going to give it an opening and closing parentheses and we'll look at what those are used for here in just a moment. However, then in the body, I'm simply going to just write any of the code that I need, my HelloWorld function to do. Now, in this case, one line of co
de very simple but hopefully you get the idea. Now how do I call that method? How do I execute it from my static void main? Well, remember it has a name and we can call it by its name in order to invoke it. But remember, there's one other piece of information that we need to provide here. Not only do we need to give it the name of the method that we want to invoke but also we need to use the method invocation operators which are the opening and closing parentheses in this context. Now we've call
ed our method and we expect output in the console window. Now I'm going to go ahead and add one more line of code just so we can see our result like we always do and now when we run our application, we will get the unexciting results, Hello world. But the most important part of this was to create the simplest example we possibly could. Now that you see how easy it is to create a method and how easy it is to call the method, let's go ahead and shut down that project. Instead, what I want you to d
o is open up the project and you should be able to find this where you're currently watching this video, wherever you originally downloaded from, there should be source code available. You should be able to find that source code in before folder for Lesson 10, copy that HelperMethods project folder into your project's directory or somewhere on your hard drive, and then you can open it up from there. I've already got this opened up here and you can see that I've created a simple name game applica
tion. Again, this is simple but at least there's more code that we can use to demonstrate how useful methods can be for us. It's going to ask us for our name and then where we were born and then we're going to use the little algorithm I guess you could call from the previous lesson where we learn how to take a string, how to convert it into an array of characters, how to reverse the order of each of the characters in the array and then display it back out to the console window. That's what we ha
ve here in our results, Oak Park Tabor Bob spelled backwards. Now, in order to accomplish this, I have what, from lines 13 to lines 56 so about 43 lines of code. Admittedly, I made this longer than it probably needs to be but notice the amount of duplicate code that I've introduced into the application. Here is where I am retrieving the first name and the last name and the city and those are essentially the same even though what I'm collecting is a little bit different but it's only two lines of
code so that doesn't hurt much. Here we are actually taking the first name or the last name or the city and we're going to do the reverse operation on it and we do that three times and there's the third one. Then what we're going to do is print out the results into a string called result which will then output in a console that right live. But notice here, we're essentially doing the same thing here and here and then again here so there's a lot of duplication. Now, duplicate code in and of itse
lf is not a huge problem, there's really no way you can completely eliminate duplicate code in your application but duplicate code is usually the result of copying and pasting code. You've invented the wheel earlier in your codebase and your first thought is, "Well, I'll just copy and paste it because I need it here and here and here in my code." Now, invariably what happens is your intent is to copy it but to make a few subtle changes to it and in your haste, frequently, at least if you're like
me, you will forget and you'll make a mistake and forget to change something and you've introduced a bug and it can steal your soul like even if it's just seconds. But what if it's minutes or even hours of your time trying to figure out why you have a weird problem with your application? Copy and paste is dangerous, you should always treat it with great suspicion. But in addition to that, if you have the same code repeated multiple times, then whenever there's a change that's requested in how o
ur application works, we're going to have to change it in multiple places. But what if we were to take some of this functionality like this, for example, and this, and we were to extract it out and put it into its own method and then just call it three times? First of all, it would reduce our need for copy and paste. If we needed to fix a problem with our code, we can do it in one place, and then also, if we were to give that method a meaningful name in our system, it would describe what we're a
ttempting to accomplish. Right now, we're just filtering through lines of code and it's a little bit more difficult to ascertain quickly what this application is attempting to do. But if we were to maybe give our methods nice meaningful names, it might read more like a paragraph of English instead of a bunch of disparate lines of C# code. So that's the goal. Now, the second reason we might want to break this up into methods is to simplify the readability of the code. We already talked about maki
ng it more human-readable but also, there's a lot of lines of code here that we have to pass through to understand what's going on and if we can reduce the amount of code to read, then we can improve the readability of our code. We want to reduce bloat every time we have the opportunity. We should strive to make our code readable, clean, clear, and perform well and maintainable so that if we need to make a change, we can do it in one place and methods help us accomplish all of those things. Let'
s do this. Let's create a method, we've already learned how to do that. I'm going to go somewhere between the end of our static void main but before the end of our program class, I'm going to define a private static void, ReverseString like so, and what I'll do is copy some of the work that we've done here, for example, lines 24 and 25 and I'll paste those here in our new method and then I'm going to copy the code that we used to actually print all these out to screen and I'll paste those here a
s well in our reverse string method. Now to get started here just to make sure that this method is going to work, I'm going to hard code the message. I'm going to create string message equals Hello world and then I will change firstName to just message throughout and firstNameArray to messageArray and we'll hit control period to rename like we learned about before. Then finally, what I could do is gather up all of the individual items printed out in reverse order using this foreach or I could ju
st go here and go Console.Write each item like so and that'll accomplish, at least for now, the same thing. Now that I have this working, I want to comment out everything I've done up to this point so that I can isolate, and then we'll start reintroducing things back in as we get them working. I'm going to call the reverse string method by using the name of the method and then also again, method invocation operator and then obviously the end of line character and I'm going to go ahead and hit "S
tart", and not a very exciting example but now we know that the logic of our reverse string method is working. What I'd really like to do is make this a reusable method. Currently, right now, it's not all that useful. How many times do I need a print Hello world in an application? But if I were to remove this line of code here and replace it with an input parameter so that the caller can pass in the string that it wants reversed, now I improve the usability of this method dramatically. To create
an input parameter, I need to give it a data type and then a moniker or a name. What I'll do is say, I'm going to allow the caller to pass in a string and internally I'm going to call that string message. I'm creating essentially a variable that allows an outside passage of code to pass values into the body of my method. I can utilize that value inside of my method and then hopefully as a result of that, achieve some more interesting results. Now, having done that, I've changed the signature of
the method. I used to have just a method called ReverseString but it accepted no input parameters but now I have to accept one input parameter and that's not optional so I get this red squiggly line beneath the reverse string and if I were to hover my mouse cursor over, it's going to say there's no argument given that it corresponds to the required form parameter message of, and you're like, "What does that mean?" Essentially, we did not call the method correctly now because we have to give it
something like a hardcoded string, or probably the better thing to do here would be to give it the first name that we collect way up here in lines number 16 and 17. Let me uncomment that out and go down here and comment. Now I'm collecting the first and last name of the city but everything else I'll leave commented out for now. Eventually, we'll remove them and I'm going to call this reverse string method three times. Each time I'm going to change what I'm passing in like so. Now when I run the
application, well, let's do this as well. Let me copy that so that I can get similar results. Let's go ahead and remove that and let's see the application now. Make sure you have what I have on screen, possibly if you need to. Let's run the application and let's see it working and it should work similar to what we had before with fewer lines of code. It mostly works but you notice there's a subtle problem with this. There's no space in between Oak Park, Tabor and Bob. This is a good example of w
here I can make a change one place in my code and it will fix the problem throughout the code base, wherever I'm using and calling my new method. To fix this problem, all I need to do is to cancel "Right" and then add in a blank character that should allow sufficient spacing in between each call to reverse string. Now when I run the application and I put in my details, Bob Tabor, Oak Park. It should work correctly and it does great. Now this is definitely one way to go about writing this applica
tion. As I look at this method reverse string I see a problem. Typically, whenever I create methods, I attempt to describe in English what that method is responsible for doing inside of my software system. In this case, I would describe the functionality of this method as it reverses a string and it prints it to screen. But herein lies the problem, I really only want each method to do one thing in my system and when I use the word and, and print it to screen, I feel like that's two responsibilit
ies in the system. Typically, what I would do is split this out into two separate methods and you might say, well, that's a little excessive, and that's true in the simple case. But following that rule of thumb will help you as you begin to think about how to compose methods, what goes into a method? How many methods should I write? Should I create one massive method or lots of tiny methods? Typically the answer is more smaller methods with descriptive names are better. In this case, what we're
going to do is change up the functionality of the application a little bit. What I'll do is take out all of this where I'm actually doing the writing to screen and what I want reverse string now to do is accept an input string and then return or report back, giving the result to the caller. In other words, right now we're using the void keyword, which means I want you to go off and do something, but please don't report back to me. I don't care what you have to say, I don't need to know anything
from you, you just go, you work, you be quiet and everything is great. However, we might want to change this and say instead of being quiet when you finish your job, I want you to report back to me what the results were of what you did. In this case, I might want to say return back to me the reversed string. I'm going to give you a string and then what I want you to return to me is a string that's been reversed. Notice when I added or changed void to string, I get a red squiggly line because I h
ave not officially returned anything back to the caller. I need to use the return keyword like so. I could do a for each and gather up each individual item into a longer string like we done, pretty much previously right here by building that result. However, there is an easy way to do this with just one line of code, just like there is a helper method called Reverse on the array class. There's also a string class, and the string class has helper methods too. One of them is the Concat method, and
it will allow us to pass in an array of individual characters and it will concatenate them all together and return back a full string. In this case, let's just give it the message array like so and that should work just fine. Now notice that I'm able to call reverse string and I'm not really accepting back any values. Why is that? I thought if we were going to say, Hey, report back to me that I would need to do something with it. In other words, I would expect to see something like this, where
I'm capturing whatever has been returned from the reverse string method. That's optional. I can listen for it and retrieve it and save it or do something with it, or I can ignore it. In this case, what I would probably want to do is actually save it, so I would call this reversed first name like so and then string reversed last name equals and then string reversed city equals. We'll shorten this up in a moment. But hopefully you'll see where I'm going with this. Then what I can do is console dot
right. Right line or just here, let's just do right. Reversed first name plus space. This seems laborious to do it this way. I've got a better idea the string has another helper method. We looked at the concat method, but it also has a format and the format will work a lot like canceled outright line. In fact, they're almost identical. The only difference is canceled outright line will print its results to screen whereas string dot format will merely just create a new string as a result of what
ever been formatted. But the reason I'm using this is so that I can use the replacement codes like so. Here I go 0, 1, 2 and I can pass in reversed first name, reversed last name, and reverse city like so. Since that is off to the right-hand side of my screen, I can't easily see it. Typically, what I'll do is move each of the input parameters to the method in this case console dotright. I'll move in the separate lines to increase the readability. Notice that they're indented a little bit. But th
is is all essentially one line of code, even though it's spread on four lines. But it improves readability because I don't want to have to scroll off to the right-hand side of the screen in order to read my work. Get in the habit of formatting your code for readability and keep things narrow and small. If they do go off to the side of the screen, don't be afraid to move things down to different lines to increase the readability. Now let's see what we have. This should work. Let's run the applica
tion. It works great. But what if I want to put this into its own method? I could simply do that like so. I think I can just use a void in this case. What I could do is go display results and I could just take this and paste it in. But now what I need to do is pass in these three values. How do I go about doing that? Well, know how to add input parameter. How do we add multiple input parameters? What we'll do is define our first one reversed first name like so then to add subsequent input parame
ters, I'll just use a comma on the keyboard and add the second one like so and then the third one like so. Again, since it's off to the right-hand side of the screen, I might put my mouse cursor right before the S in string and move those input parameters below the definition for our display result method again, for readability sake. You may not agree you don't have to. That's a stylistic choice. At this point, I should be able then to call display result. Let's call display result passing in th
e reversed first name. I just happened to use the same names here, but I could have called either the input parameter something different or the temporary variables here something different. Reverse string, last name and as I'm doing this, I'm beginning to think to myself, why am I even going through all of this? Why do I even need these variables can I just eliminate those altogether and just copy this? Paste it here. I mean, it returns a string. I should be able to do that and I should be able
to do this and I should be able to do this. Then I'll put the Mitch on the line and that should work just fine and here I can eliminate these lines of code completely for my application. See if it works. Still works great, feels like this should probably go into this display result. That should reduce it from being there. Now suppose that I don't want to pass in each of these individual values. What if I want to display the result and only pass in one value. What could I do in that case? Well,
I can provide additional ways of calling a method by creating what are called overloaded versions of our methods. In this case, what I'll simply do is I'll start out and copy and paste the exact same method definition twice. Notice on the second definition, I get an error. Let me hover my mouse cursor over so you can see it, type program. That's the class program already defines a member called display result with the same parameter types, you can create additional versions of the same method wi
th the same name, but they have to have a different methods signature. A method signature is the number in the data type of the input parameters in your method definition. In this case, I already have a method called display result with three strings. I could change these names to just any old gobbledygook text there, and I still get an error. It's the same problem because the fundamental fact that we've not changed the signature of the method means that I'm still having the same problem. Howeve
r, I could change this by allowing only a single message or a single string to be input as an input parameter. Now I have two completely different versions of the method as far as C-sharp is concerned. Now, in this case, I wouldn't need any of this. I probably just do this. Like so, and then I could call it by doing this. Basically what I was trying to avoid last time, but we'll go ahead and do it anyway. This time we're passing in one long string. Notice the use of the concatenation operator an
d the use of some empty spaces defined by two double quotes with just an empty space in between. We should have two lines that display essentially the same thing here. Let's make sure we do this right. Well, in a WriteLine between them just to make sure there's a break. Bob Tabor and we get two results that look identical. Now you might wonder why are we doing this? Why in the world would you ever want to create two methods with the exact same name that essentially do the same thing, but allow t
he user to pass in different information? Let me give you a good example of why you might want to do that is with the Console.WriteLine. Here we go with Console.WriteLine Have you ever noticed as you as you type the opening parentheses for the Method Invocation operator, that there's a little message that pops up down there, there's one of 19 and then you look to the right of it, and as I use the arrow keys on my keyboard to go up and down. Notice that the number goes one, two, three, four or fi
ve. These are all the different data types that the WriteLine method will accept, it'll accept an input parameter of type Boolean, which is true false. It'll accept a single character or an array of characters. It'll accept a decimal value, which is usually used for money or a double, which is used for longer mathematical calculations or a float, which is a massive number in terms of the number of values after the decimal point. It allows you to pass in an integer and other types of integer styl
e values. It allows you to pass in a string and then others as well 19 different versions of Console.WriteLine to make it convenient for the user of the application to utilize that method in their app for the developer, the application to use it in their app. Now when we go to display result, we'll see the same thing in IntelliSense display result and notice that I have two versions. I'm looking at version one of two, and notice the emphasis on the input parameter that the first version accepts
one input parameter of type string called message, and then the second version accepts three input parameters of type String, reverse String, reverse last name and reverse city. There you go. That is why you would create overloaded versions of your methods. Now, in this case, notice that we could eliminate so much of the code from this in order to essentially get the same working results, I'll just delete that, and, for the sake of simplicity, I'll go ahead and remove this as well. Now we've red
uced down the amount of code dramatically for our application and improved the flexibility of our application by adding multiple ways to actually display the results. At Developer University, I issue a decree to students that no method should have more than six lines of code in it, if it has more than six lines of code in it, then it's probably attempting to do too much in the system. You should be able again to express what it's doing in English and then if you find yourself saying it does this
and that, then it's probably an opportunity to split those up into multiple methods. Of course, rules are meant to be broken, and as a rule of thumb, six lines of code per method will keep your code tidy and readable. It'll keep everything scoped, nice and very tightly, and it'll improve the quality of your code dramatically. That's all I wanted to say about methods, but we're going to be using them from this point on. If there's anything about this that doesn't make a whole lot of sense to you
by all means, please make sure that you watch this lesson again or seek out some other resources. You're doing great. Let's continue on. See you in the next video. Thank you. Hi, I'm Bob Tabor with Developer University for more training videos for beginners, please visit me at w.com. In this lesson, we're going to look at another iteration statement, the while iteration statement. Let's just recap the iteration statements we've learned about up to this point. We've learned about the for loop or
the for iteration statement and it allowed us to iterate through a block of code a number of preset times based on a counter. Then we also learned about the for each iteration statement that allowed us to iterate through a block of code once per item in an array. Now, in both of these cases, ahead of time how many iterations or how many times to iterate through the given block of code but what if you didn't know up front how many times that you needed to iterate? Maybe you need to keep iteratin
g until some condition is met. In that case, you'll want to use the while iteration statement. Also, we'll take a look at the do-while iteration statement, which allows us to always iterate at least one time before breaking out of the iteration statement. We'll look at both of them in this lesson, and I'm trying to think of use cases where this would be useful. The most obvious one to me was creating some little menu system for our console window application. You've seen him before, especially i
f you've worked with DOS in the past. At any rate, what we want to do is begin with a new project you can see have already created it. It's called WhileIteration. Again, another console window application. Please pause the video. Catch up with me. When you're ready, let's go ahead and get started by creating a method that will print out a list of options to our users in the form of a menu. We'll do something like this. We have some more work to do here, but what we want to do is display this, so
let's just start by displaying the main menu here like so, and let's run the application. Here we can choose an option. No matter what we choose at this point, our display will disappear. But suppose that we wanted to actually kick off another feature of our application, so say, for example, let's go private static void of print numbers and then we'll go private static void guessing game, like this and it will just console.WriteLine. Now let's go ahead and call those from here. PrintNumbers and
then GuessingGame. Now let's run the application and we choose the first option and we're able to play the print numbers game. But when I hit "Enter" we are completely removed from the application. What if I wanted to return back to that main menu? How could I go about that? Well, I could use a while statement to determine whether to show the menu again or to completely exit out of the application. To make this work, what I'm going to do is start off with a new data type called bool, we referre
d to it briefly a moment ago. It's basically true or false. We want to create a new Boolean variable called displayMenu and we'll set its initial value equal to true. Now what we'll do is create a while statement. I'll just type in while, tap tab. What I'll say is while the display menu equals true, and then we will call display menu. Now a couple of things here. What we'll need to do is actually then retrieve back for main menu, a Boolean, whether the user clicked "Exit" or not. What we'll set
is displayMenu equals MainMenu and then have MainMenu return a bool itself. Of course, we've completely broken the application at this point. That's okay. Here we are going to continue to display the main menu until main menu returns the value false. If somebody chooses option number 3 to exit, then we might choose to completely exit the application, in which case we'll return false. Now, if they choose some other option, like 4 or 5 or 6 or some other text option, then you might just want to re
display the menu. We will return true again. Furthermore, we might want to return true as well here after we go through each of these options as well. Now let's go ahead and run the application and see how it works this time. First of all, if we choose option number 1, it'll display a message, and after we hit the "Enter" key in the keyboard, it will display the menu again and I can select number 2 and it'll display the message and then I can hit "Enter" and now we can hit the "Exit" and we actu
ally exit out of the application. What the while statement allowed us to do in this case is check for a condition and when that condition is true, then we can break out of the while loop. Otherwise, we're going to keep executing the code inside of our code block. Now what we can do here is actually shorten this up a little bit. We don't need to say, while displayMenu equals true, remember that just like when we're using the if statement or the else if, we want to evaluate an expression and if an
expression is true, then we want to either execute that block of code below it or not. In this case, if displayMenu is already true or if it's false, we don't need to actually do this evaluation. It already evaluates to true or false. We don't have to do an equality there or check for equality. It's either true or false, and so we can just write it like that very simply. Moving on. Now, what we want to do is maybe fill in the gap on some of these other little games we have here. Let's play the
print the numbers game. In order to do that, let's go ahead and say Console.Write, type a number, and then int results equals Console.ReadLine. That's going to return back a string, but what we really want is an integer. I'm going to go integer.Parse and this will allow us to take whatever string has been returned and convert it into an integer. Now we should have the actual integer value. Here what will do is create a counter for ourselves. Int counter equals 1 and then we'll go while tap tab,
the counter is less than our results. Then we will do a Console.Write with the current value counter. We'll go Console.Write and we'll do a little delimiter and then we'll increase the counter. Now there's a tiny bug with the application. We will come back to that in just a moment here. But let's go ahead and run the application and let's go ahead let's type in a number 5 and it types in, and it will print out the numbers 1, 2, 3, 4. We're able to change the number of times on the fly that will
iterate through a block of code. Now it just so happens that this isn't exactly what we wanted. Let me exit out of this. What we really wanted was to display from 1-5. I'm going to go ahead and add result plus 1. If I typed in the number 5, this would actually make this value 6. As long as we're less than six, go ahead and continue to execute these lines of code. But once this statement becomes false, once the counter if it's equal to 6, it will break out and will hit this line of code here in l
ine number 59, the Console.ReadLine. That should work. Now, the other thing that I noticed when we ran the application is that we keep seeing additional data being written to the window. I might want to clear out everything that's been displayed so far. Here we'll start at the top and do Console.Clear, and that should clear off the screen for us. I'll just copy and paste that here to print numbers as well. When we run the application again, this time I'm going to choose option number 1, and noti
ce that it cleared off the screen and when the print numbers game, I'm going to type the number, let's go 4, it types out 1, 2, 3, 4. I hit "Enter" it clears that off and it displays the menu again. Awesome. The next thing I want to do is play the guessing game. Again, here I'm going to go ahead and clear off everything that's currently on the screen. What I want to do is choose a random number and then I'm going to allow the end-user who's playing the game to try and guess the number between on
e and 10. How do I create a random number in C-Sharp? We actually use this built-in class in the Dunnett from the class library called the random class. We'll create a new instance of the random class, we'll talk about what that means, create an instance of a class, in an upcoming lesson. Let me do this. We'll go random, my random equals new random. Again, that should make no sense to you whatsoever. That's just fine. I'll explain what that actually did in an upcoming class when we talk about cl
asses. I want to get a random number from my random class, so I'm going to call the next method, and here one of the overloaded versions is that I get to give it a minimum value and a maximum value. The minimum value will be 1, but the maximum value, I want it to be 10. I'm going to say, don't let it be more than 10. In other words, 11 is out of bounds. Now that I have a random number, I'm going to also keep track of how many guesses the player has guessed up to this point. Then I want to also k
eep track of whether or not the user was correct or not. Incorrect, and we're going to say it is true that they were incorrect. Now watch this, I'm going to create a do while statement. I want the block of code that I'm going to create execute at least one time. That's why I'm going to choose the do while as opposed to the while. The while we'll evaluate the very first time and we may never actually run the code inside of our code block, but this time I want it to run at least one time. We'll sa
y, do this, but then at the very end, we'll check for the statement while. If the while condition is true, then we can break out of it. While we continue to be incorrect is true. While we continue to be incorrect, then we're going to keep guessing. Let's start this Console.WriteLine and we'll say, guess the number between one and 10. We want to retrieve that number. The string result equals Console.ReadLine. Now that we have it, we can do an evaluation. If the result is equal to the random numbe
r, so if whatever the user typed in is equal to the random number that we generated, then we want to break out of the wild statements so we're no longer incorrect. In other words, let's go ahead and say that incorrect equal to false. At this point, we guessed correctly and we'll break out of the wild statement, and here we would want to say Console.WriteLine. Hey, you did it correct. However if they did not guess correctly, then what we would want to do is write Console.WriteLine and then wrong.
We probably want them to guess again, which will happen because while incorrect is still true, then we'll come and we'll re-execute this block of code. Looks like a missing end of line character here. I can see that as I hover my mouse cursor over that little red area that I forgot a semicolon there. Otherwise, this should work. Now there's one of the things that I want to do. I want to keep track of the number of guesses. Each time the user adds a guess, we've already initialized that value th
ere, that variable guesses. I'm going to increase guesses or increment guesses by one. I type in the word guesses plus plus. That means I want to add one to the current value of guesses. Then here I want to type out how many times it took. It took you guesses, then like so. Let's run the application. Let's choose to guess a number between one and 10. We'll start off at three. You can see it says it's wrong, so I could continue to guess a number between one and 10. Let's go 4, 5, 6, 7, 8. The num
ber was eight. It took me six guesses to get to that. Now when I hit "Enter", it returns me back to my main menu and here I'll just hit "Three" to exit. Let's go ahead and change our menu at this point. Let's just do Print Numbers and then the Guessing Game. We've used the wild statement in a couple of capacities. The wild statement here is used so that we can continue to display the menu until the user decides to exit. We are using it to merely print out values to a screen, but we get to determ
ine it at runtime or let the user to determine it at runtime as opposed to the four or the four each where it's predetermined ahead of time. Then finally, we're able to use the do while to continue to ask a series of questions until we get a satisfactory answer, at which point then we can break out of the loop. The do variation allows us to run our code block at least one time as opposed to immediately jumping outside of the block if the condition is true. That's why we would use the while itera
tion statement. It's pretty useful in certain cases. Let's continue on. We'll learn about strings in the next lesson. We'll you see there. Thanks. Hi, I'm Bob Tabor with Developer University. For more of my training videos for beginners, please visit me at devu.com. Now, many of the types of applications that you'll build as a C-sharp developer will require you to work with text, whether you're formatting the text for display to the end user or whether you're manipulating the text in some way. A
good example would be whenever you are massaging data. That's a term that developers use to talk about taking data from a file or a database, and it's in some raw form and you need to manipulate it. You need to remove certain characters. You need to add certain characters in certain positions in order to get it and prepare it for ingestion to be used by some other software system or to be saved in a different file format, whatever the case might be. Manipulating data is a key skill, whether for
display or for the sake of massaging data into the right format. Furthermore, whenever you're working with the string data type, you're working with a data type that can hold a lot of information. To extend the bucket analogy, you're working with a really big bucket. When you're working with big buckets, you have the responsibility of working with them in an efficient way. Because when you're working with data that takes up a lot of memory, it requires a lot of processing power, you are putting
a strain on system resources. Now admittedly, it would take a lot of string manipulation to slow down a computer, especially a modern computer. However, software developers, we want to do things efficiently, and so it's important to understand that there are tools in the dotNet Framework Class library that will help us work with and manipulate strings in a very efficient way. That's really the purpose of this lesson. To show you how to perform some simple string manipulations like inserting spe
cial characters in your little strings, formatting strings, especially numbers and dates and things of that nature. Manipulating strings, changing things about string, searching for items and removing them or replacing them with something else and strings. Then also working with strings in a more efficient way. As you can see, I've already taken the liberty of setting up a new console window project called Working with Strings. Please take a moment, pause the video and catch up with me. I've alr
eady added three lines of code that we'll use to demonstrate some key manipulations for our strings. What I wind up doing is just typing in a string and then showing you some manipulation and then moving on to the next line. But at any rate, let's go ahead and start by talking about the special nature of the backslash character, which is that character there. I always used to get my characters confused. That's forward slash, that's backslash. A backslash character can be used to escape or insert
escape sequences into literal strings. This will allow us to do things like put special characters, insert line feeds and things into a literal string. For a good example of this, what if I wanted to type something ironic like my so-called life? I wanted to insert a series of double quotes around the word so-called so that it displays the way that I would, as the author of this, expect it to be displayed on screen. Now unfortunately, you can see that the Visual Studio on behalf of the C-sharp c
ompiler doesn't like this at all. It thinks that you have two literal strings here. The word my and life and in between something that it can make no sense of whatsoever, the word so or the term so a minus symbol. Then the word called. These are not variables that have been declared. It doesn't recognize them as keywords. C-sharp does not like this. In order to insert a special character like a double quote to say, I don't want this to delineate a literal string, I want to use this inside of my
literal string, I'll use the backslash character before each double quote, which escapes out the double quote and makes it available for use inside of the literal string itself. Now when we run the application, we can get double quotes inside of our side of our string. Now similarly, let's put in my string equals. I tell you what, I'm just going to copy this to my clipboard so I can keep using it. Now, what if I needed to add a new line? What if I need a new line and I want to split this up unde
r two separate lines in my application? What I can do is insert a new line character. Think of a line feed. Slash n will create a line feed. Let's go to run the application. You can see that it's smart enough to know that even though we didn't separate with spaces around the word a and new it was still able to find that escape character for the line feed and represent it correctly in our little string. Now, you might say well, that's all well and good, but what if I need to actually use the back
slash character? For example, in an instruction to go to your C colon slash drive, you'll notice that we get a red squiggly line underneath the backslash because it's expecting us to use the backslashes and escape character as an escape sequence. But we've given it nothing after that to indicate which escape sequence we want to use. In this case, we have two options. In fact, in all of these cases we have two options. We can use another backslash character to escape out of it to represent this c
orrectly. Now you can see that you should go to your C colon backslash drive. I'll just do this again. Go to your C drive. What we can do is add a at symbol in front of the literal string, and that tells C-Sharp that we want to use our backslash characters as true backslash characters, not as escape sequences or special characters. Let's move on from there. We've already talked about the use of string dot format and we showed how we could do something like this, where we are going to insert the
words 1st and 2nd into this template. The template contains a number of replacement codes. The number inside the replacement code corresponds to which argument is passed in to the string that format as input parameter. Let's run the application and we would get what you might expect first equals second. What I didn't tell you at the time was that you can actually reuse the replacement code multiple times. Like so or you can use them in a different order if you like. Let's go back and change up t
he order where the second will be the first item displayed and the first will be the second item displayed, like so. Furthermore, the replacement code has some special powers. For example, if we want to do string.Format and say for example, that we wanted to display currency to the end user. I want to display $123.45 to my end user. In my case, since my computer's culture is set to English U.S, this will be represented as dollars and cents but if your country and culture codes are set to for exa
mple, English U.K. or some other language and some other culture you would probably see something different whenever you choose to do this. You'll see your native country and culture's symbols for currency. But to create and format values for currency, you use the colon and then C immediately after the numeric replacement code. In this case, I'm using say zero still represents the first item in the list but the colon C says I want you to format it like currency. When we run it at least on my com
puter you'll see dollars and cents with the dollar symbol. There's all these little variations on this. For example, what if I wanted to just display a really long number to an end-user like 1234567890. I want it to look like a number not like how I have it here where you can't really tell is that what, 12 billion or 123 million or what? To remove the confusion what you can do is use the colon and format character. This will add in decimal points and commas to give you the appropriate formatting
for a large number 1,234,000,000 and so on. Furthermore, continuing that same thought what if we were to go string.Format and we wanted to represent a value as a percentage? What if I wanted to display this as a percent? Be sure to get those formatting codes in there. Just to show there's nothing on my sleeve here, this is called as a percentage like so and then we will insert a percentage here. If this replacement code lets go and run the application and you can see that the percentage is 12.3
percent in this case. Finally, the last one I'm going to show you but I'll show you where you can find more information is how to create a custom format. For example, in the United States, phone numbers have a very specific way that they're presented. Let's go string.Format and let's go 1234567890. I want that displayed like a phone number so I would use zero and then I'm going to use count symbols to represent each digit that I want formatted. In this case, actually, I'm going to use parenthes
es around the first three numbers because that's usually how an area code in a phone number in the United States is presented then a space then three more numbers then a dash then four more numbers. That's just how phone numbers are presented in the U.S. Let's go and run the application. You can see that it in fact formats that number the way that I would expect. Let me throw one little monkey wrench in this. What if I were to supply too many extra digits? I added another one two at the very end
and yet I don't have that accounted for in my formatting. Where will it be presented? Well, as you can see it pushes out the area code to five digits instead of just three. The moral of the story there is that the formatting will go from right to left whenever you're using custom pound symbols to create a custom format for a numeric value. Again, the numbers will push their way out and once you get to the very end, it will put as many numbers as it can on that very first character and push that
formatting out to the left. Be aware of that. The next thing that we want to do is start manipulating strings in a more meaningful way. Up to this point, we've been formatting strings but what if I want to actually change some things about the strings themselves? Let me start by providing a little something that we can sink our teeth into and work with. I'm going to type in a lyric from a song that I like. Notice that I added or I left in an extra space here at the very beginning of the string
and then I left it in two spaces at the very end of that string. Let's go. My string equals my string. I think the most important thing you want to realize about when you're working with these data types is that they do have built in functionality that were provided to us by Microsoft. For example, every string has the substring helper method that we can use to just say, hey, I want to start at a specific point and then grab all of the characters within a given range. I can say start at position
six and grab me back everything after position six. When I run the application you can see it starts with the word summer which is at the sixth position and grabs everything to the very end of that line. Here is position one, two, three, four, five, and six. It truncates off the first six characters and starts me there and I pulling everything else giving me a subset of the strings from that point on. But I can also say go ahead and give me the next 14 characters after that. Don't give me every
thing to the very end of that string just give me the next 14 characters and so I can isolate a couple of characters in this case just three words in that string. I can also do something like my string.Toupper and that will do what you might think it will. It'll make everything upper case. Great. What if I wanted to replace one character with a different character. My string.Replace and say find every blank space and replace it with a double dash like so. When we run the application, you see tha
t we get double dashes instead of our spaces. It makes it more obvious that we had some spaces at the beginning and the end. We can also use mystring.Remove and we can remove a number of characters from our string. Instead of selecting out the substring of characters we took threes. We can actually remove those entirely from the string. You can see, summer we took it has been removed from the string completely. Also, what if we want to actually remove those trailing and preceding spaces? We coul
d use the trim method. Let's do my string equals, first of all, string.Format. Here I'm going to grab the length of the string to demonstrate this. The before length and then the after length. Let's go mystring.Length and then my string dot will call the trim method to strip off all of the extra spaces in the beginning and the end. Or I could choose to trim off only the ending spaces or the beginning spaces but I'm going to call the trim method to get rid of it all and then determine what the le
ngth of the string is at that point. You recall that we used the length property whenever we were working with the array to find out how many items were in the array. We can also use the length property on a string to tell us how long the string is. That's ultimately what we're doing here. Tell me how long the string is before we make any changes to it and then after we trim off those extra spaces, how long is the string itself? Run the application again. You can see that the before was 46, the
after was 43. We trimmed off three spaces. Great. The last thing I want to do is talk about working with strings in a more efficient way. For example, let me just type in a really quick code example here. We'll just do this. Actually here. The mainstream plus equals. Hopefully you remember what this operator was for, where we're saying, give me whatever the value of string is and concatenate everything on the right hand side to it. Here we're concatenating on just double dashes and in the curren
t value of i's, we loop through 100 times and we'll merely then just display my string in the console window. Let's go ahead and actually get rid of that. We'll start here with a blank slate. Let's run the application. The output isn't all that interesting, it's just a printout of numbers with some dashes in there. But what's going on behind the scenes is the more interesting part of this. What happens when you're working with the string data type is that it's called a immutable data type, meani
ng that you can't just add more values to it. What happens behind the scenes is there's this little dance that the dot NET Framework runtime is is performing to make it look like you're still working with the original variable My Strings, the original bucket. But what it does is it creates a second bucket and it starts copying things over. In this case, it copies the previous value of My String plus any of the new stuff we want to put in there, and it creates this new string in a new bucket and
then it removes the old bucket and it gives the new bucket, the name My String. Then we say, let's do it again. In fact, let's do it a hundred times and it has to go through that dance 100 times in order to produce the final result that we're printing then in our console window. You can see that's a very inefficient way and we're requiring a lot of memory management that might put a drain on the system if we were to do a lot of it. Instead, what we can use is a different data type. Whenever we'r
e going to manipulate strings in this way, where we're going to do a lot of string contamination or a lot of string manipulation, we can use something called a String Builder. Again, just like I said with a random class from the previous video, this may not make a whole lot of sense at first but hopefully once I talk about what classes are and how to create new instances of classes, this nomenclature that String Builder My String equals new String Builder. What is that all doing? We'll talk abou
t that very soon. But just let's create a new String Builder class and then we're going to do something very similar to what we did before where we will iterate through a 100 times. But this time, instead of just doing a simple concatenation, we're going to use an append method, which is a more efficient way to append additional information to the String Builder object, rather than going through the previous step of forcing the runtime to create all these temporary versions of string. My String
apend i and the result will look identical. But what's going on under the hood is that we're working with strings in a more efficient way. Use the String Builder along with the append method of the String Builder to work with strings in a very efficient manner. We talked about quite a bit in a very short amount of time how to work with the backslash character for escaping and inserting escape special characters into our literal strings, how to use string.format. In fact, let me show you this lit
tle page here for standard numeric string formats. If you just search for this on bin.com, you'll be able to find this article and it gives you examples in many other usages for the format that we looked at several examples of here. We looked at several of the built-in helper methods to replace or define subsections or completely remove or actually create two upper or two lower to change the case of strings. Then finally, how to work with strings in a more efficient manner. Now we're going to gi
ve the same treatment to dates and times because you'll again find yourself working with dates and times frequently whenever you're building applications and there's a lot of similar functionality there as well. We'll see 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 DevU.com. In the previous lesson, we looked at how to format strings and how to manipulate strings, whether it be for display or for the
purpose of massaging data. In this lesson, we'll do the same thing except for dates. We'll start off by talking about formatting dates and times. We'll look at how to add and subtract time to a given date. We'll look at how to create a daytime object that represents this moment in time or the past or the future. Then finally, we'll look at how to determine the length or the duration of time between two daytime objects. To begin, I've created a new project called Dates and Times. Pause the video,
please and catch up with me. What we'll do here is actually just create a new DateTime time object by going DateTime and we call this my value and we're going to initialize its value to a valid DateTime. The easiest way to do that is to represent this very moment as the application is executing. We'll go DateTime.Now and that represents this instant. The easiest thing that we can do is just do a Console.WriteLine, taking my value and calling the ToString method. Now you'll see we have a lot of
to something strings and we'll look at a several of these in an effort to format our DateTime the way that we want. But this default ToString method will take our our country and our locale and will present dates and times as they are typically presented in our country and in our culture. Here in the United States, we usually represent the month first and then the date. I know most other countries it is date, month, year and then we have the time of afternoon that I'm actually recording the vide
o. Notice that it also has AM, PM as opposed to military time or 24 hours. In order to change the way that this is presented, we're given a bunch of other additional helper methods and so we can do something like this, myValue.ToShortDateString and this will just display the month, date, year. Isolate These short time string. Here we just want to display what time of day it is , 3:35 in the afternoon. Great. We can also choose a more long form version of the date. You can see it's Tuesday, March
15, 2016, as I record this and we can do the same longer version for time as well, so myValue.ToLongTimeString. You can see not only do we have hours and minutes, but also seconds in the long time string. Great. Oftentimes what we'll want to do is do some daytime math, which means we either want to add hours, minutes, I guess, to seconds, minutes, hours, days, months, years, whatever the case might be. But we can do it through a series of helper methods, the add methods. Here I'm just going to
console.WriteLine and we'll take myValue and we'll start off with something simple, like AddDays. You can see that we can add milliseconds, seconds, hours, days and everything up from there. Let's just do something simple, like AddDays. We'll add three days and then we'll just do it ToLongDateString on it like that. Now you may have noticed me do this in the past where I've used the period, remember, that's the Remember Access operator and chained together a series of commands. In this case, we
have a value that represents a date. If I were to call the AddDays method notices that hover my mouse cursor over it, that the return value of AddDays is another date time. Now, since I have another date time in my hand that represents today plus three days, then I can call that date times ToLongDateTimeString, which now returns as you can see a string data type. That's the notion of chaining method calls together. As long as you continue to chain together methods that return some value of some
data type, you can continue to call methods for that given data type. Let's go ahead and see now, three days from now it will be, in fact, Friday, March 18th. Let's do something with regards to hours and let's go myValue.AddHours. We add three hours ToLongTimeString and that would be 6:38 PM. Then what if I wanted to subtract time? Are there any subtract hours or subtract days? No. However, what you can do is simply use a negative number to subtract, so instead of adding days, I'll subtract days
. We'll just go ahead and run that. You can see three days ago it was Saturday, March 12th. Great. In addition, we can just grab off parts of a date or time. Here again, let's go myValue, and let's just pull off this current month. This will return an integer. Now, Console.writeLine we know can accept an integer, so we'll just go ahead and print out the current month. The third month, obviously, that's going to be March. Now, we've looked at how to create the current DateTime, but what if I want
ed to create a DateTime in the past or in the future? I could do something like this, so DateTime and I'm going to call this myBirthday. Here again is that new keyword. I've hinted at a number of times, we will get to it, don't worry, but I'm going to use it one more time, new DateTime, and I'm going to parse in the year 1969, the month December, and then the day the 7th, that was the day I was born. Now what I can do is something like we've been doing up to this point, Console.writeLine and jus
t myBirthday.ToShortDateString just to prove that it's of date just like the other dates that we've been working with, so 12/7/1969. Now there's one final way to create a new DateTime, so let's create another version of birthday equals DateTime.Parse, remember we've used in parse. We were able to take a string and turn it into an integer. Here we're going to take a string and turn it into a date, hopefully. We'll just type in myBirthday again one more time, and that should give us a DateTime obj
ect that represents December 7, 1969. Now what I'm going to do is try to determine how many hours that I've been alive or how many days I've been alive. Days is probably more interesting number. In order to represent a span of time, we're going to use a new data type called TimeSpan. Here I'm going to use a new TimeSpan, and we're going to call this myAge equals DateTime.Now.Subtract, and the subtract method will take the current date and subtract whatever date we want to use. In this case, we'l
l use myBirthday. Now that I have an object that represents a span of time, I can say represent that span of time in terms of days or years or whatever the case might be. To do that, I'll go Console.writeLine and then I'll use this myAge.. Here I can say, give me the total number of days that I've been alive and print those to screen. You can see I've been alive, what? Well, 16,900 days. I'm getting old. I say that every time I record this video and I feel older every time. Anyway. Here we were
able to format dates for display. We're able to manipulate dates by adding and subtracting date and time, and they were able to determine the difference between two dates using a TimeSpan object. We also talked about different ways to create a date, whether it be now or some time in the past or future, by either just using one of the versions of the DateTime objects constructor, we'll talk about that later, or by using DateTime.Parse and parsing in a string. Let's stop right there and we'll pick
it up in the next lesson. Doing great. See you there. Thanks. Hi, I'm Bob Tabor with Developer University. For more of my training videos for beginners, please visit me at devu.com. You might recall at the outset of this course, I said that a class is a container for related methods, and I used the console class as an example of this. We had the Console.writeLine, Console.readLine, Console.Write, we've even used Console.Clear. All of these methods that had something to do with working with the
console window. I said it makes sense to put them all in the same class, the console class. Now, truth be told, I intentionally oversimplified my explanation about classes and their relationship to methods, because first of all, I wanted you to gain a little bit of confidence in yourself that you can do this, that this isn't hard. You can get your hands around it and you're going to do just fine. I wanted to do that before we got into the topic of classes, because while there's nothing hard per
say about classes, they do lend themselves to a conversation about object-oriented programming, a style of programming that some beginners find a little bit difficult to grasp at first. Now, the code that you've been writing in your methods have all been defined inside of classes, and you've been calling methods that were defined inside of classes. Classes have been all around you, you've been working with them from the first line of code that you wrote. You're really already an old pro at this
whether you realize it or not. I'm merely going to fill in some of the details that you don't yet know about in this lesson in a couple of subsequent lessons so that it rounds out your knowledge so that you can fully harness the power of the.NET Framework Class Library in your applications. Maybe someday, whenever you sit down to architect some big application for some large company that you go to work for, you'll begin to think like an experienced, object-oriented software developer. But at thi
s early point in your C-Sharp experience, I really just want you to be able to do one thing and one thing well, that is to find what you're looking for in the.NET Framework Class Library and be able to have the confidence to utilize the methods and the properties in those classes that have been defined there. The truth of the matter is that object-oriented programming is such a massive topic that I certainly couldn't do it justice in this course. In fact, I have a whole course devoted to it on d
evu.com. Again, I really just want to accomplish one thing here, I want you to know enough about classes and objects and properties and methods and things like that so that you can harness the power of the.NET Framework Class Library inside of your own applications. Now, the way that we're going to learn about classes and methods and properties and all that good stuff is by creating simple custom classes of our very own. Let's start by talking about creating a simple application for a car lot. S
uppose that I own a car lot and I want to sell cars, and I want to build an application that helps me keep track of all the cars on my car lot. I might need to create a number of variables to hold information about a given car, because I'm going to use that information to then determine its value based on its make and its model and its year and so on. I might start off by creating a couple of variables called car1Make, car1Model, car1Year, and so on, in order to keep track of that information. N
ow, what if I need a second car in my application? Well, then I guess I could create another set of variables called car2Make, car2Model, car2Year. What if I need a third one? Well, I think you see where I'm going with this, things are going to get out of hand pretty quickly here. Then what if I decide one day that the value of the car is not only based on the make, model, and the year, but we also need to keep track of the color of the car as well. In that case, now I got to do car1Color, strin
g, car2Color and so on. You can see that this simply is not the right approach to keep track of information that should be collected together about a given entity. I need a way to keep all of this data about a car together in its own little container. I want to keep track of the make, the model, the year, the color, and maybe a bunch of other things too about a single car, but I don't want to have to treat it like a bunch of loose information, I need it all related together. What I'm going to do
is start off by defining a class that contains four properties that describe any given car on my car lot. To begin, what I'm going to do, you can see I have a project that I've already started with here, SimpleClasses, go ahead and pause the video and catch up with me if you like. What I want to do is work actually outside of the first class that's already been defined in our program.cs file. I want to work inside of the namespace SimpleClasses, but I don't want to define a new class inside of
my existing class, I want to work outside of that class here, and so I'm going to define a new car class like so. I'm going to give it four properties, and I can type it all out like this and I'll explain what I'm doing here in just a moment or I can use a shortcut prop, tab, tab and then I can use the replacement areas by using the tab on my keyboard, so I want to make a string, tab, tab model, enter, enter, prop, tab, tab, int, year, enter, enter, prop, tab, tab, string tab, tab, color, enter,
enter. I've just defined a class name car with four properties. This car class allows me to define a data type that describes every car in the world. Every car has a make, a model, a year, and a color, and a bunch of other information that I might or might not be interested in for my specific application, but my aim here is to use this definition of what comprises a car in order to create additional instances of the car class that represent all of the cars on my car lot. In other words, I want
to create a bucket in the computer's memory that's just the right size to hold information about any given car on my car lot. It should contain not only the fact that it's a car, but then also the value of its make and its model and its year and its color, all in one big bucket up in the computer's memory so that I can access it. There's two parts to this. There's defining the class itself and then once I've defined it, I can create instances of that class. Here the class is the definition, but
when I create a new instance of this class, then I'll be working with an object and sometimes those terms get confused. But the class is the blueprint, the object is an instantiation or something that's been created as a result of having the blueprint or the pattern. The way that we create a new instance of the car class is to do this. I'll just call this my car to avoid confusion. This point, I've defined it just like any variable I would by declaring the data type itself, whether it be string
or integer. This is just a little bit more interesting, a little more complex. It's the car class. Then I give it a name that I want to call it by my car. Now, that's part of what I need to do. The next thing that I want to do is actually then create a new instance of that class and say, put this up in the memory, in the bucket, so to speak. Here we go, new car. Again, there's two parts of this equation, we'll talk about this more as we go throughout this course. First of all, I want to declare
a new car in memory and then I want to create an instance of car and then put it up in the memory, so there's two distinct steps there. In the real world, you can use the same blueprint to create many different houses. In the neighborhoods that I've lived in before, you might describe them as cookie cutter houses, they all look the same. You could use the same pattern to create clothing over and over, or you could use the same recipe to create the same cake or casserole and get the same results
each time. Each time you want to build a new house, it will be at a different address. Each time you follow the pattern, you'll create a new instance of the clothing that can be sold to a different customer. Each time you follow that recipe, you create a new instance of the recipe and you can offer it during either the same meal or a different meal. The same is true with classes, each time that you create a new instance of the class, you have a new object that is distinct and separate from the o
ther instances of that same class in the computer's memory. They each live by themselves. A class is like a cookie cutter. Now keep in mind, you can't eat the cookie cutter itself. You eat the cookies that you make from the cookie cutter. The cookie cutter gives each of the cookies some shape, and so when you instantiate a new instance of a class, you're basically using your class as a cookie cutter to stamp out new instances and you have 1, 2, 3, 4 new instances of cookies that you can then put
in the oven and bake. Focus on the new keyword, it is what you would consider to be the factory. It actually builds the new car and puts it into memory. It uses the blueprint, it uses the pattern, it uses the recipe, it uses the cookie cutter in order to create a new instance of that blueprint or that pattern or that recipe or that cookie cutter and it brings the class to life in the computer's memory, and it makes it usable by your application. You can create many instances of a given class or
you can create many objects, all based on the same class, but each object will be distinct from the others. If by no other distinction then by is merely the address in memory where they live. What I want to do is not only set the properties of this car because I have these four properties that I want to use to distinguish this car on my color to represent this single car. But then also, I may want to then access or get those properties back out, and it's working just like you're working with va
riables. In this case, instead of just accessing make variable, I would go mycar.make and I would set that equal to Oldsmobile. Now, admittedly, in this particular case, I am merely hard coding these values. If this was a real application, I would ask an end user to input this information or I grab it from a database, something along those lines. There we have it. We have one instance of the car class and I've set all of its properties, and now I want to get those properties and print them out i
n a console window. We'll just do this in the most easy way possible. We access, or we get the values just like we set the values before by using the name of the object, dot the name of the property. Let's go make, myCar.Model, myCar.Year, and myCar.Color. Now you might be wondering, well, Bob, why did you do it that way and not Car.Make, or Car.Model? Remember car in that instance, car describes the class, the blueprint. But what we want to work with is one instance of the blueprint so that's w
hy we're calling that instance myCar. It's the variable name in the computer memory that we want to work with. Let's go ahead and separate these out on the separate lines and then finally will go Console.Readline, so and this should not be an exciting application at all because we're merely just printing things to screen. But at least I can show creating new instance of a class, setting the properties, and then getting the properties and printing them out. That's what this get in the set are for
. There are actually longer versions to declare a property in fact, let's just do this propfull, tab, tab. This is a longer, more complete version of creating a property, but I don't want to talk about it right now there are reasons why you would want to use this. But for the most part, for our simple needs, we'll just use this abbreviated version of defining a property in our classes. Now did you notice that we got full IntelliSense support, so whenever I typed out myCar. and I used the member
accessor operator that I'm able to see all the members of the class, the Make, the Model, the Year and the Color. All represented as a little wrench icons in IntelliSense so that I can access them, whether to set their value or get their value. Furthermore, I'm able to set values the way that I would just with normal variables by using the the assignment operator, I'm able to work with the variables and write them just like I would any other variable in my system. There's nothing all that specia
l about it outside of the fact that they're all related, to a specific instance of a class. We created a new data type, the Car data type, and since the data type, we can use it just like we would any data type in our system, so if I wanted to create a little method here, private static, and I'll use the decimal data type because I'm going to work with dollars or money currency, and I'm going to create a method called determine market value and I'm going to allow this to accept a car as an input
parameter. What I'll do is just in this case, I'm going to have to carValue to $100 and we'll leave it at that. In fact, I'll go ahead and the end here. However, if this was a real application someday, I might look up the car online using some web service to get a more accurate value. But for today, we're just going to hard code the value to be 100 and we'll return carValue. Here I can go determine market value, I can pass in myCar, and I should return back the value, so let's go decimal value
equals determined market value and then let's go Console.Writeline and will use what we learned previously, to print out the value of the car like so, and let's run the application. You can see that it's worth $100. Now notice what I did here. I used the C in car in a c in car. The C corresponds to the name of the class because I named it with a capital C, and the C-sharp compiler is smart enough to know that again, C car and c car are two different things, and this is a common naming convention
to use the same name for an object if there's no reason not to. If there wasn't something special about the car like it being in some special state, but I can reuse the word car, I chose not to do that here just to make it obvious what I was actually doing. But there's nothing wrong with doing this as well. Defining this input parameters data type and then giving that input parameter the same name. But just with it lowercase character they're two very different things. Moving on, I want to talk
about creating methods on the class. We've already said that classes are containers for methods. We've created this helper method here inside of my static void main. But it might make more sense for us to create that method here inside of the car class itself since the car class already has access to information like the make model of the year and the color and that's the information that we would use in making a determination on its value. Here, let's go ahead and define this as a public decim
al DetermineMarketValue. Now, we're not going to allow anything to be passed in, because we already have all the information we need right here. Let's create a little algorithm here. If the year is greater than 1990, then we will set the value of the car, the car's value, which we need to define as a, so let's go. Decimal carValue, set the carValue equal to $10,000 so if it's a relatively new car, we'll set it to 10,000. Otherwise, we'll say the car's values only words of 2,000. This is a very,
very overly simplistic example. But we just want to demonstrate the fact that inside of an instance of the class, you're going to be able to access its properties. We're able to access the current car's year in order to determine its value, and so in this case, what I'll do is let's comment this out and comment that out, and here will go Console.Writeline, myCar.DetermineMarketValue. Like so. Because this is going to come back as a decimal, I'm still going to want to format it. Now let's go ahea
d and run the application. Since it's in 1986, is before 1990, it's only worth $2,000. In this lesson, we used a very concrete example. We've all seen cars, driven cars, own cars. A car is easy to conceptualize and represent in a class because there's a tangible real world equivalent. Now my assumption again, is that your main exposure to classes will be whenever you're using classes define by Microsoft in the.Netframe class library, and most of the time, those classes don't represent real tangi
ble things. They're very conceptual in nature. You might have a class that represents a connection to the internet. You might have a class that represents a buffer of information that streaming from hard drive. They don't really have real world tangible equivalence, so you need to be aware of that. In most cases, the.Net Framework class library classes don't have real world equivalents, but the ideas are exactly the same. As you choose a software developer, you might want to invest a little bit
more time in learning how to create your own library of classes, and those classes can interact with each other, they can represent real things in your company or in the real world or conceptual things. The process that you go through to break down a problem in the world and represented in objects, is object-oriented analysis and design. Again, that's not a topic that we're going to cover in this series of lessons, but you can learn more about that at DevEW.com, where I spend a lot of time talki
ng about those things. To recap, a class is just a data type in.Net and it's similar to any other data type like a string or an integer. It just allows you to define additional properties and methods so you can define a custom class with properties and methods, and then you create instances of those classes or rather you create an instance of in class, therefore working with an object using the new operator. You can then access that object's properties and methods using the.Operator, the member
accessor operator. There's quite a bit more to say about classes. Don't worry if you don't understand everything just yet, why you even need them, how to really fully utilize them. Just make sure you understand the process that we went through in this lesson of defining a new class, creating an instance of a class, setting its properties, getting its properties, passing an instance of a class into a method, or even defining the method inside the class itself, and allowing it to access its own me
mbers like its other properties. If you really don't understand much more than that, then you're doing just fine. You're exactly where you need to be don't worry, we'll cover lots of other topics related this in the upcoming lessons. We'll see you there. 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'll continue to talk about classes and methods. We'll begin by talking about the lifetime of objec
ts so objects come to life. They live for a period of time, and then they die. They're removed from memory, and we'll talk about the.NET Framework runtime and its role in the creation, the maintenance and then ultimately, the removal of objects from memory. Next, we'll talk about constructors, which are simply methods that allow us to write code as developers at the moment when a new instance of a class is created. Finally, we'll talk about static methods and properties that study keywords been
lingering around now for some time, and we've been using static properties and static methods throughout this course, even from our very first examples. So we'll finally tackle that issue in this lesson. Let's begin by creating a new project. You can see I've already done that and pause the video and catch up to where I'm at right now. I've created a new project called Object Lifetime. Furthermore, you'll see that I copied the car definition from our previous lesson. If you like, you can type th
at in help build some muscle memory, help remind you to use the Prop Tab Tab shortcut, the code snippet in Visual Studio to create these short and auto implemented versions of properties. We've talked about that a little while, and then ultimately you can see in line number 13, we create a new instance of our car class. That new instance we'll call myCar, and we've talked about this in the previous lesson, but I felt like this deserved a little bit more explanation because there is actually a lo
t that's going on under the hood, and it would be helpful to understand this as we begin to work with classes and objects. Whenever we issue a command to create a new instance of a class like we have in line number 13, the.NET Framework runtime has to go out and create a spot in the computer's memory that's large enough to hold a new instance of the car class. Now that much we know. The computer's memory has addresses that are similar to street addresses like the address you live at, the address
that I live at. Now, admittedly, a computer's memory address is looked dramatically different than our addresses, like 123 East Main Street, because the computer's addresses are typically represented in hexadecimal values, but they're known addresses nonetheless. It's easy then, for the computer to find something in its memory by using its address. The.Net Frameworks first job is to find an empty available address where nothing is currently living, where there's no data that's currently being s
tored, and that address has to be large enough to store an instance of our class. The.NET Framework runtime will then create the object instance, and it will copy any of its values that are currently stored in that object instance up into that memory address. Then it takes note of where it put that object. It notes the address of the memory where it put that instance of our object, and then it serves that address back to us, and we store that address in the actual name or the instance name of ou
r class. In this case, myCar, that variable is actually holding on to a reference or, in other words, an address in the computer's memory where we can access that object once again. Now, whenever we need to access the new instance of the car class, we merely can use its reference name. It's in this case myCar, so myCar is simply holding an address. It's simply a reference to an instance of, in this case, a car class in the computer's memory. Whenever you need to work with that instance of the ca
r class, you just use the myCar Identifier and the.NET Framework runtime, takes care of everything else for you. It gives you the illusion that you're actually working with the object itself, but in reality, you're just holding on to a reference to an address in the computer's memory. Now there's an analogy that helps me to sort all this out in my mind, and we're going to continue to extend that bucket analogy, if that object is stored in the computer's memory, if it's what we have equated to a
bucket, an address, an area that holds on to our values, then what's returned back to us as programmers is a handle, that's what myCar is, it's our handle to the bucket. We've used that bucket analogy in a number of different times and it's served us well. But we essentially are storing values in that bucket just like we were before, and we're holding on to that bucket using our reference to that memory area in our computers memory. What happens if we were to let go of the handle? Well, at that
point we'll no longer be able to get back to the bucket. We've lost the bucket somewhere in the computer's memory. The bucket will no longer be accessible to us. Now, can we ever get back to that bucket? Well, no. What happens is that the.NET Framework runtime will be constantly monitoring the memory that it manages, and it's looking for objects that no longer have any handles associated with them. Once we let go of a handle, the reference count, the handle count, I guess you could call it will
go to zero and at that point, the .NET Framework runtime will say, I see that nobody's interested in you anymore. They've let all of their handles to you expire or to go out of scope. That must mean that you're no longer needed and it removes it and throws it in the garbage. That process of monitoring memory, looking for objects that no longer have any references to them is called garbage collection. It's one of the core features of the .NET Framework runtime, and it's one of the reasons why it'
s easier to work with C-sharp at first as a developer than maybe going directly to C++. In an unmanaged language like C++, you, the developer, may have to manage memory on your own, and sometimes you might forget that you actually are leaving things in memory and you're not cleaning them up, you're not removing them yourself so your application might have a memory leak. Or you might have a corrupted memory region where you're using an area of memory and you forget that you're using it, so you co
py something else to that area of memory. Now you go back to retrieve the value that you originally put in there, and it's corrupted. That leads to corrupted memory in applications. You don't really get that issue so much in C-sharp because again, the .NET Framework runtime takes care of all the memory management for you. Let's do a little of experiment here, if we said that we can have one handle to a bucket, what happens if we attempt to create a second handle to the same bucket? Let me do thi
s real quick. Let me go to myCar and start setting some of the properties like the Make equal Oldsmobile. Then we'll set the Model equal to that Cutlass Supreme and then we'll set the Year equal to 1986. Finally, we'll set the Color to Silver. Now, keep that in mind, we've created a new object that we're referencing using the myCar identifier. Instance of the car class lives in memory, and we're holding on to it with a handle called myCar. But what if we were to create another car like this? So
my other car, what have we really done right now? We simply have created a handle, but we've not attached it to any buckets of cars in our computers memory. At this point, what I could do is go myOtherCar equals myCar. Now, what have we really done there? Well, we've merely taken one handle to a bucket in memory, and we've created a second handle and said, "Hey, let me copy your address," so that we're both referencing the same bucket in the computer's memory. Now, to prove that what I'll do is
do a Console.Writeline and we will do what we did before. Just give me a second here and we'll reference myOtherCar's Make, myOtherCar's Model, myOtherCar's Year and then myOtherCar's Color. Let me separate these two different lines for readability sake. Then a Console.Redline for good measure. Now let's run the application. You can see that even though we created or set the properties of myCar since we copied the reference to the car object in the computer's memory into a new variable called my
OtherCar, I can still get to the values that are in memory because they're both pointed to the same object. Now I can even do something like this where I actually change something, myOtherCar.Model equal to the 98. That was the large style model for that car. Let's then go back to and do something similar to this just to prove that they're one and the same here, and I'll say, "Hey." Let's do that. We're going to use our reference called myotherCar and set the model, change the model from the val
ue Cutlass Supreme to the 98. Then we're going to say, Hey, show me what's in the myCar object. So now we're going to run the application, and you can see now we're printing out what's currently in my car. It's the same thing that we changed in my other car because they're both pointed to the same place. I just want to emphatically make that point here. As you can see, we have now two references to the same object in memory. We essentially attach the second handle to the same bucket so that we c
an use either one to retrieve the data in the bucket, so to speak. If you don't like that analogy, maybe it helps to think of this in terms of balloons. I have a balloon and I have two strings tied to the balloon. What happens when I cut the first string? I'm still holding on to the balloon, but what happens when I cut the second string? The balloon now will fly away, and we'll never see it ever again. As references go out of scope, in other words, whenever the current thread of execution leaves
the current code block that we're currently in, or those object references are set to null intentionally by the software developer, then the number of references to the object, the number of handles to the bucket, the number of strings attached to the balloon, they go to zero. So here again, when the. NET Framework runtime looks through memory and finds objects that have a reference count of zero it will remove those objects from memory. We talked about the two instances in which the connection
s to the object get removed. One is that the reference goes out of scope, so whenever we create a new variable called myCar, it will continue to be in scope as long as we're inside of this main method. But once we exit out of the main method, that variable goes out of scope. it's no longer available for us to access any longer. The same would be true if we created a different method, and defined a variable. As soon as we go out of scope of that method and we have finished executing all the lines
of code in that method, then any of the variables that were declared inside of that method go out of scope. In this case, we would lose then any references to the objects that we created in the context of that method. That's one instance in which we'll lose references to objects that we created. But the second is if we, as the developers, actively take a role in cutting the strings or removing the handles from the buckets in memory. The way that we do that is by setting our objects equal to nul
l. The value null is not zero, and it's not an empty string, it just means indeterminate. In this case, what we'll do is go here, and we'll set myOtherCar equal to null like so, and when we do this now we'll remove one of the handles to the bucket, so we're back to just one handle in the bucket. To prove this, let me go ahead and copy this little section of code, and go here and put it below this, and when I do that, notice what happens will get an exception. The exception is that there's a null
reference exception that was unhandled, and the reason why it was a null reference exception is because we have now removed the handle. The handle does not point to any objects in memory, and yet we're still attempting to access values from the object in memory, so we get an exception in our application. Now what will happen if we were to remove the second reference like so myCar equals null. Well, at that point now we have removed all the references to the bucket, even if we were to attempt to
get to it with either myOtherCar or myCar, either way, the references are gone completely, and so now the object will be removed at some indeterminate time in the future by the.NET Framework runtime. In some situations, this indeterminate period of time can cause a problem, especially when the object in memory is holding on to some special resource, maybe something like a reference to a network connection or a file on the file system or holding on to a handle to access a given database. Again,
we don't know exactly when the.NET Framework runtime will actually execute the garbage collection step, and that might pose a problem in certain situations. In these cases, you would want to use a more deterministic approach to requesting that.Net removes the object from memory and, if necessary will finalize and clean up anything that needs to happen inside of that object to completely get rid of it in the computer's memory. In these cases, you want to learn about deterministic finalization. Th
at's a little bit of an advanced topic, so we're not going to talk about it in the series of lessons. Just keep in mind that whenever we set reference to null or whenever we go out of scope, we will be removing all the references to our objects. But the .NET Framework runtime itself figures out when it's ready and willing to remove those objects from memory completely. In most cases, that's not a problem. Occasionally, you're going to run into a situation where it is a problem, know that there i
s a remedy for it called deterministic finalization. That should suffice our explanation of really what's going on whenever we create new instances of objects, how objects are maintained in memory, and then at what point they're removed from memory. Let's move on and talk about constructors. I said at the very outset that a constructor is merely a method that allows us as developers to execute code at the moment that a new instance of a class is created. There's something really subtle about wha
t's going on here in this line of code line number 13. Did you notice that whenever we use the new keyword, and we give it the name of the class that we want to create a new instance of that we're also calling it using the method invocation operator. Why do you suppose that is? Whether you realize it or not, you're calling a method whenever you create a new instance of a class, and that method is referred to as a constructor. It allows you, the developer, the option, you don't have to do this. I
t's an option to write some code at that very moment whenever a new instance of a class is created. Constructors can be used really for any purpose, but typically they're used in order to put that new object into a valid state, meaning that you can use it to initialize the values of the properties of that given object, and so it's immediately usable. Now, let me give you a really quick example here. Let's say that you want to create a constructor that would allow you to set a property of the car
at the point whenever you create a new car class. That property is available immediately in the very next line of code whenever we begin to work with it here in line number 15. Whenever you actually want to create a constructor, you would go and create something like this, public car. In this case, what I'm going to do is simply set the make property to Nissan. By default, whenever we create a new car class, we're going to set one of its properties, the make property to Nissan. Now let me say t
his as well, you might see the keyword this used that this keyword is optional, it refers to this instance of this object, and it's just to help clarify where this variable name or this name is coming from. When I see that this keyword, I automatically think, Oh, that's part of the declaration of the class itself. It's saying that you want to access a member of this class that's been created. But as you can see, it's faded out in my text editor. It might not be in yours, which lets me know that
I could actually remove this it's not necessary. You might see that though in other people's code, just understand what that is. Now if we were to go ahead, and create a new instance of the car class, here's what I'll do. I'll actually comment out all of this code. Like so, and then I'll comment out the code that we know will break the application. We can leave the rest of it, I suppose. Notice that the very first item that is displayed is the make of the car, and it's set to Nissan. I didn't se
t any other properties. That's why we didn't get any other values there in the printout, but hopefully you can at least see how we go about creating constructors. Now, admittedly, it may not make a lot of sense right now why you'd want to do this, but I'm showing you the technique you'd use, not the rationale, necessarily, but the rationale is simple. What we would typically do here is to put any new instance of an object into a valid state. You could load values into the various properties of y
our class from a configuration file or from database or some other place in order, again, to get that object into a valid state so that it's immediately usable at the point of whenever it's instantiated. Let's go ahead and talk about overloaded constructor. You'll see this frequently whenever working with objects in the.NET Framework Class Library. Just like you can create an overloaded method in your classes by changing the methods signature, in other words, the number and the data type of the
input parameters for the method, you can do the same thing with a constructor. You can create an overloaded constructor. What I'm going to do is create an overloaded constructor here like so. Now at this point, the method signatures are the same, so I'm going to get a little error here. But to modify that, I will merely add at least one input parameter of type string, but I'll go ahead and do them all as well. Then here in the body of the constructor, I would Make equals make. This Make is in re
ference to the property itself. This 'm' in make is the name of the input parameter, and it's a good convention to use the same name for readability sake and for your own sanity. You don't have to do it this way, but just keep in mind that M and m are two different items as far as C-sharp is concerned. It's not confused. You might be confused, but you will be able to handle this just fine. Now you might ask, what's the point of that? Well, in many cases, whenever you create a new instance of a c
lass, typically you don't want to take five steps to do this. You would want to immediately whenever you create a new instance of a class, so my third car equals new car. At this point, you can do one of two things. Notice here that underneath the open parentheses, I have one or two ways that I can call the constructor. I can either give it no input parameters or I can give it four strings as input parameters to initialize that new instance of car and put it into a valid state immediately. Here
I might go Ford, escape, 2005, white like so. Now I have not only created a new instance of the car class but I immediately initialized its values by calling its overloaded constructor to populate all of its values at the moment of instantiation. What would happen if we were to actually remove these two completely? What if we were to comment these out? What happens? You can see that we're still using the method invocation operator for our new instance of car that would suggest that we're calling
a constructor, but we don't have a constructor defined. Why is this working? Why isn't it giving us an error? Well, the reason is because a default constructor is automatically created for you whenever you compile your classes. It will be a constructor without any input parameters and will have no body, but it's essentially the equivalent of doing this right here, except with nothing inside of it. That's created automatically for you. No matter what, you're going to have a constructor, it just
won't do anything for you. The implicit default constructor has no input parameters, no method body, but it allows you to make calls and create new instances of classes in a consistent way. It's actually just generated for you. Again, it compile time, of course, by defining it yourself, you're taking control of the process of instantiation. Let's talk about the static keyword now. You've seen static around since the very beginning. I said, let's ignore that for now. We created our own methods, a
nd I said, we have to use the keyword static. I'll explain later. Well, now is the time. I want to ask a question, did you ever notice that whenever we were working with the Console window, we never had to create an instance of the console class in order to call its methods? That combined with the fact that whenever we wanted to work with DateTime, we could get to this moment in time by using the DateTime.Now property, but we never had to create an instance of DateTime. Furthermore, whenever we
were actually working with arrays and we wanted to call the reverse method, do you remember we did Arrray.Reverse and then we passed in the array itself? How is it that we were able to use the reverse method without creating an instance of the array class? Well, in each of these cases the creators of those classes, or specifically those methods adorned their methods with the keyword static, which means that you do not have to create an instance of a class in order to utilize that method. In some
cases, they may have defined an entire class as static, meaning that all of its properties and methods were static. You can create your own static methods in classes as well. Again, the objective here at the very outset is to just help you utilize the.NET Framework Class Library. So just know that some of the classes and methods in the.NET Framework Class Library are static and some are instance or require you to create an instance of the class before you call its methods and properties. Static
methods will be available to you without first requiring you to create an instance of a class. Just so you can see how this works, we can create a static method on our car class like so. In this case, we'll go public static void MyMethod, and here we'll do Console.WriteLine called static MyMethod. Now we can go here near the very top and just say Car.MyMethod, and notice I didn't have to create an instance of car. I'm using the actual car class definition itself when we run the application. Bef
ore we go too far here, let's comment out pretty much everything. Let's remove that. Let me go down here. Just make this so that we don't run into any potential issues here. Let's run the application and you can see that we were able to successfully call the static MyMethod. Now, what would happen if we attempted to reference one of the properties in our class? Let's just print out the make property. Notice that I immediately get a red squiggly line beneath the word make. It says that an object
reference is required for the non-static field, method, or property called Car.Make. It's important to keep in mind that there's a fundamental difference between working with classes that have static members versus instance members. Instance members are the things that we've been working up to this point where we have a series of properties that describe a single instance of a given entity like a car. They might be methods that operate on a single instance of a car like the constructors that we
saw, whereas a static member, like a static method in this case, they don't really operate on any single instance. They're more like utilities. You can call them at any time. They don't depend on the state of a given instance of the class or even the application itself, they can be used at any time because they're not really tied to one specific car. They're true of all cars and can be used at any time. Static members versus instance members, just keep those two clean in your mind. You might wan
t to ask the question, why would you ever create a static member like a static method? Well, that's a bit more complicated. That might require a longer discussion of things like design patterns which are common solutions to common problems for software developers or coding heuristics which are more the best ways to go about solving problems. I just want you to know that there's a fundamental difference between static members in a class and instance members of a class and it's easy to recognize t
hem. If it's a static member, it'll have the static keyword and in which case you cannot reference any instance members like instance properties or even other instance methods that act on instance properties. They require an instance of the class to operate. Just know that there are these two types of members in a given class and that you're going to encounter both whenever you're working with the.NET Framework Class Library. Why you would use one or the other, well, that's really again another
story. I would say this that typically, I would recommend that you don't mix and match them in the same class. Clearly, not everybody agrees with me because you'll find that many times, but it's not really important at this point to understand why you would use one over the other, just know that that possibility exists, that's why you don't always have to create an instance of a class before you use the members of its class; in this case, a given method. Let's recap what we talked about in this
lesson. We began talking about the lifetime of an object, how we create a new instance of an object, what that's doing in terms of creating an area in the computer's memory, returning back to us an address, a reference to that object in memory, what happens during the lifetime of that object, and ultimately, what happens whenever we remove all of the references to that object. Talked about the role of the.NET Framework runtime and how it's keeping track of the number of references to objects so
that it can perform garbage collection on objects that have no more references to them in memory as means of keeping things clean and making the memory available to other applications or even our application again. We talked about constructors and how developers can use them to put a new instance of an object into a valid state at the point when that object is created. Then we talked about the static keyword. We looked at some usages of static members inside of the.NET Framework Class Library. W
e looked at creating our own static member, this MyMethod. We talked about the difference between static members and instance members and how it's really oil and water. You can't mix the two and why that is. We didn't really talk about why you would choose to use one over the other. However, that's again a topic for another day. Hopefully, all of these concepts make sense. If not, don't continue on and hoping that you'll just catch up to them at some point in the future. Make sure you thoroughly
understand this before you continue on. If you are continuing, great, we'll see you in the next lesson. We'll see you there. 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 a lot of time talking about variable scope. It's actually extremely important. We recently learned that it also impacts the lifetime of objects. We want to spend a little bit more time really making sure we understand the sco
pe of the variables, whether they be variables holding simple types or references to complex types in our applications. Not only do I want to fully explain that, but then I want to use that as a launching pad to explain key words like public and private that we've seen several times in our course up to this point but I haven't really talked about. Before we talk about that, let's talk about variable scope. Let me start by saying that whenever you declare variable inside of a block of code, that
variable is only alive for the life of that code block and any of the interior code blocks or code blocks inside of that code block. Meaning that when the code block is finished executing, the variable that was defined inside of that code block is no longer accessible and its values are disposed off by the.NET Framework runtime. We'll start by looking at how that is impacted by common code blocks that we've been working with up to this point and then we'll use that and expand beyond there. You c
an see that I've created a project called UnderstandingScope and you can pause the video and catch up with me. I want to create this project and focus on testing how variable scope works. I'll start with a pretty simple code example. Again, the concepts that we talk about also apply to object references not just variables that hold simple strings and integers. Let's start by creating a simple for iteration statement and we'll just loop through 10 times and we'll do a Console.WriteLine containing
the value of i, and then here, we'll do the Console.ReadLine. We can see our results and we'll run the application. As we would expect, we can see values from zero through nine. Now, what if I wanted to access the value of i here right after the closing curly brace for the for statement? We'll notice that I'll get a red squiggly line under i, and if I hover my mouse cursor over, it says that i does not exist in the current context. Why? Because i is now outside of the scope of its definition, w
e defined i inside of the for loop, it's available inside the for statement itself plus in the code block below it but not outside of either of those. Let's comment that up. Second, we'll continue by going and creating a string of j equal to empty string. What we'll do inside of our loop here is just go j equals i.ToString. Now let's go outside of our loop where we'd be able to access the value of j. Let's go outside of the four, and well, we'd we be able to actually print to screen the value of
j. We were not getting any errors, so let's run the application. You can see that the last value that was inserted into j was the value nine. Since we defined j outside of the scope of this of the for statement and its code block, we can access it inside of that code block and outside of that code block as well. Next up, let's look at something like this, where we'll actually create what's called a field or a private field. We'll go private static string k equals. A private field is like a prop
erty, except it's private in nature, but it is available to all of the members of the class. We should be able to see k inside of our for loop. Let's do i.ToString. We should be able to see it here as well outside of the for loop like so. Let's go ahead and run the application. You can see that second Console.WriteLine will also display the number 9, but the real question is, what if we were to create a helper method? Static void, and we'll just call this HelperMethod. Here we go. Console.WriteL
ine, and we'll say this is the value of k from the HelperMethod, and we'll do that. Now here, we'll call the HelperMethod like so. Will this work? Will we be able to access the value of k as it was set inside of our for loop outside of our static void Main? Let's run the application, and you can see that we can, in fact, get the value of k from the HelperMethod. Why? Because k was defined at, I guess, you could say, the class level. It is a sibling to static void Main and static void HelperMetho
d; therefore, it's accessible to each of these as well as any of their inner code blocks. Hopefully, this is starting to make sense. Let's go inside of the for loop now, and here what we'll do is a simple if statement. So if i is equal to 9, so on the very last run of this, then let's declare a string called l, and we'll set that to i.ToString. Then outside of that, we'll go Console.WriteLine the value of l. As you might anticipate, we will see that l does not exist in the current context. Why?
Because we declared the value of the string variable l inside of the if statements curly braces. Outside of those curly braces, it's no longer accessible, so we have to comment that out. Hopefully, this solidify in your mind many of the combinations that we can use in determining whether something's in scope or out of scope. If you had any confusion about this, hopefully, that cleared it up a little bit. Now let's move on to the larger topic of accessibility modifiers. We've been creating classe
s, specifically the car class up to this point, and whenever we were creating methods, I would typically use the public keyword. Occasionally, I would use the keyword private like I did here in line number 11. Private and public are both accessibility modifiers. They're used to implement a tentative object-oriented programming called encapsulation, which is actually pretty important. In a nutshell, you should think of classes as black boxes. Whenever you think of a black box, maybe you can think
of one of those old-style television sets. Maybe your parents or grandparents had one. I remember as a kid, us having one, there were no remote controls. You had to get up, walk across the room and actually turn the dials of the TV in order to tune to either VHF or UHF channels. You had another dial where you would adjust the volume. You had an antenna in the back, so you would connect this wire out to your antenna, and you had another one where you would plug it into the wall. Everything else
about the television was self-contained. Now, as a kid, I was fascinated whenever my dad would pop off the back of the television set, and he'd go and try to fix it by changing up the tubes. It always seemed like magic to me because I knew absolutely nothing about the innards of televisions. All I knew were the public interfaces, the button for on/off, the dials to turn the channel, the dial to turn the volume up and down the antenna, whatever that did, and the little plug that would obviously g
ive it electricity, but frankly, in order to use the television set, that's all you really needed to know. You did not have to know anything about how a television worked. All you really needed to know is how to plug it in and change channels, turn it on and off, and then adjust its volume, and that is exactly how your classes should be treated. All the important behind-the-scenes functionality should be encapsulated behind interfaces like public methods and public properties. Now classes might,
in fact, have private fields like we looked at here in line number 11, or they might have private methods that are used behind the scenes to enable all the magic that goes on inside of that class, but the consumer of the class shouldn't know anything about the inner workings of the class in order to work with the class, to operate the class. All they need to know is what's publicly exposed through the public properties and public methods. In a nutshell, private means that a method can be called
by any other method inside of the same class. I used the term private HelperMethod a number of times accidentally. Essentially, when I use the term private helper method, I'm talking about a private method that's add some additional functionality to those public methods that are exposed to anybody who needs to work with the class through that method. A public method is what's actually going to be then called by somebody outside of the class, some other code outside of the given class, and priva
te methods are only going to be called by members inside of the class. Let me do this. I'm going to paste in some code, recreate our Car class, and here I have a public and a private method. The public method is called DoSomething, and the private method is called just helperMethod. These are not very interesting examples. I want to keep this as simple as possible. Now, from the outside of this Car class, it's just roll this whole thing up here and save it. Now, whenever I want to go here inside
of my static void main, I might want to work with the Car class, so I'll go, Car, myCar equals new Car, and then I'll do myCar. and notice that I can only see the public method DoSomething. Now I might happen to know there are other methods also inside this class, but I can't see them from outside. Their visibility is hidden to me because they're marked as private. All I really need to know is how to use the DoSomething method. If I understand that I can call that, all the implementation detail
s will be hidden from me, but it'll work as I expect it to work. Here you can see that it's merely prints out the words Hello world. Now, whose responsibility inside the class it is to actually display that? That's none of my concern. All I need to know is how to call the public method DoSomething. In a sense, the consumer of the Car class has absolutely no idea that the helper method even exists. All it really knows is that there's one public method and it could call that public method, but it
doesn't know any of the Harry implementation details. Now, I use the term in a sense that in a sense, the consumer of the car. The consumer is going to be a software developer and a software developer is going to be able to drill in and say, "Oh, I see how it's doing its work. It's actually making a call out to this other private helper method." There is a sense in which it is public to developers, but it's private from the perspective of the consumer, which is this main method. It can only see
the DoSomething method, not the private helperMethod. That's all we really mean here. Now admittedly, this is extremely mundane. It's a simple example that's only real value is to illustrate the notion of encapsulation, that we typically want to hide the implementation of our classes behind well-known public interfaces. In this case, a friendly method called DoSomething. The purpose of this lesson is to better understand the notion of scope because we said that once variables, especially variabl
es that contain object references, fall out of scope, their objects will be garbage collected. Furthermore, it's important to understand that there are parts of classes that you have access to and parts of classes that you don't have access to. Now, if you ever decide that you want to create your own custom classes someday, even a library of classes that represent the business domain of your company or of your specific application, it could be a game, you should strive to expose public methods a
nd give a simple, straightforward, obvious way to call the public methods from your class, but keep all the other helperMethod, all the other internals privately tucked away and not available to prying eyes. You don't want a developer to simply go fiddling around inside of all of your methods and use your class in a way in which it was unintended. You want to give them a way to use your class properly through the methods that you've designed and that you've made available through public interfac
es. This also will help to remove any ambiguity in the usage of your classes, and it should be much cleaner as well. All of these things were under consideration whenever the developer's build the.NET Framework Class Library. In the.NET Framework Class Library, methods and properties are exposed using the public keyword. Now, they might also be using private fields and private methods behind the scenes, but you would never know. They may use other types of accessibility modifiers as well. There'
s actually a couple available called protected and internal. However, these are primarily for whenever you're working, either in a rich inheritance relationship between classes and you're building a rich inheritance hierarchy between classes, or whenever you're working with a very large library that's compiled into separate assemblies. That's when some of these other accessibility modifiers might come into play. They're topics that are beyond the scope of this absolute beginner series, but topic
s that I do cover on Developer University. If you want to know more about object oriented programming and encapsulation by all means, go ahead. We are well past halfway through this course. You're doing great. We've already covered the most difficult material already, now we're just adding on details, so you should be encouraged by that, that you're still plugging away at this and you're doing great. We'll see in the next lesson. Thank you. Hi, I'm Bob Tabor with Developer University. For more m
y training videos for beginners, please visit me at devu.com. Previously in this course, I said that the .NET Framework Class Library is merely a collection of classes, each containing methods filled with functionality that we can utilize in our applications, but we didn't have to write. Microsoft has spent tens of thousands of man hours building and maintaining this library of code, and we can benefit from it by merely calling into his classes and methods inside of our applications. Now, the Fr
amework Class Library is massive. Thousands of classes, each with their own set of methods, and so the developers of the Framework Class Library wisely decided to split this library of code up into multiple files. Just imagine if you had to load the entire library into memory every time you wanted to run your application. First of all, it would be excruciatingly slow. Then secondly, it would probably take up the maturity of your computer's memory. They split up the code into multiple files. Thes
e code files are called.NET assemblies. In fact, even the applications that we build, they're ultimately compiling into.NET assemblies. As you can see, I have a new project called AssembliesAndNamespaces already open. I've added two lines of code. If you want to pause the video and catch up, that would be great. In lines 13 and 14, I'm merely printing Hello world to the screen and then pausing the execution of the application. However, even in this application, a executable.NET assembly is being
generated the very first time that we run the application while we're debugging. Now, if you want to take a look at what happens, go to your project's directory and inside of the project folder, you'll see that there's a bin directory. We avoided this very early in this course, but now I want to talk about it briefly. The bin directory will contain both at a bug in a release version, ultimately a release version. The debug version will contain additional files required by Visual Studio to conne
ct to the execution of the compiled executable. This allows us to step through the execution and pause the execution line by line in the Visual Studio debugger. Now, we can additionally, then after we created our application and thoroughly debugged it, we can say I want to create a release version of the application and go to Build Solution in the Build menu, and it will create a version of our application without any of those debugging symbols without that connection to the debugger. If you loo
k at the file system, you might be a little confused to see that it also has a lot of those extra files in there, but they're basically ignored. But that is what's going on behind the scenes. Notice that in each of these cases, we're building an executable file that will run and we could even just double click it and run the application from here like we did before. Now that is different from the type of.NET assembly that allows you to create a library of code that can be shared across multiple
projects. In that case, you'd be compiling a project into a.DLL file extension. We can create a code library. I'll show you how to do that in another video. But at any rate, the.NET Framework has to already be installed on any computer where you want your application to work or to run. Basically, every copy of Windows already has the.NET Framework runtime and the class libraries installed in a location that's globally accessible, called the global assembly cache. Every.NET application can refere
nce the same set of assemblies in that one spot on your hard drive. Now, you might say that whenever you build your application and set up your application, you may not realize that by choosing to create a file new project and then selecting the Console Window project template, you were actually creating references to those files in the .NET Framework Class Library. That's one of the functions of the setup routine for a project template. If you take a look at the references node underneath your
project in the Solution Explorer over here on the right hand side, you'll see that, there are some references already to these things like system, System.Core, System.Data, System.Net and so on. We'll talk about what these are in just a moment, but that's indicative of the fact that we have references into files of the .NET Framework Class Library that the creator of the Console Window application thought we might be or might find useful at some point. We'll come back to that in just a moment. N
ow sometimes you'll need an assembly from the .NET Framework Class Library that has not been referenced and I'll demonstrate how to do that in an upcoming lesson. Or perhaps you need to add a reference to an assembly created by a third party, maybe even yourself. Again, I'll demonstrate not only how to create your own class library, but then also how to create references to third party assemblies as well. Again, there are 10's of thousands of classes defined in the full.Network framework class l
ibrary. In a few cases, the same class name was used, or at least there was the potential for it to be used. When that happened, the creators needed a way to be able to tell one class from a different class and so they introduced the notion of name spaces and name spaces are like last names for your classes. Think about your name or my name. For example, somebody might say, "Bob loves coffee" You might say, "Well, which Bob?" There's like a billion Bobs in the world. But if somebody were to say,
"Robert Theron Tabor likes coffee." Well, that narrows it down. I'm pretty sure that I'm the only person in the world that has that combination of first middle and last name. I could either use the full name, Robert Theron Tabor to reference one person or once we understand the context of who we're talking about, maybe we're talking about only people in this room. Then you might say, well, Bob likes coffee, he's the only Bob in this room, so they must be talking about Bob. The same idea works w
ith your code. We could use the full name of the classes that we need inside of our application. For example, the full name of the console class is actually System.Console.WriteLine. Or the System.Console class. That's the full name of the class and then we're calling the method in that class. However, you'll notice that I didn't have to use the Word system here. Why not? Well, because we used a using statement at the very outset of this code file, which says, 'I want you to look inside of these
name spaces whenever you find a class reference that you don't recognize and so the C-sharp compiler, it finds the Word Console and it says, "Hmm, I wonder where that came from?" It begins to look through the name spaces listed in the code file and it says, "Oh yeah, I found a class name called Console inside of a name space called System." So it thinks, "All right, well that must be the Console class that he's talking about." Occasionally, you might have two classes with the same name, and you
've added using statements for each of these inside of your code file. When that happens, you merely need to disambiguate by adding the full name of the class instead of relying simply on the using statement. You'll notice here that by default, the program that CS file has a number of different using statements. In my text editor they're faded out a little bit, which indicates to me that they're not being utilized at this moment. We could remove unused using statements from our code and our code
will compile just fine. This is a convenience for us, that was set up for us by whoever created the project template for a console window application. To further illustrate this idea, let's talk about how we can go about using the.NET Framework Class Library to do meaningful things and how we would go about finding the source code or the classes we need to do something cool in our application. For example, maybe I want to write data to a text file. How could I go about doing that? Well I might
open up bing.com, and I'm going to type in site:Microsoft.com, so I'm going to limit the search results to just those that are returned by Microsoft.com. This is going to help me find the documentation specifically created by Microsoft as opposed to third party articles or whatever the case might be. So site called Microsoft.com and then I might just say, write to a text file and then using C-sharp. One of the top results are from msdn.Microsoft.com and msdn stands for the Microsoft Developer Ne
twork. This is your primary source of information as a software developer on the Microsoft platform. In this case, here's a how to article that will describe the code that we would need to write in order to write data to a file. Here's a long code example. In fact, it gives us three examples in one and we could use one of these examples in our application in order to write data to a file. We might decide to go ahead and use the second example. It comes close to what we want to work with here and
I copy and paste it into my application and I might remove some of the extra information here just because I don't need it and I may need to modify this path. I believe I created a folder called Lesson 17 for this purpose. Notice that it's going to use a class name file and a method called write all text. In this particular case, notice that we already are given the full name name space of this file class, System.IO.File. What we could do is actually remove that from here and go up and add a us
ing statement for System.IO like so. Notice that, the compiler will find it and will be able to run our application and got a little message there because I was in release mode, lets go back to the bug and start that over again. We don't get any feedback there but if we were to open up our Lesson 17 folder, we would be able to find the text in a text file. Great, so now we can use that little snippet of code to do what we want to do, but notice it all started by searching on msdn finding a code
snippet that we could use and then we can modify it and add our own text here that we want to then we want to write this to our file, so that we start stitching things together. That's one way that we can find the features inside of the.NET Framework Class library that we need is to search on msdn. Let's try one more quick example and let's go back here, back to bing.com and here again I'm going to cycle in on Microsoft.com. Then I want to do c-sharp download html as a string and I might find an
other reference. This is a different style web page. There is one web page on msdn for every class and every method in the.NET Framework class library. In this case, we're looking at a specific page for this download string method and if you were to look at the remarks and some of the additional, the syntax and some of the exceptions that it would throw, what we ultimately get to is a little snippet of code that we can copy and that we can paste inside of our application. That's what happens thi
s time, it does not recognize the term WebClient. Why not? Well, we may not have the assembly referenced in our project, or we may have the assembly referenced, but we do not have a using statement that would include the WebClient class. To remedy this, I'm going to hit "Control period" on my keyboard, and it says that it found this class in system.Net so we can automatically add a using statement for the System.Net class by merely hitting the "Enter key" on my keyboard. Or I can just go ahead a
nd say, let's go ahead and use the full name of the class here, I'll choose the first option using the Arrow keys and the Enter key on my keyboard. Notice what happens, it adds a using statement for System.Net and then notice that the WebClient class is now found. It is obviously in a different color, there's no red squiggly line, so it looks like it found the correct class that we're looking for. Now we merely need to give it a URL so let's try, msdn.Microsoft.com like so and then we will just
write this out to string reply. Then we might even rework our application in attempt to save that into our text file as well. Let's see what we get here. Hopefully, this will work, we'll run the application. It took a moment, but it loaded up a bunch of HTML into our console window. We can see the closing body in the closing each HTML tag. Now, if we were to go back to our folder and find our Lesson17 folder, and open up our text file, we see here is the full web page that we scraped off of msdn
.Microsoft.com. That pretty much wraps up what I wanted to say in this lesson. We are able to utilize the classes and methods in the.NET Framework Class Library and we can find what we need by doing simple searches in bing.com using Psyco and Microsoft.com to find the classes in the methods that we want to work with. Once we find those classes that we want to work with and we find maybe even little code snippets, we can copy those into our program, and we may need to at that point, fix the refer
ences to those classes. Now, in this first case, remember that it gave us the full name of our file class System.IO.File. But in the second case, we had to provide the using statement, System.Net in order for the compiler to find the class that we were wanting to reference and work with. Ultimately we did that with hitting "Control Period" in the keyboard to add a using statement to the very top of our code. We talked about the purpose of namespaces to provide disambiguate between class names. W
e talked about the using statement as a way of creating a shortcut or a context and say, we're not talking about every class in the.NET Framework Class Library. We're only talking about the classes that happen to be in these namespaces. If you find Mr. C# compiler, if you find a class that you don't recognize, look in those namespaces first before you complain. We're going to continue on these ideas in the next lesson. We'll see you there, thank you. Hi I'm Bob Tabor with Developer University, f
or more of my training videos for beginners, please visit me at DevU.com. Now, previously I said that the creator of the console window application project template, added references to those assemblies in the.NET Framework Class Library, that we as developers might find useful for the majority of use cases. However, if we need an assembly containing some portion of the.NET Framework class library, that has not already been added to our project, then we can simply add a reference to it. This is
one of three ways that will demonstrate how to add a reference to an assembly. The first being an assembly from the.NET Framework Class Library. Now there's a number of different ways to go about this. The easiest way, I think, is to go to the Solution Explorer, and then right click on "References" and select "Add Reference". Here you can see there are a series of, I guess, tabs along the left hand side that would allow us to choose from the various types of assemblies that are available to us.
We want to choose the Framework and these are all of the assemblies that are part of the.NET Framework Class Library. Now, and you can see that there's already check marks next to a number of the system.this, system.that, System.Net.Http. These contain a number of different classes each with many methods, and these are just automatically accessible. If we needed something that is not contained here then we could choose, for example, to just select a checkmark next to the one that we want to add
to our project System.Net and click "Okay". You can see that is added a reference to System.Net into our project in the Solution Explorer. Now we can reference any of the classes and utilize any of the methods in that particular assembly. That's one way if we need to access some part of the.NET Framework Class Library. Now, in addition to that, there are libraries that are created both by Microsoft and there are libraries that are created by open source contributors, other companies that are pro
vided for free for very specific purposes in our applications. These are often common features that many applications need that's why they've been open sourced. However, they're available through a special tool called NuGet, which is a repository that's maintained by a foundation supported by Microsoft, but ultimately its own entity. There are a number of different ways to work with NuGet in Visual Studio, I'm going to choose the visual way to do it. I find that to be the easiest for those who a
re just getting started and for me, because I'm a more visual person. There's also a textual, almost command line style interface that would allow you to do similar things and even script these things. Let's go to the tools menu and select "NuGet Package Manager" and then "Manage NuGet Packages for Solution". This will open up a tab, undoubtedly no matter what you see on my screen, it will look different on your screen because this is going under active development for the last few years, and it
has changed frequently. Now, if there were a package that we wanted to add to our solution, we could simply search for it. Typically, we can learn about these things through blog posts and what have you. Say for example, I wanted to access a database from my console window application, and I wanted to use the Entity Framework API from Microsoft. It's available as a NuGet package through this Manage NuGet Packages for Solution dialog. I can select it as one of the options you can see it's one of
the most frequently downloaded. Furthermore, I would then choose which project in my solution that I wanted to add it to, and I can choose the "Install" button. There's some other options as well, I'll leave you to to investigate those on your own. I'm going to go ahead and click "Okay" I agree to the terms for using the Entity Framework. In this particular case, it installed just a number of references to assemblies and copied them down locally to my computer. Now, depending on the type of pac
kage, it could not only contain.Net assemblies, but also sample source code files. It could actually run macros inside of Visual Studio. It could include things like style sheets and HTML, and even graphical assets that it will include your project. This is the second way that we can go about adding assemblies and more to our projects. But the third way that I want to talk about is whenever we want to add a reference to a class library that we created. Now we haven't created a class library up t
o this point, so this is a perfect opportunity to do that and then add a reference to it in our project. What I'll do is start off by creating, New, Project. Let me go ahead and let you see my entire screen here. In the New Project dialogue, I want to make sure to choose C#. Then I want to choose Class Library, notice that I chose the one that doesn't have a little Nu.Get logo next to it, it's just looks like several books in the old C# logo. Now, this will undoubtedly look different to you, but
just make sure that it's a regular old class library. Here we're going to call this MyCodeLibrary and click "Okay", and I'm going to go ahead and say, I don't really care to save my other solution there. Inside of this, you can see that I don't have a program.cs, all I have is a Class1.cs. There's no static void main, and so what I'll call this is the scrape class, and we'll have one public method, so public string ScrapeWebpage and we'll create a version of this where you provide it just the U
RL. Then we'll create a second version of this. Where you provide the URL and file path. In this first case, I'm just going to copy down some of the code that we've worked with previously to create this functionality, where we were actually using this webClient to go out, download a page and then save it to a text file. I'm just going to generalize this. Remember what I did previously when I hit "Control Period" on the keyboard in order to add a reference to System.Net or add a using statement f
or System.Net? The next thing I'm going to do here is actually replace this hardcoded string with whatever gets passed in by the end user. Finally, I'm also going to have to add or resolve this reference to the file class. It's in the System.IO namespace, so I'm going to add a using statement for that. However, in this specific case, I'm not going to write this to a file and this overloaded version of it. In fact, what I'll just do is return whatever's been actually downloaded from client.Downlo
adString. Now, the second version, we'll do something almost identical. Here, let me replace this with the URL, and we'll get rid of Console.WriteLine and we'll go ahead, and write this to the file path that was passed in and then we'll return the reply. Now, truth be told, this might be a good situation where I could actually take these lines of code and create a private helper method out of them. Maybe that's a good idea, let's do that right now. Private string GetWebpage and we'll pass in the
URL here. Now both of these can just call, GetWebpage like so. Here we'll go string return or reply, equals GetWebpage. See what I did there. I was able to use a private helper method to encapsulate the functionality of actually getting the web page itself, and then in this case, I was able to extend the ScrapeWebpage method to include writing that to an actual file path. Now that I've created this, and let me go ahead and rename this file as well by right clicking on it and selecting Rename, a
nd I'm going to choose to name this file scrape as well. I could name it anything I want, it won't matter, because the name of the class itself is scrape. But at this point now I'm going to go ahead and build the solution. It looks like it built. In fact, let me go ahead and build a release version of this. Great. Now let's open up a second version of Visual Studio. I'm going to call this MyClient. This will be a console application called MyClient, and we'll click "Okay." What I want to do, is
to first of all, add a reference to that deal that we created just a moment ago. I'm going to go in right click on references and select add a reference. Here I have some choices. Ideally, I would be able to look and find it in the same solution, will come back to that and do it in just a little bit here. But I may have to go and actually browse through the file system to find this, and unfortunately, this is popping off the screen. However, hopefully we can work our way through this. I'm going
to navigate to the bin directory into the release directory and find my code library, and then I'm going to select the "Add" button and then click "Okay". Now that I've done that, what I should be able to do is get to the scrape class, but it doesn't see this scrape class. I'm going to hit " Control" "Period" on my keyboard, and notice that it will find the correct using statement. The Using MyCodeLibrary namespace. Scrape myScrape equals new Scrape. Now I should be able to go myScrape. and ther
e we go, ScrapeWebpage and I should be able to give it a url. Let's go. That should return a string. String return or actually just value equals. Let's move this over a little bit. Then I should be able to print that to screen. Console or write. Now we should be able to run the application. It takes a moment, but it pops up. What we're able to do there? Well, we created a reusable library now. Whenever we want to scrape a web page, we can utilize this and any of our other projects. Now did you f
ind how inconvenient it was to actually go and search around whatever we wanted to add a reference to it? I had to go, and browse through all my projects and everything. But I do want you to notice one thing about what happened after we did that. Let's go to my projects. Let's find that client and let's navigate into the bin directory. Notice that it copied MyCodeLibrary.dll into the bin directory for the client application. That's one of the things that it will do with any of the third party as
semblies that it we'll utilize. But wouldn't it be easier if we were to start this over from scratch, and we were to create a single solution that had both the client and the code library in the same solution. Let's do that now. I'm going to actually open up a third copy of Visual Studio. Here, let's create a new solution. What I'm going to do is actually scroll all the way to the bottom and choose other project types, and choose Visual Studio Solutions, and find a solution. This might be in a d
ifferent place, so you may have to hunt around for it, but you ultimately want to choose blank solutions that should be available to you. We're going to call this a Lesson 18. The solution's name will be Lesson 18, but we're going to do is add projects to the solution. The first project that I'm going to add, and there's a number of ways to do this like add, but it goes off to the right hand side of the screen, I could add new project, file add New Project and then we're going to choose the clas
s library. We'll call this the ScrapeLibrary. Then I'm going to choose to create another project and add it to our solution called app type Console Application. This will be the ScrapeClient. In our ScrapeLibrary, what I do just for simplicity's sake, is actually go to the work that we've done here a moment ago, and I'm going to copy all of this like so. Let's come back here, and I want to paste all this in, like so. Yes, I'm going to have to resolve these class names by adding using statements
here and here as well. That should work. Looks like I actually lost my class name, so let's go public class Scrape. Then let's make sure to put everything inside of it. There we go. Now we get it working, and I'll rename this as well to just scrape. I could have left it, call the class one to but that'll work just fine. I'm going to go ahead and build that right clicked on the project name a select to build. Now what I want to do in the client to utilize that class library, is I need to add a re
ference to it. So here again, I'm going to right click and select add reference. This time we go to projects, and notice if solution is selected, the Scrape Library will be an option. I'll choose that and click "Okay." Now we can utilize ScapeLibrary in our application. Let's go ahead and just type in the "Word" scrape., and it's not going to find it. The Here Control period, and I need to add a using statement, since I renamed it. Now it's called ScrapeLibrary. I'm going to add the ScrapeLibrar
y namespace too, using statement to the code file. In fact, I don't have to do all that right. I can just copy and paste it from the previous client, like so. We can rerun the application. It says a project with an output type of class library cannot be started directly. Why do you suppose that happened? Well, because there are actually two projects now in my solution, and you can't execute a library, correct? So what we need to do is right click on the client project and select Set as Startup P
roject. It's going to close that, when we attempt to run the application. It'll work. Furthermore, if we were to make any changes to how the library actually works, let's say what could we do here? That's interesting. Let's do this. We'll make a change in one spot and then I'll go content plus equals THAT'S ALL FOLKS for the very end of that string this return. I'll return content this time. Let's make sure we have everything there. We've made pretty big change to the application. Now when I run
the application, it will recompile the DLL. It will add it to our project and at the very end, it adds, "THAT'S ALL FOLKS". The only thing I could think of off the top of my head. Hopefully now you can see that there are several different ways to add assemblies. If it's part of the .NET Framework Class Library, then obviously there's a way to do that. If it's a free or open source, package that's available from NuGet, we can use the NuGet package manager or we can create our own third party cla
ss library and then add a reference to it by browsing. Or if we were to create the client and the library inside of the same solution, then we can reference it in the add reference dialog. But just under the project solution option, and we get the added benefit of being able to make updates, not having to go through two copies of Visual Studio to updated. It'll update the next time we hit, run it or recompile it and everything. That's pretty much it for this lesson. We'll continue on the next le
sson. Will 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. Previously, we looked at arrays which allowed us to keep a sequence or group of related data together inside of the same variable, so we would create an array by providing a data type, and so each item in the array had to be of that data type. We would also provide the number of elements we expected in the array by defining that number between a se
t of square brackets. Now that we have that predefined sized array, we could add items into each element of the array or retrieve values out of each of the elements of the array by indexing into the array using a zero based index to index in and address one specific element of the array. Now, once we have the data collected into an array, we could do some interesting things. We could iterate through the array and investigate each element in the array, or we could even pass the array around as if
it were one variable. Pass it in, for example, as an input parameter to a method. But you recall that time, I also said that at some point we would talk about collections. I even gave collections a nickname, calling them arrays on steroids. I think you're going to agree after this lesson that collections are great whenever you're working with all data types, especially those custom data types that we've been working with up to this point in this series of lessons. For example, the car class tha
t we created ourselves. Now, as far as the .NET Framework class library is concerned, it will often use both arrays and collections, depending on the need. But I think you will probably wind up preferring to use collections in your applications because of the rich filtering, sorting, and aggregation features that are available to collections through a technology, a language called LINQ L-I-N-Q, which stands for the language integrated query. It was a very innovative feature whenever it was first
introduced back a number of years ago in C-sharp and other .NET languages. Other languages have since implemented something similar to it. But we're going to dive into that topic of LINQ and what you can do with it in the very next lesson. But first of all, let's talk about collections. We're going to talk about two collections, specifically lists and dictionaries. Now, truth be told, there's probably a dozen additional varieties of collections that you could use for very specific purposes. The
y each have a superpower. They each have a very specific use case where they're intended to be used. I find myself using lists and dictionaries 95 percent of the time. So we're going to focus on those for this lesson. But after this lesson, by all means, feel free to go off and learn all of the additional collections that are available to you and what they can do that's a little bit different than the list in the dictionary. Suppose that I have a number of cars on my car lot and I want to write
an application that allows me to manage them. So I need some way to collect all of the individual instances of the car class together into a single array or collection. Now again, I might use an array of cars, but I think I'm probably going to choose to use a collection because of the added features that I'm going to gain using collections. We're going to talk about a bunch of different types of collections, but I want to start off with a conversation about an older style of collection that's no
longer used anymore to show why there's a newer style collection that's available, and it'll help you maybe understand that idea a little bit better. As you can see, I've got a project called Working With Collections already set up here. Please take a moment and create a new console window project. I'm also going to paste in two classes that I've defined simplified version of the car class that we've used before. Then also, I'm going to create a book class, as you can see there at the bottom. V
ery simple classes. The next thing that I'm going to do is actually paste in some code to actually create new instances of each of these classes and then populate their values. You may want to pause the video yet a third time and copy in the code that I have copied to screen there as well. The very first thing that I'm going to want to do is to work with a collection and I'm going to work with something called an array list. Let me just say this about array lists that they are dynamically sized,
which is one of the great benefits. You don't have to do anything to say, I need to add one more item and another item and another item. Remember with arrays, I said it was possible to resize an array, but it's a little bit of an advanced operation. Not so with an array list. That's one of the big benefits. You can just keep adding items to it and it'll be just fine. It will also support cool features like sorting. You can easily remove items from the collection and so on. Let's go ahead and cr
eate a new instance of this array list. When I do notice that we don't already have a reference or a using statement to a namespace, so what I'll have to do is hit Control period on my keyboard, and you can see that it is in a namespace called using system. collections. I'll go ahead and add that namespace to my project and so will create a new one called myArrayList equals new ArrayList, like so. Now that I have my array list, I can begin to add items to the array lists like, for example, the f
irst car, and then I can add a second car like so. Now, one of the problems with the old style collections like the array list is that there was no easy way to actually limit the type of data that would be stored inside of the array. For example, I want to work with automobiles, but I might accidentally add a book into the array and it will work just fine. There's no complaints. The old style collections are not strongly tight in so much that you can put anything inside of a collection. At first
glance, that might seem great. But what if I wanted to actually then print out a list of all of the cars makes and models? Let me start by at the very bottom here type Console.ReadLine so we can get through that formality and then I'm going to just do a for each. What am I going to work with here? Let's just say I'm going to work for each car car in my array list. Then I might do a Console.Writeline, and let's just go car.Make like so, and print that to screen. You must run the application, and
we will get an exception whenever we hit the third item in our array list. Notice that it is printed first to the screen, but when we get to the book, it says that there's an invalid cast exception. In other words, we could not convert a book which was the third item in the array list into a car, so when we get to this spot as we're iterating through each of the items in our array list, we're going to hit a problem here. The fundamental problem is that we allowed our collection to store somethi
ng other than cars, so we cannot work with these collections in a strongly type fashion. Now, what I can do, one of the neat features here, is that I can actually remove that item prior to going into that for each list, and we should just be able to execute the application without problem. That is at least one of the good benefits there. But unfortunately, the downsides outweigh the benefits. Let's go ahead and take a look at the newer style collections. The first, I said, was that we were going
to look at a list, and more correctly, we're going to look at something called a generic list. Often, you'll see it referred to as List of T, like so. That of T in the term generic might require a little bit of explanation. When done, that was first released, the first set of collections allow you to put anything you wanted into them, like we saw here just a moment ago. Now, it might make sense in some contexts, but typically, it doesn't, and it leads to potential errors like you saw. Now, at s
ome point, then, C# introduced the notion of generics, and specifically for our purposes, they released a series of generic collections. A collection is essentially generic but it requires that you make it specific by giving it the data type that should be allowed inside of that collection. We have a generic list but we're going to make it a specific list to car so that we can't even add a book to that collection. Let's attempt to do this one more time. This time we're going to go List, and noti
ce that I'm using angle brackets, and in-between the angle brackets, I'm going to say what data type I want to use. In this case, I want to use the car data type. List of car called myList equals new List of Car, like so. At this point, we can go ahead and add the car1, just fine. We can add car list to myList beginning at car2, just fine. But what happens when we attempt to add the book into our list? Well, at the point when we attempt to add the book to the list, we get an exception. We hover
over and it says it cannot convert a book to a car. That makes a little bit more sense. It is specific to a car data type, so we cannot add a book to that list. But from this point on, we can work with it now with some confidence, so each car car in myList, and we can use the car.Model, like so, and we would get what we would expect here, create a list of our car models. That's one of the big benefits of working with a generic type, is that it allows us to work with the specific data type and on
ly allow those types into our collection. This is probably the most popular of all of the collections available. But I'm going to show you one additional collection called the dictionary. A dictionary is similar to, think of Webster's dictionary, where you have a word and you look it up in alphabetical order and find the word that you want definition of. Then once you find the word, you can look to its right and it will have the definition. There is a key, which is the word itself that we want t
o look up, and then there is the definition next to it. There are two components to each entry in a dictionary; there's the key and then the value itself. Typically, when you see a generic dictionary mentioned, it's going to be listed like this Dictionary of TKey, TValue. In this case, what we'll do is specify the data type of the key. This allows us to find one specific item by the key. Now the key should be something that is unique to every entry in the dictionary. In the case of people, there
might be some identifier. It could be a customer ID in your system, it could be a Social Security number if you're in the United States, but something that uniquely identifies one entity inside of that dictionary. Then the value can be of any data type. In the case of, again, a customer, you might have the customer ID being the key, but the customer object itself is the value that we actually want to get access to. Now, in our case, this seems a little bit weak because our car class only has ma
ke and model, and we know that we can have multiple cars that have the exact same make and model. They may have different colors, they might have been created in different years, but you can have multiple cars in the car lot that have the exact same make and model. Neither of these are good candidates for keys, but there is something called a vehicle identification number. Let's do a prop string and let's call this VIN. That will differentiate every car in the world that's been created. What I'l
l do is come back up here to the definition in the car1.VIN and I'm just going to use a very short VIN number. I think they are typically like 18 or 24 characters long, something like that; I'm not exactly sure. But this should uniquely identify every car in the world, especially every car in our car lot. Now what I can do is create a dictionary of my cars by starting off and saying something like dictionary, and they were going to give you the two data types. The VIN will be of type string, and
then the actual value will be of type car. We're going to call this myDictionary equals new Dictionary of String Car; notice the InteliSense help me out by essentially giving me a lot of that, and I can just hit the semicolon at the end of the line for it to type out that entire phrase. Now that I have this, what I can do is go myDictionary.Add, and we'll do car1.VIN and passing car as the actual value. The car1.VIN, again, is our key into the actual car1 itself. Likewise, we'll go add car2.VIN
in car2. At this point, here, if I were to attempt to find a given item, so Console.Writeline, and I need to find a specific car in my car lot, I can allow a user to type in the VIN number and I can look it up in the dictionary quite easily. Then there's a number of different ways to go about this, I think probably one of the easiest ways actually. Let's go back and not use the dot. Here, I'm actually going to use the key itself, so we'll call this B2. Then now we can reference a specific item
in the Dictionary of Type car so we can get the make, for example, and print that out to screen, like so. We were able to find the Geo that way. Hopefully that makes sense. Let's continue on, if you recall when we originally were looking at, let me comment all this out. We were looking at a raise, I said there's some interesting things you can do to initialize an array with values like we see here. We're creating an array of strings called names and to initialize it, I give it a collection of na
mes that are common to limited. Now I have an array that has four elements in it and it's already been initialized with the values. You can do the same thing with the objects to initialize objects at the point of instantiation, to do that will use an object initialization syntax. In fact, let's go ahead and just approve this all works is coming out everything we have up here as well and get rid of the cars in the book, we'll come down here and go car1 equals your car and then notice what I do, I
use that same syntax the curly braces and inside of here, what I can do is actually define all the values to make equals. Let's just dream large here and go make in the model would be a 750 and we'll make it an ally and then we'll also give it a vehicle information of C3 like so. Now I've done the actually three things in one line of code, I create a new variable called car I create a new instance of car and computer's memory now I'm getting access to that address in memory by using the car1 la
bel, the variable name and then I go ahead and populate the properties of the car object at the moment that I create that new instance by using this object initializer syntax. Some people don't like this. It looks like it might be doing too much in one line of code, but I think you'll find that if you ever do need a hard code, examples like I do frequently that the shortened syntax actually saves you several lines of code and it's just fine it's valid code Let's go ahead and while we're working
here, let's go ahead and create a Toyota. We'll set the model equal to a 4Runner and we'll get to that a VIN of D4. Like so and now we can work with the cars just like we did before but in and of itself, this might not be so interesting but this is the object initializer syntax. We can take this one step further when it comes to working with collections, we can use collection initializer syntax. I want to point out one other thing that we didn't have to use a constructor to make this work like w
e looked at before that we're able to regardless of the constructor, go ahead and set these attributes just like we use the syntax there. Well, let's now talk about a collection of initializer which can look a little hairy, but it's essentially the same thing we're just taking it to the next level here. In this particular case, let's go ahead and create a list of car called my list equals a new list of car. Now, at this point, what I can do and notice that I put this on separate lines here, I ty
pically might keep this on the same line just for my own sanity here and now inside of this new empty list of cars, I can create a series of car objects like so. In fact, what I can do at this point then is use an object initializer inside of that, so here we're going to make vehicles lose it all then we'll set down the model equal to Cutlass Supreme and then the number of a set that equal to E5, so comma and then we'll create another new car to add to this list of cars and we'll set its object
initializer setting it's make equal to Nissan and its model equal to an Altima then finally, it's VIN will equal F6, something like that. Now what I've done, all in one line of code essentially is I've created a collection and I've added two objects and in each of those objects, I went ahead and already initialized all of the property values. There's a lot going on there and just that one line of code. Great. At any rate, just wanted to recap the things that we talked about in this lesson. First
of all, we talked about the difference between arrays and collections and I promised that there will be a more obvious set of features that are available to collections, which we'll learn about in the next video. We talked about the old style collections versus the new generic collections. We said generic collections are superior because they allow us to make sure that we're only adding specific types to our collections so we make a generic collection specific by passing in the data type that s
hould be allowed to be referenced inside of that collection. Then we looked at object initializer just a shorthand syntax for initializing the properties of a new instance of an object and then finally taking that one step further within a collection initializer where not only are we creating a new collection, but then initializing it with new instances of the car collection. In both of those cases then we are using object initializers. We can do it all on one line of code. Now, honestly, unless
you're building a lot of example code like I do, you may not see this as often unless you are creating some hardcoded objects for use within your application. But I wanted you to be aware of that syntax nonetheless, because we're going to use it again in the next lesson and we'll see you there. 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, we're going to look at link the language integrated query sy
ntax that was introduced some years ago to provide a way to filter thoughts and perform other aggregate operations on collections of our data types so will demonstrate two different styles of Links Syntax there's a query syntax that will resemble the structured Prairie Language sequel for querying databases. If you're already familiar with sequel, this will at least feel familiar. Then there's also a method syntax which might feel more familiar to C-sharp developers. However, there is one little
strange nomenclature thingy that we got to figure out but I think it's pretty easy. I think I have a good way of explaining it to you and hopefully you'll understand what it's trying to do there but what I'd recommend is you find the code for this lesson there should be a before and after folder and you want to copy the code in the before folder in your project's directory and then open it up and you'll be where I'm at right now. In the understanding on project, you can see that I merely create
d a car class and then I also have here a collection initialized class filled with cars filled with attributes that will be able to search and sold on and that'll give us something to work with here. What I want to do to begin with is to show you a comparison between links query syntax then links method syntax to do the exact same thing. You'll see the obvious difference and we'll talk about the ways in which they're different but let's begin with a query where we want to find all BMW in this li
st of cars called my cars. It's as easy as this, and we'll talk about the VAR keyword here in just a moment but BMW equals from car any cars looks from car in my cars, where car.Make is equal to a BMW, that's car. Now, let's come down here and print all those guys out. Let's go console that right line and let's provide the vehicle information number let's do zero on on, actually, let's do this. It's good for each tab VAR car in my in the BWS Console.WriteLine and then we'll go car.Model and car.
VIN. Let's go ahead and add some of our replacement characters in there. Now, let's go ahead and run the application and we see that we get three cars that have been returned, so of all the cars, I think there's five or six three of them with those VINS A1C3 and E5 are BMWs. If you take a look at the data, that would be correct. Very quick, concise way of finding only those cars that match that criteria. What if we wanted to add additional criteria? Say, for example, we wanted to also see where
the cars year equals 2010. We could do that and rerun the application and now we see that it just finds one of the BMW cars was created in 2010. It is this last one, the 555i. That is the language integrated query syntax, the query syntax of Link. Let's go ahead and comment that out and compare that to the method syntax and so here will go far. BMW equals myCars.where. This will give us all the BMWs, so let's go and run that. It gives us the same three that we got before. Now, what if we wanted
to also find only those where the year is equal to 2010? We would do that. You can see we found just that E5; that last one. This might take a little explanation here. For the moment, let's just ignore this last part, we'll talk about that in a moment. But what you see here, in fact, the whole thing in between the opening and closing parentheses is called a Lambda expression, and you can think of it as a mini method. Essentially, what will happen is, you say given p, so given an instance of the
collection, only return back to me those instances of car where the make is equal to BMW. See how easy that is? Again, just a mini method. You could think of this as like the input parameter, and then this is just some condition. When it's true, then return that instance and add it into this little collection over here, so now that we have a subset of all of the available cars in our car lot. Furthermore, I just added the logical and operator and said, and make sure also that it was in 2010. Wel
l, that filters out two of them. Again, a Lambda expressions are just many methods, so for any given item in the collection it has to match that criteria. If it does then we can add it to this little subset collection over here that I'm calling bmws. The var keyword it has a very different connotation in C# than it does in other programming languages. Here I would ask that you forget what you know about var from maybe JavaScript or Visual Basic or some other programming language, it does not mea
n the same thing. In this case, the var keyword says that we're going to let the compiler figure out what the correct data type is. I'm not even sure what gets returned from this little query that we do here. If you were to hover your mouse cursor over the where, you can see that it's going to return back in i numerable car. What's that? Not entirely sure, doesn't really matter. I don't care what it is, I know that it is a collection of cars. To prove this point we'll talk about this in just a m
oment a little bit later where the var keyword can really come in handy because we truly don't know what it is that's being created by our link queries. Again, the var keyword it's still strongly typed. We're just going to let the compiler figure out what the type is at the point when the code is compiled. Let's move on, and let's take a look at a few other examples. I may want to find an ordered list of cars, so I might go orderedCars equals from the car in m Cars, order by car.Year descending,
select car. That's how I would take all of my cars and order them in descending order by their year. Let's just change this from bmw, let's put this to orderedCars like so, and this might help if we actually saw the year itself so I'll add in the car.Year as well. Let's go ahead and run the application. You can see it starts at 2010 and in descending order, works its way back to 2008. Awesome. That same query if we were to do it in using the methods syntax instead of the query syntax, it would
look something like this. var orderedCars equals myCars.OrderByDescending. Given each item in the collection only return those or actually order them by the year like so. We should see the same grouping and we do. Starts at 2010 and works its way back to 2008. Again, in my opinion, this is more concise. The only conceptual hurdle you've got to jump over is just make sure you understand what a Lambda expression is. In this particular case, it's not a filter, we're just saying, given each item in
our collection, we want to order by this particular property; the year and then add that ordered item to our new collection of cars over here. Now, there's a lot of interesting things that we can do, and I'm only going to work with the methods syntax from this point on. The first we might do something like this, for example, if we want to find just the first item, so let's go ahead and grab this and maybe we want to find the first item where the make is equal to a BMW like so. This will give us
the first car; the first BMW car in the list that it finds. Let's go ahead and console. In fact, let's change the name of this to firstBMW, so Console.WriteLine. All that right. firstBMW. just a VIN number should be sufficient. Let's run that. We can find that the first BMW in the list was A1, or we can do the first BMW, and we can actually start by ordering by descending given the year. You can see I'm chaining these together, we've talked about method chaining before. This will return a collec
tion of cars and then this will return a single car in that collection. Then we'll print that single items then out to window, in this case E5. The list is first sorted and then we grab the first one that matches our criteria of BMW. That's how we can use first. We're going to comment that out. We can also do something like this, Console.WriteLine., and inside of here, let's go, myCars.TrueForAll and say the year is greater than 2012. We need one more right there. Is it true that all the cars in
my car lot that every one of them is greater than 2012? That would be false. Well, then how about are they all greater than at least 2009? That's still false because we have at least one that was created in 2008. If we were to change this to 2007. Are they all at least greater than 2007? True, so that's true for all. Very helpful in order to aggregate and look across all of them and see is this true for all the items in my list. We can also even do something interesting like this instead of doi
ng this for each statement where it's essentially what, at least two if not four lines of code we can create a for each like so. myCars.ForEach and then inside of here for every item, let's just do a Console.WriteLine and in here, I can do p.VIN and p.StickerPrice. Let's go ahead and do that. In fact, we'll just do that as well, one and zero. Hopefully, that all makes sense. Now let's run that and see what happens. Here we are, we're able to list them all out and format their values, so you see
how much more compact this looks than what we were writing here. We do it all in one line of code. Again, we're passing in for every single item in our collection just call Console.WriteLine and then use that particular item's VIN sticker price inside of our formatted string. Here's another interesting example of this. Maybe in each case we want to go, so myCars.ForEach. In fact, here let's do this before that line of code. Let's keep that one and then go myCars.ForEach. In this case, I want to
perform an operation on each of the data inside of there, so I might take the sticker price and reduce it by $3,000, actually let's go minus equal to. This will take the sticker price and subtract $3,000 from the sticker price of every car in my collection. You can see now what was if we could get a comparison going here. See, unfortunately not going to be very easy to do, but you can see that what was $55,000 is now 52,000 what was 35 is now 32,000, and so on. Again, a lot of functionality in a
very small space. Let's continue on with this thought and go and do something like, myCars.Exist. Do we have a car in our car lot where the model is equal to the 745LI, true or false. Here let's do a Console.WriteLine and let's see if they turn true or false? Yes, we have at least one item in our inventory where the model is equal to 740LI. Now here's another good aggregate function. Here, let's just do Console.WriteLine, and let's go, myCars.Sum, and here we'll say, sum up all the sticker pric
es. Let's see what the total value of our car lot is right now. You can see that it's about 247,000 so actually, there should probably be a better way to format that using a format code but hopefully you get the idea. We're able to sum up a single field across all objects in our collection of cars. There's so many other things that I can show you, but I don't want to overwhelm you, but I want us just to go in one ear and out the other for now. This VAR keyword we've looked at, and I said that we
use it because we want the compiler to figure out what the data type is. Sometimes it's easy for us to figure out what the data type of something is. Sometimes it's not so easy. To illustrate this, let's do a Console.WriteLine line and what I want to do is call on myCars, I'm going to call the get type. In fact, all data types in.Net have this GetType method declared because it's declared on the grandparent of all objects called System.Object. It defines this method called GetType, which will t
ell us what the type of a given object is and we can print it to screen. In this first case, what is myCars? Well, myCars is a generic list of the car data types so this understanding link is the name-space and specifically, though, it's the car type. We're basically saying this is a list of T, a list of car. That's what's being printed out whenever we're looking at what the cars are, and that's pretty easy to see because we define it here. But once we perform an operation like one of these here
, let's just see ordered cars and copy that again and stick it down here, and then I'm going to do Console.WriteLine, orderedCars.GetType and it'll show us what the data type is for ordered cars. Let's go ahead and compare the two. Now, in this case, you can see that we're no longer dealing with a list of car, even though under the hood we know we're working with a list of cars the way that it's represented in.Net is that it's actually ordered enumerable so an ordered list of the LINQ.Car, Under
standing LINQ.Car. Again, that makes sense. That's an ordered version of cars. How about just a regular old where statement. Let's do that. Let's copy that and see what the data type of that is and then do the same thing here. Let us see what that is. Let us go and run the application again. Here is this third one. The second one was an ordered enumerable, then the one where we just called the where was an enumerable plus the WhereListIterator. So things are starting to get a little funky here.
It might be difficult for us to be able to express this ourselves if it were not for this var keyword. The var keyword is essential to help us to be able to create these very complex queries, and not have to worry about what the data type of it is that's returned. We know that it is a type of list. It is an innumerable list, whether it is ordered or not, and we can follow each our way through it or whatever the case might be. Now the last thing that I want to demonstrate, is I am going to take t
his first query here, and I am going to pop it all the way the bottom. If this stuff doesn't make sense, don't worry about it too much. I wanted to go in one ear and out the other, just to explain again the value of the var keyword. In this case, let's change something about this. Let's call this my new cars. Here, I am not going to return cars. I am actually going to do what's called a projection. I am going to only take certain values, certain properties of a car, and I am going to project the
m into a new data type. What's the name of the new data type? Where am I defining that data type? I'm not going to define the data type. It is an anonymous type. What's the name? I have no idea, it is anonymous. We can define types at runtime and only choose those properties that we need in the type for the moment. Why may not be obvious just yet, but I want you to understand that there is this idea, what we can do here. In this case, let's pull out just a few things like the car.Make, car.Model
. That is all we want. We are going to leave all the other attributes of car alone. We are going to only take these two values, put them into a new anonymous type. Where is the type defined? Nowhere, we just made it up off the top of our heads, and we are going to save each of those anonymous types into a new collection of anonymous types. Let's go. Console.WriteLine, and then take a look at newCars.GetType, and let's run the application yet another time. This time you can see that we also here
have an innumerable plus where select list iterator, whatever that means, but then notice that the data type involves something called an anonymous type that has two attributes, two string attributes, which would be the make and the model. I say all that to say this, that whenever you're working with LINQ, there is a lot going on under the hood to make it all very easy and accessible, but it all depends on defining your types as var, which says, let the compiler figure out what the type is, we a
re not so worried about it, because the data type might be so crazy that we can't even comprehend what it is. Hopefully that makes sense. Just to recap the things that we talked about, we talked about the difference between the query syntax and the method syntax. We looked at a number of different examples of the various LINQ extension methods that were available. We saw how we could break apart an individual Lambda expression, to better understand that essentially we are saying each item in the
collection, run this little mini method against it, and return back a given item that matches that criteria. Then we looked at how to tell what the types were and what the value of the var keyword is, and then we looked at anonymous types. We covered a lot of ground, I didn't explain everything in great detail. But the key here is just to look at that little formula and try to understand what it means. Look for examples online, make yourself a little cheat sheet, and you should be able to utili
ze these methods inside your own application. That wraps up LINQ. This will be the hardest thing that you have to think about today, I guarantee it. That is it, we'll see YOU in the next lesson. Thanks. I am Bob Tabor with Developer University. For more of my training videos for beginners, please visit me at DevYou.com. In this lesson, we will introduce a new decision statement, the if, else if else statement, and the conditional operator are both great. They work best when there is only a handf
ul of things to evaluate. But if you start needing to evaluate many different potential cases, you might find that the Switch statement is a little bit more concise and keeps things a little tidier. That would probably be one of the only reasons why you would use it, and I will show you a second reason why in this video as well. We will come back to the switch in just a little bit. But first, I want to talk about a special data type called an enum or an enumeration. Typically, we want to limit t
he possible values of a given variable. Now, admittedly, we're already limiting the possible values that can go into a variable by virtue of the fact that we've given it a specific data type. However, even within that, I may want to limit the number of possible values to just a handful. Typically in software development, you want to limit and constrain your data to ensure its validity inside of your system. An enumeration is a data type that limits and constrains all possible values to only thos
e that are valid and have meaning within our system. For example, we might want to keep track of series of to-do items. Maybe that is the type of application we're building, and each to-do item is represented by an instance of a to- do class. We may want to keep track of the current status of a given to-do item on our list. We may want to constrain the possible statuses to maybe like five, that the task has not been started yet, or it is in progress, or it is on hold, it is been completed, or pe
rhaps it is been deleted. There might be some other statuses, but you can see how I may want to just limit the number of options that are available for a status field or status property of my to-do class. We could do this in a number of different ways. We could just concoct a numbering scheme, where one always represents not started, and two represents in progress. I refer to those as magic numbers. They may have some meaning in the system but it's not readily obvious if you're reading the sourc
e code. As the developer, you may have to look up at some external reference, maybe some code comments, and who knows, maybe they are not even current anymore. Maybe things have changed since whoever wrote those code comments originally wrote them. I may need to reference or look through a number of different code to ensure that what number one means in the system, what number two means in the system and so on. The same thing can be true with strings. I could just use a literal string to indicat
e the current status, so I could use a literal string, not started or in progress. But the problem with literal strings is that somebody can misstype them, or there could be a space, and not started one time, and then somebody uses not started without a space the other time. If you are looking for all those items that have not been started yet you may have a hard time finding those that have not yet been started or in progress because they are not spelled correctly or whatever the case might be.
The great thing about an enumeration is that it gives us a textual equivalent to a numeric value so that it will remove any ambiguity inside of the system. As developers, we know exactly what we are working with, and yet behind the scenes, it is still working with the number. Enumerations are used frequently in the.Net Framework Class library for the very same reasons. For example, you can see here that I have a project, EnumsAndSwitch, and here again, if you look in the code folder for this le
sson, there should be a before and after. You want to copy the project from the before folder and copy it into your project's directory so that you can catch up to me where I am at at this moment. You can always pause the video and type all this in if you like, it can quite a bit of typing though. You can see that in this project, I have already created a to-do class, with a description of each to-do item, the estimated number of hours it should take to complete the to-do item. Then notice that
I have a status of type status. Where does this come from? You can see directly below, I have created an enumeration called status, and I have not started in progress, on hold, completed, and deleted. Did you notice as I hover my mouse cursor over it, that each of these values are given a numeric values? Not started equals zero, in progress equals one, on hold equals two and so on. If we were to store these values somehow in a database or a text file, those are the values that might actually get
stored. However, they will be translated into this more textual format so that when we are actually working with the data, as you can see here in the static void main as we are creating a new list of to-do's using the collection, initializer or syntax, here, I am setting the status equal to either completed or in progress or deleted or not started and so on. Visually, it's much easier for a developer to work with those options in a more textual way. Now, the.NET Framework Class Library will use
enumerations extensively. In fact, even in the Console window, if we were to set the foreground color, notice that IntelliSense automatically pops up to the console color enumeration. See, it says enum over there. Let's see. I don't think you can see that. Let's go up a little bit here. All right there. Now, you can see the word enum right here. It's a console color in enumeration. When I hit the member access operator, the period, it will show me all the colors that we can choose for the foreg
round color of our console window, so I might choose dark red. Again, enumerations are great because they are descriptive and they limit the number of possible values for our applications, for the properties of our classes. The next thing I want to talk about is the switch statement, and these two are going to marry together here in just a moment. But a simple switch statement is going to look something like this. In fact, I'm just going to go switch Tab Tab, and that will create essentially the
outline for it. In this case, we can use an individual to do item and choose it's, or let's say estimated hours. If the estimated hours are, for example, case four, then we might perform some operation until we hit the break statement. Or we could go case five, so we could perform something and then we would hit the break statement and break out. There's also a default case, that would be the catch all just like the else statement and the if else, if else, construct. But the most important aspe
ct of this, is the construct of the switch statement. You have the keyword switch, then you have a variable that's under evaluation and then a series of cases where we would try to match it up with one of these cases, and then we use the colon after that case. We write our code below it and then we use a break statement to break out and continue on our execution of the code. Now we might choose to, for example, do something like this. This makes a little bit more sense to work with the statuses.
In this case, we might go status.completed. We might do something versus case studies.deleted and we might perform some operation there and so on. Now the beauty of the switch statement and the enumerations are that they can conspire together here. Watch what I do. I'm going to type Switch Tab, Tab and then I'm going to do, which is each the items in the to do collection dot status, and then I hit the "Enter" on my keyboard twice. The second time I hit "Enter", see the macro that will actually
blow out, each of the individual statuses so that I can write code associated with each status. Isn't that crazy? Now, I can do here anything that my business logic would require. I have an idea though. Let's use the foreground color and change it up for each of the individual to do items. It can be as simple as this. Let's just copy this, and we'll put it here for each of these statuses. Then here at the very end, we will actually then do a console.write line of the actual item itself, the todo
.description and here will change up the color. If it's not started we'll leave it as dark red, if it's in progress, we'll use green. If it's on hold, maybe we'll use the dark red. Let's use the red here in the dark red there. Completed, let's mark those as blue and if it's been deleted, we'll mark that with yellow. Now let's go ahead and save and run our application. You can see we have a very colorful list of tasks that are color coded by their current status. See how cool that is. In this les
son, we talked about enumerations and why we would use an enumeration to constrain the possible values for a given property of our classes. We saw how it was used in the.NET Framework class library, one little instance of it here, where they've created their own enumerations. Just be aware of as you're trying to work with a given class and its properties, always look at, for example, in this case, what data type it is. This is a data type console color and typically IntelliSense will point you i
n the right direction. As you hit the equal sign it will pop down to that data type, that enumeration so that you just hit the period then you can make your selections there. That's a really good hint. Then we looked at the structure of the switch statement, where we're evaluating something in between the opening and closing parentheses. We looked at the body, the opening, and closing curly braces, the entire body of the switch statement. Then inside the creation of the number of cases, each cas
e equating to one possible value of the item that's being evaluated and then a colon and after that, then any of the code that we want to write, and finally, a break line which will pop us out of that switch statements body. Then finally, we saw that there is a catch all the default colon, which we can use to write any code for cases that we haven't accounted for in any of the other previous cases. That wraps up this lesson. Doing great work, getting close to the end now. You feel pretty confide
nt C-Sharp. You've got the majority of it under your belt. Just a few more topics we want to cover, and then we'll wrap this up. We'll see 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 devu.com. In this lesson, we're going to talk about handling exceptions that occur within our applications. We'll discuss what can go wrong, why things go wrong, and how to build resilient applications that are imperviou
s to crashing through the use of C-Sharp's Try Catch block statement. When the compiler catches a data type mismatch or an unresolved reference to a class or some malformed C-Sharp instructions, it'll refuse to compile your C-Sharp code into a.NET Assembly until you fix the problem. These type of errors are called compilation errors, and that's not what we're talking about in this lesson. However, there are other types of errors that happen during runtime or in other words, they happen when the
compile.NET Assembly is actually in the act of executing. Honestly, there are countless number of reasons why you could encounter an exception while the application is running, depending on the kinds of things you're trying to do in your application. Many times these things are outside of the direct control of the software developer. For example, if your application can't read or write to disk because a folder or a file is missing on disk where it expected to see it, it could trigger a runtime e
xception. Or maybe the files corrupt, or maybe the network access to that resource is unavailable, or it attempted perhaps to access a database, and it couldn't find something in the database that it needed. A table, a column, whatever the case might be, because the structure has changed of the database out from under the application. All of these things and many more could cause the absolute failure of your application, and the user will see a nasty error message at runtime and the frustration,
say the developer. In some cases, the developer may have not even foreseen that that could have potentially been an issue. If they didn't see that it could be an issue, they couldn't have accounted for it. Maybe the developer for example, allows the users to type in a country, but the user misspells the country name. Now, maybe they did that intentionally or unintentionally. Perhaps they maliciously use numerical characters instead of alpha characters. But as a software developer, your job is t
o make sure that you account for all of these possibilities. A friend of mine was fond of saying that 80 percent of all code exists to solve 20 percent of all the potential problems that could happen in your application. Generally, software developers should be pessimistic regarding the reliability of everything outside of their control. Whether that be input from an end user, any connection to a network, to the file system, anything that the developer cannot directly control be should be held a
great suspicion. Again, if you rely on a file or a network resource, you should treat it with great suspicion. If you rely on the user to type data into your application, definitely treat that with great suspicion. It's absolutely evil. This is the software developers equivalent to driving defensively. Always code defensively, which means you are always looking for problems all around you-all the time. Now, the way that the C-Sharp developer codes defensively, or one of the ways in which they d
o it is through the use of a try catch block, and I'll demonstrate that in this lesson. Up to this point, we've been reading or actually writing files to disk. This time I want to read a file to disk. We use the same file class like we've used previously. I noticed that I already have a using stand for system that I also finds it. This time I want to use the read all text instead of the write all text. Here, let's just go ahead and set this example. Notice that I've already got a project created
called handling exceptions. Please, pause the video and catch up with me if you like. But here we go. String content equals file.read all text. Then let's just for the sake of argument, hard code a location. I'll put this at less than 22 slash example.txt and then we'll do console.writeline.content. Then finally, console.readline like so. Great. So far, so good. Now, here I just want to demonstrate that this actually will work. You can see that I created of my route a Lesson 22 folder with exam
ple.txt in it. Let's go and run the application and show that there is actually text in that file. It's just a quote from Mark Twain. Now that we've got it working correctly, let's break the application by giving it a fake name just by removing the E on the end of example.txt, and now you can see that we get an exception. This is a file not found exception was unhandled. I'll tell you what, let's do this. Let's stop the application. That's what the developer will see while they're debugging thei
r application if they were to run across this issue while they're building the application. But what if we were to build a release version of the application by changing the solution configuration and then selecting "Build Solution"? Now we're going to go out to our projects directory and I'm going to act like an end-user and actually attempt to use this application outside a visual studio, so outside of the debugging environment, just to see what the end-user would see if they ran into this exc
eption at runtime. The name of this is handling exceptions, there you go. Let's go into the bin directory, into the release folder, and then I'm going to double click the "HandlingExceptions". Whoops. Notice that I get this ugly little message here and it's trying to help me figure out what happened and I get all of this text here with all this ugly information just spewing out all this information that an end-user probably would have absolutely no idea what the issue was. Although we can read h
ere near the very top that the problem is that it couldn't find the file Lesson 22 slash example with no E dot txt. Now, a very observant user might be able to look at this and figure it out if he stared at it for a while. But most users are going to be scared off by this, and I don't blame them. We ideally would like to make sure that the end-user never sees anything like that whenever they run our application. Again, Windows will then close the application, notify you if there is a solution av
ailable. There's just a mess going on there, and we want to protect our end-users from this mess, from ever seeing this. What we can do is actually wrap a try and a catch around this. We'll do this. There's a couple of different ways to go about it. I'm just going to take the easiest approach to begin with. What I might do is just go ahead and let's switch back to the debug configuration and run the application. Now, you may have noticed that the application ran briefly and then went away, and t
he reason it did was because we ran this, we hid an exception here, the catch statement kicked in, there's nothing defined in the catch statement, and we continued on. What if we were to move this to right there? We would at least see the application now run for a little bit and we would see no output. So still not an ideal situation, but at least we're not seeing any exceptions. Let's go one more step with this and let's actually catch the exception that occurred. Here we're going to catch an e
xception that we're going to call ex. Now, exception is the most general type of exception that can be thrown. What we're going to look at in a few moments are very specific versions of exceptions. But this is the most general version so that at least we can see what the problem is and we might do something like, there was a problem, something like that, and even we could provide a description of the problem, so the message from the exception. Let's go and run the application. At least this time
we're giving the user some feedback here. There was a problem, could not find the file Lesson22/example.txt. That's better. Again, it would require an observant and slightly more technical end-user to be able to resolve this issue on their own to say, "Wait a second. I wonder if that file might be named something different here on my own hard drive." As they traverse through and look for the file, they're, "I see what the problem is. There's no e on the end of example." That's asking a lot of y
our end-user, but that at least is a step in the right direction, at least we're giving them some clue as to what the issue is. Now, really what I would like to do is account for all the possibilities and be a little bit more specific. If I were to hover my mouse cursor over this read all text where the issue seems to be mostly, you'll see that we've only been looking at the return value and the input parameters for a call to a method. But notice below that there's a list of possible exceptions
that could occur. Also, if we were to go to System.IO.File.ReadAllText. Let me just copy this and let's go to Bing. We're basically going to be searching through Bing here for System.IO.File.ReadAllText. That should help us find an article in MSDN that has a full description of this method. You'll see that there's two overloaded versions. We're using this 1st overloaded version of it. Then if we were to scroll down and pass some of the initial information, there's a list of exceptions, and it wo
uld provide us some scenarios why that particular exception might happen. Like a security exception, the caller doesn't have the required permission. The path is an invalid format. Interesting. File not found, the file in the path was not found. There's also a directory not found. Interesting. Maybe the path was too long or maybe we provided a no value. There's a lot of things that could potentially go wrong whenever calling this method. As developers, we really need to, to the extent that we ca
n, account for all those potential situations, at least the ones that make sense. For example, I could rewrite this code example to begin catching some of those specific examples. For example, let's take a look here. Let's, first of all, make sure that the directory exists, and then if it does exist, then we'll check to make sure the file exists. Then if the file in the directory exists but we're still getting exception, then maybe we let it drop off to this most generalized exception here. I'm
going to start from the most specific case and then work my way to the most general case. In this case, I think the file not found exception is probably the most specific of the ones that we're going to work with. Then we'll catch the directory not found exception. Then if that doesn't work, we'll just print out whatever the exception was. Here I might do something like Console.WriteLine and say there was a problem. Then give it a specific. Make sure the name of the file is named correctly, shou
ld be example.txt Then we can do something similar here and say there was a problem. Make sure the directory:\Lesson 22 exists. It's something like that. Remember, we're getting the red squiggly, why? Well, because we either need to add another backslash here or add the @ there, remember that from earlier? Let's go ahead and test our application. I'm going to set a breakpoint here whenever we hit this line of code so that we can watch this execute. Let's go ahead and step over. Looks like it fou
nd the file not found exception, and so we will see, there was a problem. Make sure the name of the file is named correctly. Then let's go out and let's rename this to Lesson22a. I think we're still going to get the same actually exceptions. I know we did get the directory not found exception, good. In this case, we'll see that error message, make sure the directory Lesson22 exists. Then for any other exception, maybe there's a permissions issue on the computer, maybe the file is corrupt somehow
and we can't read from it, we would get this last catchall, where we catch just the general exception and print it to the user. When you read the key to this is that we check the most specific exceptions first and the most general or generic exceptions last. There's also one other item I want to add here, and that's a finally statement. This is where we would write any codes to finalize, which might mean setting objects to null, closing database connections, but this code is going to run no mat
ter what. We're just going to go console.WriteLine, closing application now that like so that we can see that this code will run regardless. It's just that one last chance as a developer to clean up our mess before we stop the execution of the application. You can see that now represented here by closing the application now. Great. Now, you might look at this and you might think to yourself, great, I'm going to use this try catch around everything in my application. Every single line of code in
my application, I'm going to wrap it with a try catch. I'll just take every method and I'm going to blindly just copy and paste everything in there. That's definitely a strategy that some people take. It's a little bit lazy, quite honestly. Some developers have done that, but they're often ostracized by their end users for providing very cryptic error messages. If we were to leave all of these off and just wrap everything and just only show the exception ex, we would just be saying, hey, there w
as a problem here, figure it out for yourself. That's not really advocating on part of the user. We're not protecting the user. Furthermore, we might be tempted to provide some type of debugging information for ourselves as developers. Sometimes you'll see some error codes pop up that no human couldn't be expected to understand, except the guy who originally wrote the application. The reason developers do this because sometimes they take that exact approach where they just say, hey, we're going
to forget about the user. I'm just going to wrap everything in a try catch and it will pop the error message to me, it'll flip back to me. I'll fix the problem and everything will be okay. But, again, this catch all is convenient to the developer, but it's really frustrating to the end user so you shouldn't do that. You should strive to put the same amount of attention into protecting your user from having these issues and protect them from having to guess at what to do next by simply helping th
em fix the problem. Tell them specifically if you possibly can. If you the developer can fix the problem, or at least you can point the user in the right direction, then that's awesome. You should do that. But if you can't, well, then at least try to identify the exact nature of the problem and then ask the user for the type of input that you would need as the developer to fix the issue. You don't want to leave your users feeling stupid that they did something wrong. You want them to feel empowe
red and you want them to feel like your application is well built and it considered them whenever you were building it. That's what makes your application polished. It's what users expect, a reliable experience with no surprises. To recap this lesson, we talked about a number of different things related to exceptions that can happen essentially any time that you the developer are not completely in control and you're accessing things outside of your boundary of control, outside of your domain. Yo
u need to wrap those in a try catch and be thoughtful about the types of exceptions that you'll be handling, listening for specific exceptions that you know a particular method could raise, and it's easy to find out. All you got to do is hover your mouse cursor over it, or you go to mstn and you find that method and you look for it like we did, all the potential exceptions that could happen. Then be reasonable about it, but then write the code necessary to handle those exceptions and protect you
r end user. We looked at the try, the catch, we looked at catching the exception and then using certain properties of the exceptions, like the message property to print out to the user what the issue was. We could also use this to log the error, even send it to a centralized logging service like application insights that's available from Microsoft Azure to report back to the developers what the issues were. Then you can use the finally code block to clean up any connections you have to file syst
ems, databases. You can set objects equal to null and go ahead and remove all of your references and be very explicit about that before you shut down the application. Hopefully that was helpful. This is a great lesson in building resilient applications, giving the users the experience that they would expect whenever things go wrong in your apps. We'll have one or two more lessons and then we're done. We'll see you in the next lesson. Thank you. Hi, I'm Bob Tabor with Developer University. For mo
re of my training videos for beginners, please visit me at devu.com. In this final tutorial video, in this course, we're going to discuss event-driven programming. Event-driven programming is really at the heart of Microsoft's presentation APIs, whether it be for web or Windows. Really, for that matter, it's at the heart of just about every other API in the .NET Framework Class Library. It is so essential that we have to spend a little bit of time here near the end talking about it because it's
that next step that will help you graduate on to building real applications with real user interfaces beyond this course. Events allow you, the developer, to respond by handling those key moments in the lifecycle of the application's execution, allowing you to write code to respond to an event being raised. Up to this point, in our simple console window applications that we've been building, there's really only been one event that ever gets fired off, and that is the application startup. On appl
ication startup, the static void Main is executed, so it's handling that event, I guess you could say, and this is where we write the majority of our code, and that's why it actually executes whenever we run the application. Now in a modern user interface, whether it be for Windows or for web, users can interact with the various elements that they see on their screen. They can hover their mouse cursor over given things, like buttons or graphics or text boxes, and they can see maybe a change in t
he visual presentation, maybe they see a pop up that explains the usage of that given item, perhaps they can click on an item to enact some business functionality inside the application, they can press keys on the keyboard to make things happen, they can type inside the text fields, or they can drag and drop items around the user interface, and each of those will raise a number of events. As a software developer, you can decide to write code that responds to those interactions between the end us
er and those various user interface elements on screen, and you can also choose to ignore those that really don't make sense that you really don't care about, you don't implement for your application. A given component, let's say a button, for example, in its development by Microsoft, they included or defined an event, let's say it's the click event for that button. Now the developer, you and I, we say, "Hey, I'm going to write a code that performs this business logic that I'm writing here in C#
whenever that event, the buttons click event is raised, that I want this code that I write to be executed." So the developer creates a method and attaches that method to the event, and I'll show you how we do that in just a little bit here. As the application is running, the user is interacting with the application. Eventually, they click that button. The .NET Framework runtime says, "Okay, if you were listening for the button click event, here it is." It just happened, and it will notify every
one of the methods that you and I, as developers, have attached to that specific event notification, that we've registered to that event. Now I'm going to show how events are used in a simple Windows application near the end of this video in a more realistic scenario, but first, I want to start with the absolute basics and keep things as clean as possible, so we're going to work purely in a console window application. We're going to work with a timer class, a timer object, and it has one event
which is Elapsed. We can say after a certain amount of time, we want you, timer object, to execute or to raise an Elapsed event, and then we're going to attach our event handler code to that event so that it gets executed every time that event is raised. Maybe it'll be easier to see this in action than explain it. There are a number of different timer classes inside at the.NET Framework Class Library. We want to make sure we get the right one. I want to work with System.Timers.Timer, and I don't
want to use that long name every single time, so I'm just going to add that to my using statements up here at the top like so, and I'm going to say "Timer myTimer equals new Timer". One of the overloaded versions of the constructor for this timer class allows us to pass in the interval in milliseconds. So every, let's say, 2000 milliseconds we want the Elapsed event to fire, to be raised. So 2000 milliseconds would be simply two seconds, which is an eternity as far as a computer is concerned. N
ext up, what we're going to want to do is say, my Timer we know that it will raise an event called Elapsed, and so we want to create an event handler, a method that will be executed whenever the Elapsed event is raised by the.NET Framework runtime. Here, you can see that we get this little message on screen that says, "Press TAB to insert," and I press "TAB", and it automatically creates the method stub called MyTimer_Elapsed, and it creates in a very specific way with a very specific method sig
nature, and it also gives us this little stubbed out, "Hey, don't forget you did not implement me," so throw new NotImplementedException. Let's go ahead and remove that for the moment, but notice what happened here as well. We are attaching or registering an event called MyTimer_Elapsed to the Elapsed event, so this references this code block right here. Inside here, we can write the code that we want to execute each and every time the Elapsed event is triggered inside of our application. This i
s where I might write something like Console.WriteLine, and the Elapsed event will send along some event arguments. One of the interesting event arguments is actually the signal time, and that will give me the exact, down to the millisecond, when that particular event was raised. Here we go. Actually, let's do it this way so that we can format it nicely. We'll call this Elapsed, and then hour, minute, second.fff. That should give us down to milliseconds. Now what we'll do is actually tell the ti
mer to start ticking by calling the start method, and then we're going to go Console.ReadLine, and we're going to say, "Continue running until somebody hits the Enter key on the keyboard." Hopefully that makes sense, and let's run the application. Now we see every two seconds, we get this message. You can see at 32, 34 seconds, 36 seconds, 38 seconds plus some thousandth milliseconds there. We get that MyTimer_Elapsed method executing. Now let's do this. Let's say that we want more than one even
t handler to execute whenever the event is raised. I can do this all day long. I can say, "Hey, well, let's go ahead and add another method." This time it will be called MyTimer_Elapsed1. Notice the 1. I'm going to get rid of this little box again. Inside of this new method, I can do essentially the same thing, and I'll just use that Elapsed1 versus Elapsed. In fact, just to make this obvious, I'm going to use that little trick we learned just a lesson or two ago, where we set the ForegroundColo
r equal to the ConsoleColor.Red. That would be for the second one, and then we'll do Console.ForegroundColor equals ConsoleColor.White. We can see clearly the two different event handlers that are both executing whenever the Elapsed event is raised by our timer. Let's run the application, and now we see the pair running every two seconds. We could continue adding additional event handlers to the event. That's what this little operator is doing. It's saying, "How many current items are subscribin
g or have been attached to this event, I want you to attach this other one too." Now we can do the opposite as well. In fact, let's go Console.WriteLine line, and we'll say "Press enter to remove the red event." There's probably a better way to say that, but hopefully you get the idea. Then after this ReadLine, we'll add another ReadLine for the very end of the application, and in between what we'll do is actually unregister, detach this second event handler for this event, so we'll just do the
reverse. myTimer.Elapsed minus equals MyTimer_Elapsed1. So now we have removed it, and it should no longer execute whenever the Elapsed event is raised. Let's run the application. You can see, here we go, and now I'm going to hit the Enter key on the keyboard, and we should only see the white, the first version of our event handler firing every two seconds. Hopefully, that all makes sense. This is the most simple scenario that I could think up without having to actually create a real application
, and by real application, I mean, one with a graphical user interface. But now that we've broached the topic, let's go ahead and build an example WPF application. WPF stands for Windows Presentation Foundation. It's one of the APIs inside of the.NET Framework class library that you use to build Windows applications. In other words, applications that are executed on the Windows desktop, not web pages that are executed on a server, and their markup is delivered into a browser but a true applicati
on that's running on the end-users desktop. I'm going to File New Project, and here I want to make sure to choose WPF application. It should be one of the templates that are installed in the new project dialog. What I'm going to call this is, "WPFEvents" like so, and then click "Okay". This is not going to be a tutorial on how to create Windows presentation, application, interfaces, or how to work with it, but I just want to show you the basics are generally the same. Here we have a basic applic
ation, we can actually run the application, it will do nothing at all. We just get a white form on screen. But I want to go to my toolbox over here on the left-hand side, and I'll even pin it down briefly. Then inside of here, where I'll go is to this rolled-up area called common WPF controls. Now. What you see on screen might be a little bit different than what I see on my screen. Just make sure you're working inside of this MainWindow.xaml, and that you see some visual representation of your f
orm here in the main area. You can ignore everything below. That's the actual markup that will generate what you see visually here. We're only going to work with the visual editor but know that there's some markup that's going on to produce this. But again, that's a topic for another day. I'm going to drag and drop a button onto the design surface like so. I'm going to go over here to the Properties window on the right-hand side. This will allow me to set various attributes of that object, that
visual object. For example, I can change the content to, "Click me" like so. I'm also going to add a label, control. I'm going to drag and drop it anywhere on this design surface. I'm going to remove the content completely, but I am going to change the name to, "myLabel" like so. Now, what I want to do is print out the phrase Hello world, whenever somebody clicks the "Click me" button. I'm going to choose the "Click me" button again by selecting it here in the visual editor, and then I'm going t
o look for this little lightning bolt over here in the Properties window and click the lightning bolt. This will show me a list of all of the events that this single control, this button can raise. Now, a lot of these are going to be for very specific situations, and we can ignore the vast majority of these. But the most important one here at the top is the click event. Now, I can write C# code that will execute as a result of this click event being raised by the .NET Framework because somebody,
the user clicked on that "Click me" button. I'm just going to double click here in this white area, and when I double click in the white area, it created this button click method stub. This is going to be my event handler code. Let me use the auto-hide PIN to get rid of that, so I can see this. Here what I'm going to do is type in myLabel.content equals "Hello world" like so. I'm going to save my work, and then I'm going to start the application by running it. I'm going to click the "Click me"
button and it displays the word "Hello world" inside of the little label. Now, what you didn't realize is that maybe that whenever we double-clicked inside of Visual Studio in this little white area right here, it created a event handler for us, and it wired up or attached or registered that event to this button. You might wonder, well, where is the code that looks something like button.click plus equals, where's that code at? Well, that's a little bit difficult to describe if you take a look at
this markup code here at the bottom and we scroll all the way to the right, that is essentially what happens right here. This code will get converted into C# at the point of compilation, and it will create that little snippet that we were used to looking at in the previous code example. However, I can create a second event handler in C#. By doing this, let's go to the toolbox and I'm going to actually grab another label and just plop it down anywhere, and I'm going to select that label and they
go to the Properties qindow and I'll change this to be named my other label, and then I want to change the actual content of that label to be blank as well. Now what I want to do then is go to the MainWindow.xaml.cs, and here I'm going to go button underscore dot click plus equals and I could click "TAB to insert" but I'm not going to do that. I'm going to name this manually myself. But in my other click like so and then I hit Enter on the keyboard or actually I'm going to hit that. Now I'm goi
ng to, you can see that I get a red squiggly line. I'm going to put my mouse cursor on that line and hit Control period and then choose generate the method button underscore MyOtherClick and it does it for me, and you'll see something that looks very familiar here, a method stub with the not implemented exception. Here I'm going to say myotherlabel.content equals "Hello again", like so. Now if I did this correctly, whenever my user clicks the button, it will not only fire off this event handler,
but then also this event handler. This event handler, we wired up manually using the technique that we learned in the previous code example. Let's just run it, and make sure this actually works, and it does. The same principles are at play here. The difference is the vast number of events that are accessible to every single visual control in your toolbox whenever you're working with the Windows Presentation Foundation API. The main takeaway of this lesson is that events are all around us, and e
specially whenever we're working with Windows and web applications, we're going to write our code in methods that respond to specific events that are raised by the .NET Framework runtime in response to events that are published by the various objects inside of our Windows apps, our web apps, and so on. We can either rely on Visual Studio to wire things up for us in a very quick and elegant way like we saw here in our XAML code, where we let it essentially do the wiring for us. Or we can take con
trol of that process of wiring, of attaching, of registering an event handler to a specific event, and then write the code ourselves to actually respond to that event being raised. Again, extremely important. Hopefully, that's the next logical step for you is to move on to other APIs, whether it be something like ASP.net or WPF like we've worked with a little bit right here or the Universal Windows Platform to build Windows Store applications. You'll need to know these concepts for all of those.
That pretty much wraps up this lesson and this entire course. We'll have a couple of closing comments in the next video, and then that's it. We'll see you there. Thanks. Congratulations. You did it. You made it all the way to the end. That's a huge accomplishment, don't sell yourself short. When I look at the given views for our course, I typically see the first two or three videos in the course have an astronomical number of views, and then it begins to tail off over time until you get to the
very end, you see a rather small percentage of those who started actually finishing the course. Then it used to concern me thinking, maybe I could be a little bit more engaging and keep people's interest longer but good folks at Microsoft Virtual Academy assured me that that happens across the board with every course. I think what's really going on is that everybody has the best of intentions to follow through to watch an entire course. But then life happens, distractions pop up, maybe changes i
n priority present themselves they interrupt or completely halt progress. But the good news is that is not you, you were able to make it all the way through to the end and now you're well on your way to mastering C-sharp, or at least learning more about C-sharp. Then from here, learning more about.Net, picking a user interface technology, whether for web windows or mobile, maybe learning more about databases, maybe using C-sharp to access APIs around the Internet. We'll talk about some of those
things that you could learn as you move on from here a little bit later in this video. But soon you're going to be building your own applications, whether for yourself, for your employer, maybe your future employer. But whatever the case might be congratulations, I really encourage you to continue your momentum. Don't stop here, keep pushing forward, keep taking baby steps on a daily basis. As you know, daily progress, no matter how seemingly insignificant, is how you make real improvements in y
our life, it's how you add skills to your skill-set and you've taken this great first step in the right direction and I'm proud of you can't say that enough, great job, and I'll continue to encourage you throughout this lesson. But I want to wrap up this series in this lesson and provide a few suggestions about where to look for answers whenever they pop up from here on out, as inevitably you can continue by building applications and learning more about the various APIs that are available to C-s
harp developers. We're also going to talk about the right way and the wrong way to ask for help out on the Internet. Then I'll make a few suggestions on topics that you might want to investigate from here on out as you continue your self-directed training. But before I get started in earnest, let me say that some of the ideas that we talked about here, especially some of the more advanced concepts that I hinted at or that I said, you can let this go in one ear and out the other, I just wanted to
show it to you up briefly. Some of these things could require weeks or months or even years of thought work before your mind is really able to accept them and digest them. I know I've personally spent hours just staring at a wall, thinking about some programming concept, trying to wrap my head around it. The mind needs quiet time to reflect. You need to put yourself into a position to succeed by giving your mind the time to discover, the time to ask the crucial questions, the time to allow thos
e neurons to make those vital connections. Honestly, there are things that I learned about 10 years ago that I'm still trying to really wrap my head around, figure out what this means overall, in what contexts it applies, things like that. Many times I might need to read different books and articles, watch videos, and to hear what different authors have to say about a given topic before it finally resonates with me and I really understand what the topic is, how it pertains to me, what do I need
to do with it? Things like that. Each author who talks or writes about a given topic can say things in just a little bit differently, and sometimes that can finally unlock something for me. Don't forget to keep pushing forward and keep learning because there's always answers out there. But ultimately, I hope you realize that you really don't need to know everything right away to get started and to be productive right now. You don't have to be an expert first before you can begin to write softwar
e. In fact, some concepts really only make sense after you have more experience. Once you've made some mistakes, or you can see where a given idea and Oh I see where that applies, I could use that here in this scenario, that finally makes sense to me why I would want to do that. Adjectory in a program is a good example and there's some others too. I titled this lesson, where do you go from here? My intent was to answer that in two different ways. First of all, where do you go from here whenever
you have a problem and you're having a hard time resolving the problem and getting back on your feet again? There's a good chance at some point as you're learning, as you're building applications, you're going to run into error messages or something that just doesn't make any sense. It happens to everybody. But I would encourage you do not fret, I think in fact, what makes programming such a vital skill is learning how to solve problems that combine your existing knowledge with your ability to r
eason through what could be the problem and then your ability to research and perform research on a given problem until you come up with the solution to it. The good news is that there is this large community of other developers inside and outside of Microsoft that can help nudge you and get you past these problems. These people write blog posts, they answer questions in the various forums, they write books, they record screencast video tutorials like this one. You can tap into that community of
knowledge at any time. But let me give you a few tips on how to utilize that community in the most effective way. Let's suppose that you do hit a wall. You're experiencing some issue with your application, it's not behaving the way that you expected, maybe you're getting some strange error message popping up every time you try to debug your application. Where do you start to debug this to pick apart the problem and get to the root issue? First of all, I research using key phrases directly from
the error message itself, and I can't emphasize how vitally important that is. If there's an error number or a specific phrase that I can latch on to and I can "surround those" as I type in my query to Bing.com, that always helps me get closer to a resolution. I might spend 10-15 minutes scanning through various blogs and forum posts or on MSDN as search results pop up for these sources in order to find a potential solution. If I'm mindful about my search terms, I almost always find a solution.
I think the reason why a lot of beginners fail with finding solutions to the problems is because they become impatient or they don't use the exact error messages in their searches, and they don't know how to search correctly, and they're not willing to put in the time to actually read through pages and pages of content to find a solution to the problem. I can't emphasize enough using the exact phrase inside the error message that you see on screen "surrounded", will get you closer to finding a r
esolution to the issue that you're having. There are always usually people with other similar issues that are posted and then explain what they did to actually solve that particular issue, so research is vital. I think actually one vital skill as a modern software developer is you become great at search. Searching on the Internet to help solve issues that you run into is such a vital skill. Now, it might seem easier to go directly to the forums immediately and to post a question to the forums in
hopes that somebody else can help solve your problem for you. But I assure you that it will actually take longer to ask the question and get an answer than it would if you spent the time searching, refining your searches, and so on until you find a solution to your problem. Frankly, I almost never have to ask a question in the forums because a simple search will almost always yield a clue to what I did wrong or what the core issue is. In fact, I get embarrassed when I have to ask questions. May
be that's a bad attitude to have, but I don't want to burden other people with when they could be answering other legitimate questions, so I go overboard and try to figure out the issue on my own. Now, virtually any issue that you run into, I'm almost positive that somebody else has at some point run into that issue before you have, and they've already posted the solution to that problem online. You just need to get out there and find it. If you get good at doing research, doing searches on the
Internet to help find solutions to your problems, then it'll get you back on your feet faster than again, posting into a forum and asking other people for help. Now, let's suppose that you're at your wit's end and you've done searches and there's nothing out there that really seems to apply to your situation. Nothing you've tried actually works to resolve your problem, maybe at that point, you need to ask for help. That's fine. Here's what you really need to do whenever you ask for help. You nee
d to ask your question in such a way that you're going to get a resolution and how you ask your question is important. You need to be an empathetic requester. In other words, you need to get people who are willing to help all the information they need to get you back on your feet again to pinpoint the issue and then isolate the issue and prescribe a solution. This means that you need to, first of all, clearly state your request. There's a checklist that I have in my mind of the things that you n
eed to do. Some of these will be obvious and some of them you may have not considered before so let me just go through them real quick here. First of all, you should start by posting your question in the right place. Find the right category in the given forum or use the correct tags for your post so that the right people are looking at your questions. Posting a C-sharp question in a visual basic form is not going to be all that productive, in fact you'll probably get chided for it. Secondly, you
also need to choose a simple clear title for your post so that it attracts the attention of the people who can help so that it saves everybody a lot of time. If I see a forum post that just says, please help, I usually just skip it. If it says link to objects queries yielding unexpected results, well, okay, that's oddly specific. That might be something I can help with. I look like the person put some effort into concisely stating what the issue is. I'll read the question and I'll see if I can
help. Third, a short synopsis of the issues that you're having, including the exact error message, including the exact behavior you are expecting, and what you're actually experiencing. Describe what you expected to happen, but what if it happened instead and keep it concise. Fourth, if you can at all possible include screenshots, and ideally you would go one step further and use some screen editing or image editing software and draw circles to draw the eye's attention to those parts of the scre
enshot that are pertinent to your question. Fifth, if possible, include a code example. Make sure to change any super-secret information, passwords things of that nature before you post it, but without a code snippet, many problems are unsolvable. I can't tell you how many times I get people writing e-mails and they'll say, I'm having a problem with this what do you think the solution is? I'm like, show me some code, I need to see what you did to get to that point, and then maybe I can help you
figure out what your issue is. Always include, if you can, a code snippet of the code that you think is causing the problem. Then be choosy about which code you choose to post. There's nothing more frustrating than looking at somebody who posts like 200 lines of code and expecting me to go through it all when a lot of it doesn't even pertain to the question at hand. I mean, you had to spend a little bit of time narrowing it down to a few things. You need to help me be empathetic to me, the perso
n who's willing to help you to identify those lines of code that might be involved in the issue. Number 6, if a given forum has special HTML tags or shortcodes that you can use to format the code or some other aspect of your question to help it stand out in the post, then you definitely should use it. Number 7, tell me, what have you done so far to try to resolve the issue? Did it change anything at all? Did it change anything? Did it help? Did this lead you to rule out certain possibilities? Ag
ain, empathize with me, the person who's reading your question, trying to help you. This will result in a faster resolution. Otherwise, people will start with the obvious issues and then move forward. There's that old joke, Hey, I'm having a problem with my computer and the technician asks, well, do you have it plugged in? Everybody says, Oh, the technician was, but there's a reason why they do that. It's because the most obvious answer is the one that most of the time works for people. Don't be
that guy make sure you already list out what it is that you try to do and you've eliminated it as a possibility. Number 8, tell me which operating system you're using, which version Visual Studio and the DUnit framework, which programming language you're using, which updates, service packs have been applied anything that you feel is pertinent to help me help you diagnose the issue that matters more than you might realize. Number 9, suppose that there's a resolution to the issue, you figured it
out. Awesome. Very cool. Maybe somebody made some suggestions that led you down to investigate some things and you finally figured it out that's great. Take a moment, go back wherever you asked the question, and describe exactly what you did to resolve the issue step by step. Use that as a means of better understanding it yourself and articulating that will help you better understand the issue and what the solutions are. It makes you part of the community of the wealth of information that's out
there so that others in the future who have the same issue can look at your post and that you are feeding it back into the community just like you're taking out of the community. Chances are that honestly, that person that you help in the future is you, I can't tell you how many times that I found a resolution to something, and then months later, I hit up against the same thing, thinking to myself, I know I've solved this once and I'll go searching for a solution and I'll find the exact solution
and I'll read it. Oh, that was me, that was me who answered the question. It would be nice just to search for your solution online if you knew where it was, or at least be courteous to everyone else and your future self to post the answers to the questions that you have. Finally, absolutely 100 percent be polite, people don't owe you an answer they don't owe you anything there. If they're going to help you, they're going to do it out of the kindness of their hearts. They're going to be doing it
in their spare time as a means of maybe, furthering their own understanding, helping themselves grow but then also to help you grow as a software developer. Say please and thank you and be nice and then help other developers as you have the opportunity. I do sell training content, but I give a lot of it away for free. I do ask questions in the forums, but I answer a bunch too, make sure that you become part of that community and that you are feeding back into the community, you help, and you su
pport, just like you've been supported by others. You might be wondering, where do you go to find this level of support, where you can ask questions. That depends. Typically, I'd recommend that you go to msdn.Microsoft.com here, let's go out real quick. So, msdn.Microsoft.com/forums and it might redirect you based on where you are in the world. But typically you can choose from a number of different forums, so you definitely want to find the specific technology or language or whatever the case m
ight be, or do a quick search for those keywords again right here inside of the MSD and forums. It is monitored by Microsoft employees, as well as people called Microsoft Most Valuable Professionals, or MVPs. MVPs are usually knowledgeable people who've demonstrated their willingness to help, and they've been identified by Microsoft as people who are willing to help and so they qualify for that based on some criteria, not the least of which is participation in these forums. Then there's also ano
ther more comprehensive place you can take a look at Stack Exchange, programmers.stockexchange.com, and there might be one other place where you could go but also by the same company that has similar forums, depending on the type of information you're looking for. Now, in my experience, Stack Exchange is a little bit iffier. It's a little less beginner-friendly. Maybe that's changed by the time that you visit, and I only say that it's a little less friendly because not only will you be critiqued
for how you ask your question, but very often if people do a search to help you and then they find that there's already an existing question that's similar enough to you, they'll shot your question down. Just follow the rules, do an extensive search before you ask a duplicate question, don't take offense to criticism about your question. Again, I'd recommend that you search long and hard before actually posting the question because I'm convinced that virtually everything that you could run into
has been asked by somebody already. You just need to spend the time to find the answer that you're looking for. I said that I would answer the question of where to go from here in two different ways, and I've answered the question of where to go whenever you have problems. But now I want to answer the question where do I go to learn more about application development, where do I go to learn more about software development? At this point, you've got a pretty good foundation of C-sharp basic know
ledge of the C-sharp programming language.Net and a little bit about Visual Studio but there are still a lot of opportunities to practice what you know and to grow beyond that. No matter what type of application that you want to build, there are a few fundamental ideas that you need to be fundamentally acquainted with before you move on. First of all, I would recommend that you learn about relational databases like SQL Server, you learn how to access data that's stored in a database using the En
tity Framework, part of the.Net API for accessing data in your applications. Both SQL Server and the Entity Framework have visual tools that you can use inside a visual studio to drag and drop and configure your settings and selections and so spending some time not only learning about the tools and the APIs themselves, but then also these visual tools and start a visual studio can pay big dividends. You'll want to quickly grow past that and learn how to write code and rely less on the visual des
igners and visual studio. But still, it's a great tool to help you get to that point where you can be productive quickly. Next, you're going to need to choose a presentation technology that you want to master, and this is really more about platform, honestly than just simple UI. So you have no lack of options, whether you want to build web or Windows applications or mobile applications or games or backend processes, whatever the case might be. So let's say, for example, you want to build web app
lications. There's a couple of different platforms. The older API is called asp.net web forms, and there's a lot of code that was written on the Web Forms Platform API. But then there's also a newer API, that's called asp.net core MVC, and there are some huge differences between the two, but we don't have enough time to talk about those. I had content on both of those topics on my own website debut. There's Windows Forms, which is the older desktop API. Then there's Windows Presentation Foundati
on, which is a newer API that companies use for building applications internally and then there's the Universal Windows platform, which you use to build more consumer oriented applications, typically for sale on the Windows Store. There's also the Xamarin platform, which Microsoft recently purchased at the time, I'm recording this for building true cross-platform apps for iOS and Android and even Windows Phone. Then there's a third party called Unity 3D or 2D, depending on the type of game that
you want to build. And so you might want to check out unity for building games. Now, if you're not really sure about where you should go next and what you should learn next, I really would recommend that if you don't already know each HTML5, CSS3 and JavaScript, that's a great place to start. And I've created several fundamental series on Channel 9 that are aimed at each of these topics. They're also available here on Microsoft Virtual Academy again at the time when I recorded this. Then beyond
that, I recommend learning about the basic tenets of application architecture, particularly how to structure your code into layers of responsibility and what that even means. So splitting your code into layers of responsibility will help you build applications that can withstand the impact of change. And like I said earlier in the series, change comes from a number of different places. It could be changing business rules. It could be changing requirements, changes in the technology that's availa
ble. It also comes from defects in your software, bug reports that come in and you need to make changes to fix those. But in each case, you can mitigate the negative impact of making changes in your code by encapsulating the responsibilities behind well-established APIs between each of the layers of responsibility. And I spend a lot of time talking about this, about application architecture on debut. So if that's something that interests you, you definitely want to check that out. But from there
, you want to learn more about basic software design patterns and tactics and techniques. And there are a few keywords that you're going to want to learn about, and each of these can spawn an entire book, an entire video series. And I've already alluded to the topic of object oriented programming. That's a huge topic that you definitely want to learn about first. If you can just get your mind wrapped around object oriented programming and how that changes the way that you create solutions to pro
gramming problems, then that's a huge step in the right direction. But beyond that, you're going to want to learn about the principles of software development, principles that guide you to write your code in a very object oriented way. There are some more generalized principles, like the drive principle. I don't know that I've ever given it a name, but it's essentially don't repeat yourself. I said be leery of copying and pasting. When you do find yourself wanting to copy and paste code in multi
ple places in your application, you should be stopping yourself and thinking, how can I create this in such a way that I can reuse it? So don't repeat yourself, put code, extract it out. That will be reused into its own method or class, and then reuse it from there. There's also another principle called Yagni or Y-A-G-N-I. Which is you ain't going to need it. Which means, yeah, you could probably set yourself up and architect your application in such a way that in the future you could expand, bu
t you're probably not going to need to do that. You ain't going to need it. All right. Then there's another principle or idea called dependency injection, which is super important. It's a design pattern that guides you towards building loosely coupled objects that then can be swapped in and out of the solution, and you'll want to learn about dependency injection. It's really crucial to building some of the new style applications using like the ASP.Net Core MVC, which relies heavily on dependency
injection. There's also a set of principles called Solid, S-O-L-I-D. Each of those stand for a different sub principle. They help you realize the promise of object oriented programming inside of your applications. So again, a lot of ideas that are more conceptual in nature and less code syntax or tool oriented. All right. You're also going to want to learn about the process of software development, so the workflow surrounding software development and managing software projects. So specifically,
you're going to want to learn about the tools and the techniques that you use whenever you work inside of a team sharing source code between team members using a source code repository like Git or like Visual Studio Online's implementation of Git and their own internal source code repository tool. You're definitely going to want to learn about building unit tests, which are tiny little code based tests that continually are testing your code every time you write. Some people have even gone as fa
r to say that you should be writing those little unit tests first and then you write the actual production code that satisfies those unit tests. Now, whenever there's a change made in the system, you can see what the impact of that change is because you'll begin to see these little tests start filling, that is a process called test driven development, and some people swear by it. Other people swear at it. So you're also going to want to learn about agile project management, agile software develo
pment techniques, defining requirements in user stories, playing a game called planning poker to determine what features can we include in a given iteration of our software building process, using agile boards to manage assigned tasks between the various software developers on the team. You're going to want to learn about the nature of iterative development. How to use that term iteration. So you want to learn about what are iterations and one of the goals of iterations and why they're useful. Y
ou'll want to learn about developing a spike of functionality all the way through all the layers of responsibility in your system. So I've given you probably what, several dozen different key terms that you could use as a launching point to search on. Honestly, if you were to look at all those terms that I just use, it'll take several years to learn about all those things, even in a general way. But fortunately again, you don't have to know at all to get started to be productive today. So, yeah,
there's so much to learn in so little time. But it's what makes software development fun and makes it exciting because there's always something new to learn and some new technique to try. I've had friends at Microsoft, actually confide in me that it's a challenge for them to keep up with it all. Nobody just knows all this stuff automatically. It's a challenge for everyone, everybody to keep up with. Nobody just knows it all. It just keeps evolving. You just have to really commit yourself to lea
rning. I realized some time ago that my full time job is not creating video content or training content for developers, my full time job is really learning. And then if I create training content, that's really a byproduct of all the learning that I'm doing, the value that I have to somebody else is my knowledge. And so without that is the core piece of what I do. Whether it's building applications for somebody or creating training content, they're only interested in me because of my knowledge. T
hen how I apply that knowledge is a byproduct of actually gaining the knowledge. So you have to really commit to learning. And I know since you're here on Microsoft Virtual Academy that you've already done that to some degree. There's a whole bunch of great resources out that are available on the Internet, not the least of which are Channel 9 and Microsoft Virtual Academy. Obviously, there's MSDN, as we looked at earlier in the series. However, before I close this out, let me make one final plug
for you to visit my website. If you haven't already developeruniversity@devu.com, is there on screen. I've designed the courses there specifically for someone who's a beginner to help them get up and running as quickly as possible, pointing out what I feel like they really need to know in order to master key ideas that will lead them to get jobs in the software development industry, providing homework exercises and quizzes. But more importantly, coding challenges that force people to write and
to develop the muscles of your mind that allow you to pick apart a problem and create a solution for it. All right. So please check out devu.com whenever you get a chance. All right. So as I close here, I hope you found this course to be valuable and this lesson to be valuable. If there's anything that I can ever do to help you, please let me know. You can find me out on Twitter. I sometimes go out there. Hit me up on Facebook or, you can write me an e-mail. But finally, as we close out, I since
rely wish you the best of luck in your career. C-sharp in software development is such an exciting field to be a part of, and I'm really excited for you. So good luck. Thank you for watching this series.

Comments

@jordanhwang

I just finished all 8 hours of the course! I'm so grateful that this course is available for everyone. Bob is incredibly articulate as an instructor and I can't thank him enough!

@dashnero6692

I am a beginner of the C# programming and I find a lot of tutorials on YouTube, I think this tutor is the best for the real beginner. Thank u!

@draganpavlovic1809

Thank you bob for explaining this to me like i'm 6y old! Keep it going!!!

@jamesbarker1994

I've purchased Bob's C# fundamentals course on his site after watching this series over 2 years ago, since then I've managed to complete the fundamentals course and I've moved into a programmer role in my work. I can honestly say that Bob is the best out there and I look forward to completing his other courses. Thank you Bob

@lilosSso

This is amazing. I've been looking to learn C# for a while and every course out there assumes you have some knowledge in programming and treats you like you're supposed to know what they're talking about. I have zero experience in programming, and I want the course to treat me like a 5 year old trying to learn 1+1 in order for me to understand absolute basic concepts. Which this course amazingly does. Thank you so much!

@Alan_Dler

I took this course on Microsoft visual academy several years ago. One of the best courses online. Thank you, Mr. Tabor. I only wish Microsoft and Mr. Tabor make a more advance level tutorial.

@davepazooki3891

Wow! I learned C# for the first time from Bob video's more than 18 years ago. Good to see he is still out there!

@rezvlt9285

Almost 3 years later and I'm a software engineer now. Thank you so much Bob!

@Tess_m636

I've been practicing coding for about a month now, going in not knowing ANYTHING. i invested in a computer and multi screens, I've watched 2 other people's videos for hours theirs were good, i pretty much know the basic's now and i could build a basic game and a functional calculator etc. i'm a fast learner, i'm already practicing coding something advanced i guess to me lol and ATM.... just for fun but i WISHED i found your video first. the way you explain everything is perfect!!, i'm only and hour in your video right now just to freshen my memory and after almost a month of dedication i already know what your talking about with out being confused like i was a month ago and man your a great teacher so detailed trying not to miss anything!!!!!!!! Thank you so much Mr.Tabor for making this video, looking forward to finishing this 8hr video. For those people who never coded and have no idea coming in, if you practice and really put your mind too it you'll really understand everything and what he is saying. i came into this like omg i dont think i could do this but practice really makes perfect and im interested so i did it. Take it from me coming in as an extreme newbee. :)

@umut12351

This was my first programming tutorial back in 2016 while I was in high school. I am where I am because of this video. Thank you.

@ELAWESOMEBORICUA77

Bob. All I can say, is Thank You. The last video felt like you were speaking right to me. I'm self taught and changed careers. Thanks for this course!

@lx_phx

Mr. Tabor is one the best explainers out there, watched this back in my school days and now I am studying computer science.

@Saitama-nu6jf

I started my career in software engineering years ago because of this guy. Thanks Bob.

@josegarcia2762

Ive watched over 100 videos on how to code and bob tabor is #1. he is thorough and makes everything as simple as possible for beginners to understand.

@ArrKayLondon

I'm an intermediate python programmer and so much of this stuff I never learnt with Python because it's abstracted away. Very grateful to learn it now and more importantly learn why. Great course so far Bob.

@kopilkaiser8991

I cannot explain how well the tutor explains and demonstrates all the lessons in this video. Highlg recommendable to anyone looking to dig in C# ! I have saved the video to my list and will refer back whenever I forget any topic. Thank you so much to the creator. Loads of love and appreciation for making this video ❤👏

@nicolasspies7279

Finished this course and it is excellent. Bob is an amazing tutor. As a C# beginner, the way the topics are structured and explained have really helped me to understand the basics. Thank you very much for this!

@clara8clara

I wanted to take the time to say: Thank you!. Yes, you are right when you say that some people are interested in you because of your knowledge, BUT I'd like to highlight that some others are also interested in you because you are such a good human being. You transmit your knowledge in such a way that it is easy for me to understand, efficiently, and you do that with great love as well. Thanks again!

@chrisp2639

Started working through this before starting college for computer science where our intro to programming classes are taught in C# and it has helped so much. Thank you!

@yuyuyuyuyuy484

This man honestly is a great teacher, he just does it so naturally; Thank you Bob.