What's up guys this is codiversity your channel for Non-Stop coding action in today's video we're going to be covering c-sharp programming language with no further Ado let's get started [Music] all right so the intent of this video is to give you the in-depth view into the c-sharp programming language we're going to keep things rather simple in this crash course we're going to be covering The fundamentals of c-sharp variables objects classes don't worry if that doesn't mean you know anything to you right now if you're an absolute beginner you should be able to follow along with
this course and kind of understand a little bit more about how c-sharp works and the good thing about c-sharp versus other languages anyway is that it's based on the C programming language so a lot of what you'll learn today May apply to other programming languages such as JavaScript and even in some cases Java even though things may be a little different in some cases overall things are quite similar so let's get started I just have a couple of slides to go over I promise I won't bore you so basically what is C Sharp C sharp
is a programming language created by Microsoft it runs on the.net framework the.net framework will get a little bit into that shortly but generally um on a higher level the.net framework Is utilized to create apps across different platforms such as desktop platforms mobile and even in some cases outsider.net c-sharp is being used to create games like for example on the unity engine so c-sharp is a very robust language and net is just the framework that it runs on so now you might be asking what is.net.net is a programming framework created by Microsoft and it's used to
build apps for various types of Platforms mobile desktop and so on and Dot net is very powerful in the sense that it comes pre-packaged with a lot of classes as part of its uh class Library you also have the CLR or the common language runtime which drives the program execution as well as just in time compiling or jit and how jit works is basically your computer needs to understand a set of instructions as that it's given when you write code in C sharp you're giving Instructions to your computer to carry out a series of actions
and basically jit converts that C sharp code or Intermediate Language into native language that your computer understands otherwise known as bytecode so as you can see.net has a very very important role to play in the program execution building apps and so on so why should you use C sharp as a software developer well for one C sharp is an event driven language so Essentially that means you can build very robust and Powerful applications using events and event is basically an action that gets triggered by another action or another condition so a common example is if
you have a value in your application that when a certain condition is met it will fire an action or an event for example like a database record update that's a common example of an event that can occur in C sharp and you know events are also a common sort Of framework or common foundation in many other programming languages but in C sharp there's a very robust way of writing events however we won't be covering that in this course because we're going to keep things a lot simple but comment below if you'd like me to do
specific videos on how c-sharp events work so I talked long enough about the theory and I guess you guys are ready to jump in so let's start coding So the very first thing that you want to do is you want to make sure that you have a code Editor to write your code in now when speaking about c-sharp there are several code editors that exist out there that do support the C sharpen.net framework however the most common one that we typically use is c-sharp developers is Visual Studio which is also created by Microsoft so you
want to do a search for visual studio on Google or any other search engine and then You'll come across this website here that I have open and on this website it may look a little bit different um depending on the time that you'll look at this video but generally you want to look for any installation file for Windows or Mac and I definitely recommend using a Windows PC to develop c-sharp code but it is doable on Mac and I do prefer the ux on a Mac so that's the reason why I'm going to use a
Mac in this course but generally at the time of This recording we're looking at visual Studio 2022 as being the current version so you would want to find the Community Edition which is right here on the far left so that's a free download you don't have to pay anything if you want to upgrade to the other editions of Visual Studio code you can absolutely do so for a fee I'm not really sure what the pricing structure is so you have to read a little bit deeper into that but I think the Community Edition is uh
Sufficient enough for you to do your development on now if you're on a Mac you definitely want to download this visual studio for Mac edition here this is also a free download it doesn't have all the bells and whistles that the windows version has but again in this video I'm going to be using the visual studio for Mac edition since we don't really need to do anything super complicated anyway so that when you click on that link and I'm going to Click on visual studio for Mac here the free download button it'll take me to
this page and then I'll have to complete a series of steps here to download the file and install it now I already have it installed here locally so I won't be doing this again but you'll definitely want to follow the prompts here as well as the instructions and get that set up on your local machine and from that point you can then jump in and we can start coding So now before we proceed can you please do me a favor pause the video hit the Subscribe button and Bell icon to stay updated on future videos
that definitely helps the channel and I'll create a lot more videos like these based on your feedback and your love so let's go ahead and get started with visual studio so right now as you can see I have open Visual Studio I've already clicked the icon below to open up the program right now it's a stance we haven't really done Anything yet but what I want to do is I want to create a brand new Visual Studio project there is something called the solution which is essentially a collection of projects and I'll explain that up
in a bit a bit further so you can have a better understanding of that so again guys I'm on a Mac right now so on a Windows this may look quite different but essentially it's the same process just Google exactly how to do this on Windows and I'm sure you'll find The instructions on how to do it so right now what I'm going to do is click the new button here to the right and when that opens here we see we have various different options of what we can select we're going to just create a
basic console application which essentially means that this application will run within the the visual studio editor itself so we wouldn't have to worry about building a web page and displaying any output to like a UI or Something like that so I'm going to select that I'm going to click continue to proceed so on this screen here is asking us to confirm additional configurations for our console app we're using the.net 7.0 version at the time of this recording uh if the version is higher by the time you do this don't worry it should still be the
same process if not just Google it and you should be able to figure it out and so I click continue and then on the Next screen here we have the project name so let's call this C sharp sorry I can't type today C sharp crash so a little bit of insight on Solutions versus projects a solution as I said before is a collection of projects so in a real world application you may have something like one solution that contains two three or even many projects within it and a common architectural Pattern that you'll see in.net
is something called the MVC pattern which essentially means you would have a database layer as one project another project as your business logic layer and then another project as your UI layer and all those layers come on pretty much communicate with one another so that's a very common thing you'll see in the net world so in our case we're going to build a very simple solution that would have just one project within it so I'm Going to proceed here I'm going to leave the location as default and everything else as default and I'm going to
click create so that'll just take just a second here and as I click create you guys will see that Visual Studio would open up and there will be some default code in here for now don't worry about this code because we're going to get rid of it I'm just going to talk a little bit right now about the project structure so it's Very pretty much simplistic because that's what we're handling right now we're only dealing with a very simplistic project but on the left hand side here in the folder browser you'll see on various folders
and files so our project is named C sharp as I said before we have this connected Services folder you don't have to worry about that but if you were to if you wanted to add additional dependencies and services Within it um you can do so right here a lot of it is automatically populated depending on the types of components that you work with you also have here a dependencies folder that's that's basically referring to the net dependencies or third-party dependencies that would be added to this project but again for this course we won't really have
to deal with that folder so you can ignore it for now and speaking of ignore we have the dot get Ignore file which is Infamous for you for those of you who are experienced software developers this is where you can add specific references to files or folders that you don't want to commit to git repositories so if you don't know what that means don't worry about it I could possibly do another video on how git works and things you need to know forget if you're not knowledgeable in git uh the main file we're going to
concentrate on here is the program.cs The CS extension stands for DOT C sharp and essentially this program file is usually the very first file in a console application that runs so this is the file we're going to be working with right now all right the very first thing we're going to do here is get rid of this existing code because we're going to be writing everything from scratch now you guys can just follow along and type along I think that's the best way to Learn is to actually follow along by typing or you could just
simply watch it and drink a cup of coffee so just relax yourself and just learn as we go along so the very first concept I'm going to cover here is called namespaces so a namespace is basically a set of classes that are separated by name and that might mean nothing to you right now but just to explain it as simply as I can in C sharp applications we have the concept of a class and the class is basically a Blueprint or template for an object in C sharp so for example you might have a class
called animal or a class called person or a class called you know classroom anything that you can think of well we utilize namespaces to separate classes that may share the same Name Across the application and we generally do that to avoid collisions so for example we may have a person class and a namespace called courses and a person class and a Namespace called employee so that's generally a way to separate our concerns within our application and avoid conflicts so the first namespace I'm going to bring in is called system now the system namespace contains many
helpful.net classes that we can utilize and one of which is called the console class the console class itself has many different methods that we're going to be using today such as right line and which would output a single line with a new Line at the very end to the user within the console pane so that's one class we're going to be using today is called console which is part of the system namespace so now that I've explained namespaces we can jump right into the meat and potatoes of everything which is the actual coding so in
this class what we're going to do is we're going to model this file rather as a standard console application which Contains a main method call so I'll explain more after I write a few lines out so the very first line we're going to write out here is called class and we're going to call this program because that's the name of this file that we're working with and we're going to use these squiggly braces if you will which is a left curly brace and a right curly brace to open up a code block and in this
code block we're going to specify a set of instructions to give to our local Machines to Output um data or to carry out a certain Behavior if you will So within this class the very first thing we're going to put in here is a main method so let me just type this out here so the first thing we'll type out is called Static void Main and I'll explain what this is in a second so the very first thing here is we have this static keyword and what that means is static means that whatever We're we
have static on whatever like um method or you know class that static is on this will be loaded into memory once that means that this particular function will not be reloaded into memory on every single instance creation or instantiation what would happen is it would be loaded once into memory and we can utilize it over and over again and one key concept here is we're going to be calling various methods or functions within this main method to carry out Different Behavior one thing I'll point out is that whenever we have functions that are contained within
the same file this being the program.cs file will also have to mark those other functions as static in order for this to work if we're calling other classes we can Mark those as non-static which I'll show you later on but but just keep in mind that any function or method that we Define here would have to be marked as static for it to work the void keyword just Simply means that this function whatever we write Within These braces it will not return any value so it so basically the program or the computer is not expecting
to see any value being returned from this method and lastly here we have the main so basically this is the name of our method it's called Main and C sharp is normal convention to capitalize the very first letter of your uh method but in this case we want to mark this as main because actually our computers in The.net framework recognizes this method as the starting method of the application so it must be named this to make things a lot simpler okay good so now that we've explained that let's move on to what we want to
do first so I guess the very first thing we want to do is output something to the console just to make that make sure that things are working properly so let's create how I'm going to do this is I'm going to create several different methods that will be Called from within the main method and then we'll Define those methods below to make things nice and clean so the very first method I'm going to create will be called print to console so let's type that out print account console and below that I'm going to now create
a method of the same name and this will be the method signature so again as I mentioned we have to Define this as static so static void print To console and guys as I'm typing these things out I'm definitely going to be making mistakes that's just a normal part of being a developer so you know please bear with me you know because that those things happen and to be honest you learn from your mistakes as well so I I'm still learning today and I'm very seasoned so that's something to keep in mind okay so we
have this print to console function so the very first thing We want to do is we want to display let's just say a message to the user so maybe we'll make this a hello world application this is a common thing we do in development so let's output hello world to the console so to do that as you remember I brought in the system namespace above so because I did that I don't have to say system.console I can simply just say console and then the console class has a right line method so console.writeline as you Can
see our Auto suggests is already pulling up the correct method so I'm just going to hit enter on that and every single line must end in a semicolon every single line that specifies a method call or a variable declaration which we'll get into later must end with the semicolon so make sure you do that because C sharp is very particular on those things so within this right line method call we need to give it a an argument value and so the Value that it normally expects is something called a string and a string in C
sharp is basically created with double quotes so whatever text we put between these double quotes will be the value that we're sending to the right line method and as I said before we want to create a hello world application so let's just say hello world cool and let's save that and you can save that on a Mac by doing command S I think on Windows it may be control s but Don't quote me on that there should be um something within your menu above on Windows where you can actually save the file maybe an icon
or something like that but if you're not sure when in doubt just look it up so now that I have that um I'm going to run this application just to make sure that things work and uh to run this on a Mac we there's a short key which is uh basically command option and enter so let's try that It may take a while to build because it's the very first build but there you go as you can see below it's outputting hello world so that's basically how we output information to the user now the console
class also contains helpful methods uh to you know uh take in user input or to do various other things for this particular course we're just going to be working with uh outputting things to the user outputting data or various strings and things like That just to keep things nice and simple alright so with that being said let's continue so in C sharp we also have the concept of variables and data types so what a variable is a variable is a space within your computer's memory system that holds particular values and basically variables are important because
it allows us to re um to avoid code repetition and redefining code over and over again so I'll give you an example but the very first thing we're Going to do is we're going to come back up here to main method and we're going to Define another method called called variable or variables and data types with the semicolon now as you can see I'm getting an error message because this does not exist so what I'm just going to do is I'm just going to copy this for brevity copy this uh method call name I'm going
to come below the closing bracket of the print to console line and I'm going to define a new Function called Static void and then variables and data types and hit enter so now we have our new method here now in this method we're going to be doing several things in this method we're going to demonstrate how variables work and you know exactly what you need to know with working with data types so the very first thing I'm going to show you is uh data types so in C sharp every single object or every single value
you'll deal with will have some Sort of data type attached to it either it will be a built-in data types like integer like string like character Boolean which is a true or false value or it could be a data type that you define yourself so let's start with the very primitive or basic data types first that are coming together with the.net framework so the very first thing we have here is an integer which is a number it's a whole number so if you think of 0 5 10 100 1000 these are Integers and an integer
can be signed or unsigned so in this case we are going to Define just a basic integer and we'll just call this integer age because we want to define the age of a person so int age let's say int age is 30. so this is basically assigning the value of 30 to the variable age which is in a number or an INT the int data type and let's just make sure that this is working so we're going to console.writeline age Okay and we're gonna save that and then we're going to do our shortcut key and
we'll run this and as you can see below right below the output of hello world we see 30. so that's working that's great so let's cover some other data types in C sharp so the next data type we'll cover is called float and the float basically is a decimal point number or just a decimal number and uh there are different there are actually different types of decimal uh data types in C Sharp but float is the one we'll cover first so let's define let's say a temperature so we'll say float temperature and that will be
equal to let's say 20.4 now as you see as I close this statement out I'm getting an error message and the reason why that's happening is because we did not Define F at the very end so I'm just going to put a letter F at the end and what that tells your computer and Dot net is that this number should Be treated as a single Precision floating Point number what that means is that we're not really so particular or so you know we don't really care very much about how accurate the decimal points are the
decimal values are behind or to the right of the decimal point we just want to have a floating Point number that is single Precision to the single digit after the decimal point and generally the reason why we might want to do that instead of getting more Precise with our value is because floats typically run faster than other data types so if you're not really if you don't really care much about how precise the number is you could just simply use a float in most cases and case of defining a temperature I don't think it's a
big deal if we just use a single point or a single Precision value so let's output this temperature so we're going to say console.writeline as we have been doing and we're going to Just output temperature and we'll close that off and let's run this and let's see what we get all right so as you can see below we get 20.4 and so it looks like that's working okay so if you want to get a little bit more precise with our decimal value instead of using a float data type we can actually use one called double
and double data type gives us double Precision or double digit Precision which essentially means it's a little Bit more accurate when dealing with longer decimal numbers than float is so let's say we want to define the interest rate of a loan this creative variable called interest so we'll say double interest and we'll set that to five 0.53 and close that out now if you notice I'm getting um no error message this time and the reason why is dotnet already understands that this is a standard floating Point Number so there's no need to be alarmed there
so I'm just going to Simply output this so I'm going to do console.writeline I'm going to show you guys something new so we don't just need to always output the variables what we can actually do is we can pre-pin the string or even a pin depending on what you're trying to do a string to the argument value of this right line method so if I want to display additional text for example before the actual value I Can pre-pin the string so let's call this interest and I'm just gonna throw in there a plus sign and
then the variable interest so if I save that and I rerun it we'll see that we have interest 5.53 so that's working as expected that's great all right so now um let's say we want to go even finer than that we want to fine tune this decimal value as much as possible so if you ever work in a bank in the future as A.net developer you may want to use this particular data type because it's going to be the most accurate Precision that you can get from any decimal number so a great use case for
this is working at an investment bank for example or any Bank where you need to be fine-tuned to the decimal point and the name of this data type is actually called decimal so let's define a decimal value uh let's say stock price we wanted to find the price of the current price of a stock so I'm Going to write this out as stock price and notice that this variable I'm actually writing this in camel case so again just to kind of reiterate and just to clarify an earlier point that I made C sharp functions are
written in Pascal case and variables are written in camel case so basically camel case is when the first letter of the variable name is in lowercase and in any following word of the very first letter of that following word is written in a capitalized case Whereas with Pascal case the functions are all written in um you know capital letters when it's the very first letter of a word so in this case I'm using camel case to Define this variable stock price and I'm going to set this stock price to let's say four dot and we
just throw in a bunch of numbers here and close this off now if you guys notice I'm still getting an error message here there's a squiggly line here under the value and that's because just like the Float number I have to specify to dot net that this value is a particular or special uh floating Point number so to do that for decimal I would specify a capital m and the way to remember this is for decimals uh m stands for let's say money okay just for you guys to remember that as a mnemonic device so
now I'm going to Output this and see what we get so console.writeline uh sorry something happened there console.right line and let's say we're Gonna output the stock price stock price all right let's see what we get so if I save that and I run so we're getting our first error message here console does not contain a definition for write so I'm misspelling something here okay let's fix that I know what it is so right line that should work so if I run this now you'll see that I'm outputting the Stock price to the T so
it's a very precise decimal value now you may be asking well why would I use float or double when I could just use decimal there are some performance differences especially when you're dealing with larger applications between the three so I would definitely suggest that you use float or desk or double when you don't really care about having the very very precise value whereas I would use decimal if I'm working with money that's The best way to think of it money or anything else that's very uh sensitive to any decimal being off by you know a
tenth a hundredth a thousandth and so on so that's the best way to uh remember it all right so let's move a little bit away for numbers for now and let's move on to other data types in C sharp so let's say if we want to define a character so a character can be any if you look at your keyboard you see basically various types of letters and Numbers and you know even special characters so in C sharp we can actually assign one of these as a value to a variable by specifying the Char uh
keyword and the chart keyword basically signifies that any value stored in this variable will just be a single character so I guess we can just assign a letter grade as if we're back in school so we'll say Char grade and let's just say that we were good students so you got an A So as you see here we Define just a single character so I can output this and I'm just going to do a simple output here of console.writeline and it should say grade so let's run this in our console and see what we get
and as you can see we're good students because we got the letter A that's great and uh something to keep in mind when you define a Char or a character Notice the difference between that and a string in the case up here we Define a string with double quotes whereas a Char is defined with a single quote or a set of single quotes so that's something to keep in mind remember if you use double quotes instead of the single you're actually defining a string which is actually the next data type I'd like to cover now
this is a very con um a very common one you'll be using across many applications so to define a string of Text we just specify the string data type so let's define a name so let's say string name is equal to Ron which is my name and we close that off and notice that we have these double quotes as I said before now when you use a string you can actually Define a string that just has a single character within it but net will not recognize that as a character would actually recognize that as a
string so keep that in mind Um so I'm going to just set that back to Ron and I'm going to output something interesting here so cancel that right line and what I'm going to do is I'm going to introduce myself so to do this I'm going to use uh placeholders within the string to format some text so to do that I'll type it on I'll show you guys what I mean so to do that within the right line method I'm going to use a dollar sign and double quotes and I'm going to say My name
is and then I'm going to use the curly braces within here and I'm going to give it that name value in a period and then close that off so what I just defined is a formatted string and I'm basically inserting the value of name within the string literal of my name is whatever so let's see if this is working now I'm going to go ahead and run this and as you can see it says my name is Ron so this is another Way to Output string data you can actually use this placeholder method or this
placeholder approach to outputting variable values within a string literal so I hope that makes sense to you all right so we've tackled um characters and strings let's move on to something a little bit different here another data type is what if in our application we want to be able to say whether something is true or false well to do that we can define a Boolean so to Use a Boolean there's a reserved keyword called Bull in.net and let's say for example we want to let's say define whether someone is a student of a school or
not so I'm going to say bull is student and I'm going to set that to true okay so this is so this is basically saying that this particular user is a student for example this console.writeline console.right line and let's see what Happens when I output is student so if I run this as you can see below it outputs true because I Define true or I set that as the value of is student now do notice how this value down here has um a capital T as true now keep that in mind that if you're outputting
um booleans like this is going to capitalize the very first letter so if it were false it would be false with a capital f instead so just keep that in mind in the case of You're trying to convert a Boolean to string and you're trying to you know check for a particular value you'll have to take into consideration the casing as well all right so hopefully that all makes sense to you I'm going to work a little bit harder in showing you here exactly what variables can Drew can do in the true power of variables
so let's say for example we want to just Define or declare a variable without assigning a Value up front we can absolutely do that like this so let's say we want to define the quantity of products and inventory so we can actually just say int quantity and we don't have to assign a value up front we can just Define that somewhere in the file and let's just say we want to define a product so we could say string data type and product obviously we're saying string because the product will have a name and a name
is of a string Data type now in order to assign values to these variables right below it or somewhere further down in the application within the same method call or rather within the scope of the method we can actually set the values so let's say it set quantity is equal to 5 for example and let's set product is equal to bananas hopefully I spelled that something happened here let's try it again bananas Great all right so now let's output that so let's try that console.write line and by the way if you guys haven't noticed there
is a right method also to the console basically the difference between right and right line is that right will output the data or the information to the console without a new line break um between lines whereas right line actually adds or skips to the new line And I'm using right line to make things a lot uh easier to read in the console so let's see here what we want to do is um let's just output here the way that we did above with the dollar sign in the double quotes let's output the quantity of the
product so let's say um product as a string and in here we're going to use curly braces and we're going to say product and then we're going to do a comma and Say Quantity and then curly braces again and quantity all right and let's run that and as you see below we're outputting product bananas and quantity is five so that's working as well so that's basically how we can concatenate values to a string literal as well as you know just declare a variable and assign the values later on pretty simple stuff there is another data
type that's Commonly used in the.net World and it's called constants so let's go down here and Define what a constant is let's say for example we have a value within the application that will never change we never expected to change and we want it to be read only um anyway so for a common example let's say that we're using a mathematical equation and we want to Define pi so we would um specify the const keyword and then if you guys remember remember back From math class you have the concept of Pi uh what happened there
you have the concept of Pi p i it's not letting me do it let's just do it like this uh pi and Pi we're going to set that to 3.14 now obviously it's a lot longer than that but um you know we'll just make it nice and simple I'm just going to change this back to a capital P I'm not sure why my autocomplete was uh acting up there but We're going to set that to 3.14 now the reason why I'm using cons here is let's say I don't want this value to change so I
don't want someone to do something like this I don't want them here you go again I don't want someone to then come and say well Pi should really be equal to two so if they try to do that you see we're getting an error message here and basically it's saying that this is not allowed to be changed because it's a Read-only value so we generally would use this const data type to do that to protect the value and make sure that no user uh is allowed to change it so let's just output this just to
make sure that we've assigned this properly we're going to just say console.writeline and we're just going to Output pi and hopefully that works I'm not sure what I'm getting an error message for let's see uh identifier expects okay identifier expected I'm so silly one thing I forgot to specify here is the type so we still have to specify a type here we have cons double in this case because it's a floating Point number and uh guys again just kind of going back to what I said this is the reason why you know me personally making
mistakes makes me better uh and hopefully it's gonna make you guys better because you guys hopefully were able to catch that uh but you know we just find cons as sort of a Final value uh one that will not change and we still have to specify the data type so Kant is a is like a special data type on top of a data type if you will so now it looks like the error messages are gone if I were to rerun this now you see we see 3.14 in the console and basically we were not
allowed to change the value so that's generally how that works and um yeah that's pretty much uh variables and data types and we're going to get a lot deeper into This as we go along all right so now that we understand variables and data types let's move on to math operators so basically math operators allow us to uh calculate mathematical equations and you know calculate by adding dividing multiplying and subtracting and we could do many other things with mathematical operators as well and this is basically an easy way for us to calculate values within our
program so what I'm going to do here is I'm going to come back up Here to the top to our main method uh and within our main method I'm going to define a new method right here so I'm going to call this method math operators close that out and again we don't have this method yet that's why we have this error so I'm just going to copy its name I'm going to go right back down here I'm going to define a new static void method and it's again void because we don't need to return anything
and we're going to call that math Operators okay so what we want to do is we want to be able to cover all of the major mathematical operations that exist so that you'll be able to work easily with numbers within um these programs so the very first thing we'll do here is let's define a couple of numbers here so let's Define a num1 variable and in num1 we're going to set that to ten then let's define a second number variable and we'll set that to five Uh and in here what we want to do is
we want to First do the addition so I guess we can create another variable called addition and we're going to set that addition to num1 Plus num2 and semicolon and let's just output that and see what we get so console uh jeez console with spelling that dot rightline and we're just going to Output the addition value so when I save that and I run it As you see below it's taking a while sorry there we go 15. so we get the value of 15 because we're adding 10 and 5 together so that's addition it's that
simple so what I would say guys is as we go through these examples feel free to stop the video and try it yourself before we continue so that way you can kind of figure things out on your own and learn how to problem solve so the very second thing we'll Define here is we're going to subtract Numbers so let's do that let's say int subtraction is equal to and we'll make it nice and simple num1 minus num2 so with that being said guys what is the answer going to be here so pause the video um
if you want to and give it a shot yourself okay so now we're subtracting num1 and num two so let's just output what that is so we're just going to Output here subtraction and we're going to run this And you see that the value is five now I want to show something what if for example we said that num one is five and number two is ten so now we're subtracting ten from five so if I re if I re-run this you're going to see that the output now is negative 5 making this integer signed
because it represents a negative value so just keep that in mind we're also able to get Negative values as well so I'm just going to set that back to 10 and 5 to make things simple So you guys can follow along more easily cool so now the next operation we want to show is multiplication of course so multiplication I hope I spelled that correctly multiplication yep so we're going to say num1 and to multiply we need to just the asterisk key so num1 num2 like that and let's just output that as console dot right line
and we're just going to do multiplication Say that and run so now we're expecting 50 and we got it okay so 10 times 5 is 50. and lastly we're going to do division so let's do int division is equal to num1 it should represent dividing or division we're just going to use a forward slash num2 and let's just output that console right line division and let's run this and see what we get So we get two now what happens kind of going back to the example I had before what happens let's say if this were
five and this were 10. let's see what would happen in the case of division so I'm going to run this and as you guys see the answer is zero if you guys remember back to grade school math or high school math even you know when you divide by this number you're basically going to get zero in this case right but there is A way for us to represent remainders in C sharp so I'm going to do that right now but just keep in mind when you divide a number like that um that basically if you
divide uh five into ten or rather ten into five you're gonna you're going to get zero because obviously you're dividing the bigger number from a smaller number so just keep that in mind guys there's also something called the divide by zero exception or it's an error called divide By zero that's something you have to look out for when you're writing code and you need to handle that situation properly so that normally happens for instance if you're dividing ten by zero basically if you don't handle that error properly it'll stop the execution of your program which
is not a good thing especially if you're running in a live environment I'm going to show you guys later how to handle that particular case once we get to exception handling so so Far I've shown you guys how to add multiply divide and subtract but one thing I want to also show you guys is basically how to get the remainder um from a division so for example um let's say we want to divide 11 into 5 but we don't want to or rather 5 into 11 but we don't really care about what the quotient is
we care about what the remainder is so there's something called modulus so I'm going to Define int modulus And that's going to be equal to num uh let's let's change these numbers let's define some new numbers here or actually we'll just write it in line let's just say 11 and to represent modulus you use a percentage sign and let's just use five so what do you guys think this result is going to be let's output it and see what we get so in the console.readyline and we'll say modulus so let's run that And as you
guys see below the output is one why is that well that's because if you divided 5 into 10 into 11 you're left with a remainder of one because five goes into ten two times and then you have one to carry over so that's the reason why so you generally would use modulus for things like if you want to figure out odd numbers versus even numbers um you want to find out how much is left over after a certain division Um operation has been run and so on so there's many different use cases and it's a
very helpful thing uh to use so moving along here let's look a little bit more into various other things that we can do with operations now as I mentioned before there is the divide by zero uh scenario that could occur so let's define that let's say we have another number value let's set that to five and then we have a fourth number value Here and we'll set that to zero now we have a scenario in most programming languages where if you were to do the actual math like 5 divided by zero is going to throw
an error message or an exception uh generally an exception is an error if you think of those two things synonymously then basically that's what it is um so to handle that scenario there's something in programming but specifically here in C sharp called the Try catch block and basically the try catch block allows us to gracefully handle an exception or an error message a error message and avoid the you know stopping the program or you know avoid the program just failing execution so I'll I'll show you guys exactly how that works right now so I'm going
to first of the find the try block here so within here I want to just kind of demonstrate the exception itself so let's say here int division or You know let's use something here let's say end quotient something else that's going to be equal to num3 divided by num 4. okay now normally this line alone should cause the exception but just to be certain I'm just going to cancel that right line here just to be certain that we are um basically jumping to the next block of code on failure so I'm going to uh Specify
here the quotient just output that to the console if it works so in the case of this line not working then we need to be able to catch this exception so to do that we need to just specify the catch keyword and add some parentheses here and the specific error message or exception type we're looking for is called divide by zero exception and then we specify a variable after that of EX which normally stands for Exception by convention So now we're basically saying in the event that an error happens within the try block above catch
that exception and attempt to handle it gracefully so that way your program doesn't just crash it'll continue running but you may be able to Output this error message so let's say a log or a database file or whatever we're going to Output it and save it for or save it to rather so let's just output something here just to make sure that this is working um so I'm Going to do console.wrightline and in here I'm just going to put a string literal of an error occurred and in here I'm going to say e x which
is the exception object or variable and there is a property on it called the message so we'll say dot message and this is a built-in property as part of the.net exception based class which basically allows us to Output the actual error message to the console or to the UI wherever we're outputting our data Uh so with that being said I should be able to run this and I should see an error message so let's give that a shot let's run this and there we go we see an out an error occurred and basically attempted to
divide by zero so whenever you get this exception message basically this is a way to handle the exception gracefully so that way your program just doesn't crash it'll continue running and you'll probably have like a log and a back end That will be able to capture this error message and then you and your team can look at it and figure out the best way to remediate it or to triage it in that way so yeah that's basically how that works all right so now that I've shown you that I guess the only other thing that's
remaining here is to pretty much say that whenever you're working with um number types you can actually cast or convert specific numbers to other number types so for example uh let's say I Guess the best way to show you is with an example let me just make sure that everything's good there cool so let's say um I want to convert an integer to a a double you can absolutely do that let's define an end of num5 for example let's just say 100 uh oh let's just make it simple well different 105. I can actually cast
this to a double and I'll show you guys know how right now so let's say double Um and I'm gonna just say num 5 as double just to let you guys know that this is the double version of that and to cast this it's simple which is going to put parentheses and we're going to say the double data type and we're going to then say number five and now let's try to Output this and see if it works so console.writeline number five as double and save that and if I run this you'll see that it
says 105. now you Don't see any decimal places because of the fact that um there were no decimal points at all but generally it is a double and you can take my word for it that it is now casted to a double um so you may a common use case for that is for example if you're working with an integer and you want to be able to do some clean mathematics between another double value and this double value you might want to convert it this first to a double and then multiply Divide Subtract Against the
other double value so that's like a common scenario you can also go the other way around but there are some things you have to be cautious of whenever you're casting number values you want to make sure you don't lose data as a result so I would definitely recommend going online and looking at the.net documentation just making sure you understand more about typecasting specifically typecasting numbers so that's it for math operators the very Next thing we're going to tackle here is comparison operators so let's go right back up to the top as we had done before
and as you guys may have guessed we're going to define a new variable or rather a new function call so we're going to define a new method here called comparison operators my typing today is bad but comparison operators and let's copy that name here to save us the trouble and we're going To scroll right back down to the bottom of this file here and we're going to say static void comparison operators and just open that up now what is a comparison operator well basically comparison operators allow us to compare values to one another and we're
using these comparison operators usually to specify conditions within an application if we want a certain set of instructions to be executed based on a Given condition we would use comparison operators in conjunction with control flow statements such as if and else statements to control the logic the actual logic of the application so let's start over here by first uh declaring a couple of variables so I want to declare a couple of uh integer variables so let's say int a is equal to 10. and int B is equal to five to keep things simple okay and
the reason why I'm defining these is because I'm going to be using these within our comparison operations to show you guys exactly how this works so the very next thing I'll do here is uh let's declare a Boolean and that Boolean will list will say is is equal so we want to find out if these two numbers are equal so uh to do that let's open up some parentheses and say it's equal if a is equal to B okay so just to let you guys know what this is this is a comparison operator This double
equal sign represents equality if you notice to the left of that we have this single equal sign so the difference between the two is a single equal sign specifies assignment so when you're assigning a value to a variable for for instance double equals specifies equality so you want to use double equal signs if you want to compare two numbers or two strings to each other or two objects in some cases and so on so let's just output this and Let's see if 10 is equal to 5 and I think that if you guys are good
at math you already know the answer to this so we're going to Output it the Boolean value of is equal so I um obviously this will either be a true or a false value so let's run this and as you guys see the very last output it's false so 10 is not equal to 5 is that's exactly what we expected but now let's go the other way with it let's say we want to find out if two numbers are Not equal so again I'm going to Define another Boolean and say is not equal and to
check for inequality what you want to do is you want to use an exclamation mark with a single uh equal sign like this so a exclamation not equal to B and let's cancel that right line that console.writeline is not equal now what do you think the answer to this would be let's run it and find out it's true now why is it true because Obviously 10 is not equal to 5. so basically we did the inverse of the is equal above and this is very very helpful because then if you're not really sure if something
is equal or not equal you can just kind of determine based on the given circumstance which one you should check for so the next thing we want to do is obviously you probably guessed it we want to find out if 10 is greater than 5 so we're going to say bull is greater And we're going to say a is greater than b now greater is specified I as you know it from school times uh is specified by a right angle bracket so let's go ahead and output that console.rainline is greater and let's run that and
as you can see it's true because 10 is greater than 5. let's go the other way around let's check for less than so boom is less And we're going to say if a is less than b and obviously we're expecting false here because 10 is not less than 5. um console that right something's wrong here so this is a right line it is less all right so let's output that happened here there we go let's output that and as you can see it's false because 10 is not less than 5. so it's pretty simple you
just got to kind of think of math your math classes back in The day and you know you could pretty much figure out you know what to do here but we've got more so let's say if we want to find out if a number is greater than or equal to another now as you can see above we've already specified greater than but let's do is greater than or equal and to do that we're going to say a if a is greater than or equal to B so basically a greater than sign followed By a single
equal sign and so let's output that by console.writeline and then we're going to say is greater than or equal and let's output that and that outputs true because 10 is greater than 5 okay it's still greater than five it's not equal to 5 but it's still greater than five so now we're going to go the other way around with it we're going to say if the uh 10 is less Than or equal to 5 less than or equal parentheses a is less than or equal to B this new console that right line and is less
than or equal to and semicolon let's run that and that's false because 10 is not less than 5 and 10 is also not equal to 5. so basically all of this is working and I will say there's really no reason for you to have to write unit tests for simple equations like this because your computer is rather smart when it comes to Mathematics so yeah this is definitely how you you know use math or arithmetic operators within an application all right so next up is logical operators so basically we can use arithmetic operators together with
comparison operators and logical operators to write some pretty Advanced code or Advanced logic within our application to have it do some pretty cool things so what I'm going to do next is I'm going to scroll right back up to Our main method again and in our main method I'm going to write another method call called logical operators and close that out and then I'm going to copy the name again let's make sure it's copied let's go down to the very bottom of the file and let's uh specify or create a new method called logical operators
so basically with logical operators There are many of them that can be used to specify whether we want to check for two or me or more conditions to be true or false or if we only want one of them to be true or false and I'll show you guys exactly what I mean um with that so basically what I want to do here is I want to be able to specify whether two operands um are true together or if only one of them is true and I'll kind of explain More about it as I go
along here but let's just start off by defining some variables so let's say that the first variable is a Boolean data type and we'll call it X and we'll set that to true and then we'll create another one called Y and set that to false and this is going to be the best way to help you guys understand exactly what I mean so by uh we would use for example if we want to check that two operators are Um uh creating a condition that is equal to true we would use the and logical operator and
it's written like this so let's create another variable called and result and that is going to be equal to X and Y so basically what this is saying is if x is equal to true and Y is equal to true then the entire condition is true and as you can see this is how you can start to build some very complex logic so let's console that right line this can you Guess what the result is going to be in this case so let's go ahead and run this and as you can see we get a
result of false now why is it false well going back up here to the where we declared and uh initialize these variables X is equal to true and Y is equal to false but down here we're saying we're betting on basically X being true and Y being true but in this case because Y is false then that means that the entire Condition is now rendering to false because X is true but Y is false I hope that makes sense um so basically both conditions must equal true not necessarily true the value but they must pretty
much um evaluate to true in order for the entire result to be true so let's do this with another example let's create a situation where only one of them needs to be true so we're going to call this bull or result And we're going to say if X or Y and or is represented by a double pipe character so if x or y then it's basically going to evaluate to either true or false so let's cancel that right line this we're going to Output or result now based on this we expect to get back a
true and the reason why we did get back true is because X is equal to True Y is equal to false so what happened here let me explain why this works as I Said before this logical operator is a double pipe which symbolizes or an or condition either this or that is true in this case X was the very first thing that was encountered here or that was executed which evaluated to true there's a concept called short-circuiting and basically in computer programming a short-circuited language like C sharp will stop evaluating a condition as soon as
they find the very first condition in the evaluation that's true so in this Case X is true so then the code stopped pretty much evaluating this entire statement once it found that X was true if y were first and then X were second then y obviously with it being false this will evaluate to fall so then it would run X as a second parameter and check if x is true and then in that case the entire um statement would evaluate to true in that case so either way it would be true it's just a matter
of which one is being Put first and if we're short-circuiting um you know out of this evaluation so hopefully that makes sense you know you might want to read up on that online if it doesn't or maybe just kind of re-watch this several times until it does make sense let's move on so let's say that we want to negate a circumstance I'm going to give you two scenarios here so you can hopefully understand a little bit more about the end result part as well but if you want To check for the exact opposite we can
use a not operator which is just an exclamation mark so let's go ahead and Define Bull and call this not Result One and we're going going to set this to basically what we see above with the and result If X and Y but instead this time we're going to say if x and not Y and the reason why we're doing that is because of this we want this to evaluate to true in this case just as an example so we already know that X is true and Y Is false as said above but because I'm
specifying this exclamation mark in front of the Y they were basically saying if not false which is basically true so now with that being specified we're basically expecting this to evaluate to true so let's output this as console.writeline and we're going to say not result one and let's run this and as you can see it evaluated to true And the reason why again is because X is true and in this Con situation Y is normally false but because we're putting this exclamation mark in front of it we're basically inverting it to true so true and
true is equal to true so that's basically how that works let me give you another scenario let's say for example I want to just invert X on its own and as we already know X is currently true true so now I can say bull not not result to is equal to not X So we're basically just inverting X so the inversion of a true value is a false value so that's what we're expecting to see so if I console that rightlineness and I just say not oops not result two what do we get let's run
that and basically we get false because the inversion or the opposite of a true is a false and being that X is true the opposite of true is false so X is now false or not result two rather is false so that's basically logical Um the first set of logical operators that you definitely need to know more about and you know again you know you would use this generally uh together with a lot other Logics such as flow statements or control flows like if else which will get to a little bit um you use this
together in conjunction to be able to evaluate or set conditions and and so forth so that pretty much sums up logical operators is pretty straightforward um You might want to read the documentation to get a little bit more understanding of exactly how that works in tandem with other types of operators and control flow statements so let's just kind of keep moving on because you still have quite a bit to cover here so I'm going to cover next conditionals and again this kind of works in tandem with logical operators as well as math operators and comparison
operators you don't necessarily have to use all of Them together but there are many scenarios where you would use kind of like a mix of all of them or just a couple at a time and so forth but conditional operators or rather conditional statements are very very important in programming because they allow us to Define certain Pathways within our logic so let's go ahead by creating a new method call here called conditional call it conditional statements It's cool I'm just going to go ahead and I'm going to copy this and I'm going to go down
below all the way to the bottom so you see this code is starting to stack up and we're going to define static void and conditional statements now in a conditional statement uh what we generally mean by that is there are many different conditional keywords in the.net programming languages and in fact a good bonus here is that many of These are also used in other programming languages so once you learn it here you pretty much know it for majority of the C uh programming language derivative languages out there and uh so we're going to start off
with the if statement or the if else statement and basically what that is is we're basically going to say if a condition is true do an action otherwise do something else so the best way to show this is by an example so I'm going to first off Define a new integer Variable called age and I'm going to set that to 25. and then next I'm going to Define this if statement and so we did do that by just saying if and within this parentheses we just specify the age variable and then we can um use
something like a comparison operator to compare this age to another value so for example we could say something like if age is uh greater than 18 . so actually you know what let's go this way with it let's say if age is less than 18 then we want to say something so let's say for example if this person is under the age of 18 we're going to say you are a minor right um now usually when we have an if we could just have this if block by itself but even more commonly seen is when
you normally have an if you would have an Else but just to kind of demonstrate what this is I'm gonna just run this and I want you guys to kind of guess what might happen here so I'm just going to run this with just the if statement or the if block and as I run this you guys can see that nothing happened okay and nothing happened because age is equal to 25 and 25 is not less than 18. but if I were to change this age so let's just say 5 years old and I run
this again Now you'll see that you are a minor so that basically evaluated to True once it got to this line it said okay what's the current age your current age is five and five is less than 18 so you are a minor gets outputted to the console so I'm just going to set this back to 25 or yeah 25. and uh let's move on so that's if but as I said before more commonly with if you would also see else so now let's define an otherwise scenario so if this is not True then do
something else so let's say um if the person is not a minor we can just console that right line you are an adult nice and simple all right so if I run this it we should expect to see you're an adult and we do and the reason why again is because 25 is greater than 18 and because this statement evaluated to false in this case this age is less than 18 that's the reason why we're getting we're hitting This block down here and we're getting this output now to make things a bit more complicated but
powerful there's something called the else if block as well and the else if block allows us to chain multiple if statements together so here's an example in this case let's say for example we want to specify if the person is between 18 and 65 years old so in that case let's just do something like this let's first of all I'm just going to Come down here and I'm going to just remove this output statement from here for now and I'm just going to come up here to right here Oops why is my cursor not working
here okay so I'm just going to put my block here on line 140 and I'm going to say else if and I'm going to Define another else if here and just open up that so we don't get confused all right so basically in this S elsif I want to say if this user is between the Age of 18 and 65 then they are an adult so let's say age is greater than or equal to 18 and here's where we can use the logical operator of double and sign so we're going to say double and sign
and we can say age is less than or equal to 65 years old so if that's the case if this is true this just paste in what we had before you are an adult so basically your working age between 18 starting at 18. So um greater than or equal to 18 and less than or equal to 65. otherwise if that is false in this else block we're now going to say console.rightline you are a senior Simpson all right nothing wrong with seeing citizens by the way folks alright so now let's see what we get so
again ages 25. so what do we expect this output to be let's run this and we see still that you are an adult And again if I were to change this age to below it 18 let's even say 17 and run this we're going to see you're a minor if I change this age to 18. right on the bound there let's run this again we see you are an adult if I change this age to let's say 100 congratulations we see here you are a senior citizen so this is working so again with a chain
of if and else if and if and else Statements we can actually chain together different logical flows within an application this is very powerful and being that you learned it here it's more than likely going to apply to most C derivative languages so like languages like JavaScript then Java and uh you know even python even though it's using different um you know keywords you can still literally use the same Concepts in all these programming languages once you Learn it once you'll never forget it that's the good thing about it all right so let's move on
to something else here and for this one I'm just going to copy some code that I have written somewhere else because it's rather lengthy so just bear with me for a second here let's just grab this and basically what we're going to talk about right now are switch statements so what a switch statement is is similar to an else if statement but a switch statement allow allows you kind Of like in a tree-like structure to Define different um you know logical flows within a one single block of code so kind of to show how that
works I'm just going to paste this code in here nicely and quickly here and kind of walk you guys through it because it's quite a bit so what I did first up here is I defined a day variable and I set that to three so that kind of represents the day of the week the third day of the week if You will then I have here a string data type variable called they name so the name of the day of the week Monday Tuesday Wednesday and so on so in here I Define a switch statement
and again a switch statement think of it almost like an else if or sorry an if and else if uh statement but essentially it's just one code block and allows you to logically list out various conditions that exist and then um run actions based on those conditions evaluating to true So here we have this day variable that I specified that I'm passing in and basically what this switch statement will do it will check each case to see if day is equal to a specific value so as you can see here in this code Block in
case number one it's looking to see if day is equal to one um because we specify a day is equal to three then we would expect that this case three would run and it would output Wednesday as a result now you may be Asking yourself what is this break keyword within each um and every um sort of Branch well the break specifies what must happen like basically we're exiting this branch of code if a condition is true and the reason why we do that is we want to Short Circuit again going back to that term
we want to Short Circuit execution of a certain Branch if the condition has been evaluated to true so in this case of case three because day Is equal to 3 is going to go to this code block and day name is going to get set to Wednesday and then we're just going to break out of this entire switch statement and it's just going to exit so let's try to run this and see if we get this output below so if I run this okay I see an error message type of namespace definition okay so we're
having an issue here and I think it's because we have this extra bracket on line 176. so I'm just going To get rid of that and save and run it okay and as you see here we have today is Wednesday and again the reason why we get Wednesday is because day is equal to three and being that we're passing that day value into our switch statement as an argument is basically evaluating this case to true and it's assigning that Wednesday string literal today name and and short-circuiting out of the execution so that's basically what's happening
if I were to change this to One then we would expect a different output and that would be Monday so I did that and now you see that today is Monday so this is working so now why would you use a switch statement instead of an if else if an else block well generally if you're going to have a lot a lot of a lot of different branches of logic within a single method you might want to use a switch statement if applicable because it's going to save you a lot of code lines right you
you'll Write a lot less code to do the same thing it's also a lot easier to read depending on exactly what you're writing so I would just say you just need to use your best judgment whether and if else if makes more sense or whether it makes sense to do a switch statement I personally prefer to use switch statements if I'm writing more than three branches of logic so if for example if I say if I have a condition that could have more than three possible Logical routes then I would use a switch statement in
that case because it would be a lot easier to read and a lot easier to change in the future however if I have like three or less I generally go with an if else if only because there are some programming languages that don't have the switch case um statement so just keep that in mind so that's pretty much how logical operators work so now let's move on to loops and what Loops are they're basically structures that allow us to iterate through various Collections and what that means is instead of writing code repetitiously over and over
again in some cases we can use Loops to save us some time and write less lines of code because a lot of the information would be the same or you know would be pretty similar or even a lot of the logic would be similar so that's the reason why we would use Loops so let me just kind of demonstrate you How that works I'm going to go right back up here to the top and in our main method here I'm going to Define another another signature here sorry so we are going to call this just
loops and close this out and then we're going to come to the bottom here of loops and we're going to or rather of the prior method and Define a loops method like that okay so I think the best way to demonstrate this is kind of working with Various data types and kind of show you exactly how this would work so let's see let's say for example we want to iterate from um zero to five and we just want to Output the numbers to the console we want to show um each number outputted in repetition or
in in iteration so to do that there's something called a for Loop and we would write it like this we say four the next part is we in within the parentheses we Specify the data type which we most more than likely nine times out of ten be integer and then we give it a temp variable or a temporary variable this variable would serve as a counter that serves its purpose of sort of keeping trap track of the iteration within the loop so we're going to call this int I is equal to zero to be the
starting value of zero then semicolon the next thing within this loop we're going to specify is the condition at which the Loop should end so we're going to say if I is less than 5 or actually you know what let's do if I is less than or equal to five and what we expect this Loop to do now is we expect it to iterate from zero to five so zero one two three four five lastly as a condition here we specify something called an increment operator now the increment operator is specified with a double plus
sign and what that is basically doing is it's taking the value of I on the on the First iteration for example uh in the first I will be equal to zero and it's incrementing that count by one on the next iteration so then on the next iteration I will equal one because I um sorry because zero plus one is equal to one then on the following iteration it will equal two because one plus one is equal to two so if you want to increment instead of saying I is equal to I plus one you can
actually say I is equal to double Plus or I double plus And that would increment the value on the other side of things if you want to decrement you could say I double minus and that would reduce the count by one so let's go ahead and close that up here and within this block all we want to do is something simple we want to console.writeline the output of the number and to do that just to kind of make sure that you know we're outputting the correct thing I'm going to put a string literal literal in
here and I'm Going to say number is equal to or not equal to but number is of I so we're just outputting the value of I in this case so if I run this it's taking a while there we go so we see that it's outputting zero through five on each iteration of the loop the loop will basically what will happen is uh once it hits this for loop on line 180 is all it's going to do is check the condition it will initialize the Variable to zero it will check if zero is less than
or equal to five and then on the next iteration of the loop after the console.writeline is outputted it will increase the counter to one and then then two then three subsequently so that's basically how a loop Works um a for Loop specifically Works in C sharp now the good thing again is that this knowledge is into is um transferable you can actually use a similar structure in other programming Languages so again you're learning it here is applicable to many programming languages now the next thing we have here is the while loop and a while loop
is generally used when you're not really sure about how long a loop should one but you want to specify a condition that needs to be met for the loop to to exit so basically how that works I'll give you a simple example here let's say if I Define a counter variable or let's just say int Count is equal to zero okay so Inc count is equal to zero and the reason why we want to specify this integer variable is we wanna we wanna avoid a circumstance called infinite looping and basically what that is is when
you have a while loop and you don't have a counter somewhere somewhat getting incremented or decremented within the while loop it could be that that while loop will run infinitely and when that happens it could lead to a Stack Overflow exception in some programming languages or a memory leak so generally what you want to do is you want to specify this count variable or a counter variable to avoid that circumstance from happening and let me demonstrate so next we're going to Define our while loop so we say while and we're going to say while the
count is less than five so something similar to above but we're just going to say less instead of less than or equal to so While this count is less than five let's just output here console.readyline what we're going to Output is let's just call this a string literal of wild count and we're just going to Output here the count and if I were to run this just like this we're going to have the infinite Loop scenario because we're not incrementing or decrementing five so in this case we're not incrementing it so that this Condition here
this count is less than five will ever evaluate to false because once it what needs to happen is this needs to evaluate to false in order for the program to exit this while loop while while this condition is true it's going to continue to iterate and loop through uh the the set of instructions so what we generally want to do here is below this we want to say count plus plus so that way we increment this count as we go along and eventually this count Will hit five and once it does that then this program
will exit this while loop so let's go ahead and run this and see what we get so as you can see now that we ran this we don't see zero to one million or any large number we actually see Zero through four and the reason why is because the loop exited as soon as count equaled five because the value uh the statement evaluated to false in that case so that's basically how you use a While loop again we would use this instead of a for Loop if we're not really really really sure in advance how
long we want something Lou we just wanted to Loop and we may specify this count variable you don't necessarily need to use the counter in this section here you can actually use any other kind of like Boolean evaluation or Boolean variable here you just got to make sure you have a counter set and that somehow whatever you set that needs to be sort Of like included in this evaluation so that this will eventually exit the loop and avoid an infinite looping scenario so the next type of loop we're going to cover here is the do
while loop and basically the difference between a do while and a while loop is that a do while loop is guaranteed to execute at least once whereas a while loop does not have that guarantee that will execute it at all especially if the evaluation of the statement is false so in this case Let me just demonstrate so let's say for example we are we'll specify a do while loop here and it's written like this we say do as a keyword and then at the very end of it we say while and we'll we'll use the
same counter variable we'll say if the count is less than 10 and don't forget to put a semicolon this is actually one of the only Loops that actually has a semicolon at the very end of the line and if you don't do that you'll get an error message so make sure That's included now what we want to do here just before we write the code here within the loop is we want to be able to reset the value of count to zero so that way we can clearly see the output all right so what we
want to do is let's just output console.writeline we're going to call say do while count and we're just going to Output count and let's not forget guys to also increment our account because if we don't we're Going to have an infinite Loop situation and then it will be hard to uh continue running this code so let's go ahead and run that and see what we get so after running that as you can see uh sorry my console skipped somewhere up as you can see here we actually iterated from zero to nine as you can see
here so this is working as expected basically what happens is the iteration runs at least once and then it basically evaluates thereafter this statement here So it's guaranteed to run this console right line within the do and then it does the evaluation of count is less than 10 and then what basically what we're doing here is we're incrementing the count by one on every single Loop and then until it reaches uh 10 and once it reaches 10 it exits the loop so that's the do while um to be honest with you is not used as
commonly as other types of Loops are but it can come in helpful if you want to guarantee Execution of a block of code at least once so it could definitely come in very handy there all right so there's also some other types of Loops that we can cover um I'm just trying to think if I should show you for um the four each yeah you know what I'll go ahead and show you we may be jumping the gun here a little bit but I'm gonna show you guys the for each Loop so generally in the
four e with the for each Loop is is a basically a Special Loop type that iterates through a collection or an array so an array and a collection are basically sort of if you think of like a list of various values contained within a box that you you have like various values of the same data type and use usually in most cases and that's basically what a collection is it's a collection of values usually of the same data type that you can use to store multiple values within that list or within that Collection so arrays
can be used in that fashion as well as list sets there are multiple types of collections that we'll go through shortly but what I'm going to do is I'm just going to use a simple array since it's the simplest type of collection uh collection collection structure if you will uh just to demonstrate how a for each Loop works so what I'm going to do here is I'm going to specify an INT array and we do that by first specifying the data type which Isn't and then we have this opening and closing bracket square bracket that
signifies that this is going to be a collection of values or an array so we're going to just create an array of numbers so we give it the name numbers and within this array we can just open up some curly braces and specify the numbers so one two three let's go all the way to five there you go so now we have an array of Five numbers within it now one thing I want to point out here we're going to cover a race shortly so I'm not going to go too much in detail but basically
every single position of this of an integer within this array is called an index so basically the value the integer value of one is an index of zero the integer value of 2 is an index of one so basically it's a zero in or rather a zero base index where the first position within an array a list or any other type Of collection is basically the zeroth uh position it always starts with zero so if you want to grab the value of one you would specify the index of zero if you want to grab the
last one you would specify whatever the last position is minus one so in this case we have five numbers it will be the index of four not the index of five and you have to know that because you want to avoid error messages especially index out of balance exceptions so let's go ahead and kind of Demonstrate how this for each Loop works so to Loop through and output all of these numbers I'm going to type the keyword for each with no space in between and then I'm going to specify here what our conditions are so
within the parentheses what we want to do and I'm just going to type this out and I'm going to walk you guys through it we're going to say int number in numbers and curly braces so basically what this says here guys is that for each Iteration of the loop we want to grab a single number from that index the value from that index which is an integer data type and we want to grab that from the collection or array of numbers and let me show you how this works with the output so if we console.rightline
and we're going to say number number in array for example and we just output the number if I can type it number yep and let's run that let's see what we get Cool so now we see here that what the loop what the for each Loop is doing is starting with the number one which is in the zero width index or the index of zero and it's outputting every single number until the very end of the list now why what is the huge selling point of using a for each rather than just using a simple
for Loop because you could do something like this as well and I'll just show you guys the difference you guys could have done something like This you could say four and I is equal to zero and then you can see if I is less than numbers dot length and basically what this dot length property is is this is a property that gets the length of an array so how long the array is so in this case it would be five right it would be uh the length of five because there are five items in the
array and then you do the I plus plus And then you could have said console.wrightline and then you could say using standard just to kind of differentiate here for Loop and then say number and in here you could have said something like numbers of I so basically what that's doing is on every iteration of the array is I'm going to Output uh using the current value of I whatever is in that index so On the first iteration I is equal to zero so it's going to get the number that's in the zeroth index of the
array and just to make sure that works let's run that and as you can see here we are getting the same output as we got with the four each so now hopefully you guys can see the difference basically um looking at this I would say the for each Loop is a lot simpler to understand if I'm a new developer and also you Don't have to really worry so much about index out of bounds exceptions so for example I'll show you guys an example let's say for example just really quickly we know that we have five
items in the array let's say if I try to grab the 10th item or rather the um yeah the 10th index in the array if I were to run this now you guys see that you we have a bunch of gibberish here saying unhandled exception and it's basically an index Out of balance exception and the reason why is because we don't have 11 items in the array because I'm grabbing the 10th which is essentially the 11th item in the array we don't have 11 items that's the reason why we're having this issue so I would
say honestly it's much safer to use the for each Loop instead of using the standard for Loop when you're dealing with collections because then it's it's all I don't want to say you're guaranteed to not have problems but You're you're a lot safer using a four each in this case when you're not sure how long a collection is or how many items are within the collection okay so those were loops and um we also covered a bit of a raise but I want to go a little deeper into it and I know I jumped the
gun but I wanted to be able to show you guys how for each loops work and how they work together with collection so let's go ahead and let's jump into a raise so what I'm going to Do is I'm going to scroll right back up to the top and I'm going to go back to my main method and in my main method I'm going to create a new function call called arrays okay and then I'm gonna go right back down here and Define a new method called Erase so let's just Spruce this up a little
bit let's say static void arrays okay so all I'm going to show you here is basically a little bit more about how arrays work you already know a bit from Above when we worked on the uh for each Loop but let's go ahead by start let's start by defining a string array so we'll say string array and we'll have an array of names now above what I did is I used curly braces to Define an array which is the shorthand way of doing it but let's say we want to hard code and specify a certain
number of indexes within the array or some certain number of positions we can definitely do that by using the new Keyword and say new string curly braces and specify the number of positions I'll say three here so what that means is we are not allowed to Define more than three positions within this array if we do if we try to assign a value to let's say the fourth position we're going to get an index out of bounds exception so let's go ahead and Define some names so the first name which will be in index of
zero will be run The second name which will be an index of one will be Katie and the third name which will be an index of two will be Jack all right and if we want to know definitely I mean we can simply see that there are three items in the array but let's say we don't know that if we want to know how many items are in the array at any given point we can use the dot length property on the array class within.net so what we say is names dot Length and that should
give it to us so I'll go ahead and run this and as you can see the length is three because we have three items in the array okay um and again if we want to listen just say grab a specific value from the array let's just say we want to grab the second value or the second item we just need to Simply see names of one because we want the second item so if I run this You see I get back Katie because she's the second person in the array or the second name rather in
the array so that's basically how arrays work on the uh uh in the in the easiest way possible that I can explain arrays are very very powerful because you can do many things with them you can iterate over them you can hold many different values you can even have an array of objects which are a little bit more generic in a sense but That's generally how arrays work now with that being said we also have other data structures within C sharp that works similarly to arrays we have ones called collection so let's scroll right back
up to the top and let's demonstrate how collections work by defining a new method called Collections and back to the bottom we go uh and down here we're just going to define a new static method static void collections So in general in a nutshell what a collection is it works similar to an array but there are specific characteristics between various types of collections so generally you have collections such as lists sets or hash sets dictionaries cues and stacks and each one of these have special behavior and characteristics that set them apart from one another so
let's start with the very simplest one that I love to use a lot called list so if you think of a List a list is very similar to an array but the difference between a list and an array is that a list is dynamic an array is usually not Dynamic what that means is that I can insert items into a list at any given point of the programs running or execution whereas with an array is a little bit harder to do that because in most cases you would define an array when you know that you
have a specified set of values that you want to use and those values won't update as Much so let's go ahead and demonstrate a list so we have a list I'm going to create a list of string and let's see let's do something different here let's let's say we'll have a list of cities and again we will construct or initialize this list with the new keyword and a list of string so this is how we initialize a new list notice that we have a new list and we specify the data type between these Angle brackets
and that's basically how we specify the type of data that would be stored in this list so we want to have a list of cities and generally what we want to do is we want to add just a couple of cities to this list it doesn't matter how many we can add one we can add five we can add a million but I'm just going to add let's say three of them so let's say the first city is going to be my home City New York The Second City will be a very cool one indeed
oops Tokyo if I could spell Tokyo please don't get mad Japanese people and the first the third one will be Berlin okay so now we have this list of um cities so essentially we have a list of Link three here now if we want to access these um these values it works similarly to arrays so we can say console.writeline And we can say for example if I want to grab Berlin I can just say cities of two because we want an index of two not an index of three remember because Berlin although it's the third
item in the list it's the I it's in index of two because it's a zero based collection so if I run this we see we get back Berlin which makes sense now if I want to know the if I want to know the length of this let's try this Console.right line cities dot if I try to write length you notice nothing comes up that's because the linked property is specific to arrays if you want to know how long or how large The Collection is in the case of collections versus arrays with collections you would use
the count uh property instead of the length property so if I do cities that count and semicolon and I run this we see that we get back a count of three And just to make sure that everything looks good here and we're I'm just going to add another city I'm going to add Sydney Australia right Sydney so if I go ahead and run this again we see we get a count of four this time that's because we have four items in the list so that's basically list and one other thing I'll point out about lists
is that list can contain duplicate values so just keep that in mind you can Actually have multiple sydneys in there multiple New Yorks in there nothing will ever happen because lists are Dynamic and they allow duplicates now I want to move on to another collection type I guess we can move on to Hash set well actually you know what before I do that let's go ahead and show you how to Loop through a list that works very similarly to looping through an array you can actually use a for each or four or you can even
use a while loop if you If you had a counter variable you can use any Loop possible but in this case I love using for each so for each we're going to Loop through each City and output them in this case we are storing strings so we're going to um specify that each temporary variable will be a string data type and we're going to just say City in keyword cities so for each City and cities all we want to do is cancel that right line And we're going to just say City so if I run
this you're going to see that we get every city outputted to the console so that it's just that simple guys like the four inch Loop in tandem with collections is super powerful and super rudimentary it's very easy to use um in most cases so let's go on and move on here now you have something you have a collection type called hash set Um and what a hash set does is it allows you to store values just like a list but um you are not allowed to have any duplicates in a hash set and what I
can do is I can show you how that works I guess I'll show you that before a dictionary but let's go ahead and do a hash set so let's say for instance we have a hash set um and this also make that a string data type and we'll call this [Music] countries make it simple it's a new hash set of string perfect see that auto populated it for me all right so similarly we can add values to these this country's hash set like this we can say countries dot add and let's say Germany countries dot
add and let's say USA and countries dot add Uh something happened there countries that add and let's say Japan okay all right so now again if I want to find out what is the length of this I could say console.writeline and I can say countries dot count okay and just to kind of you know separate this here just so we know that this belongs to this let's just have a string literal here and just say countries oops I misspelled that Countries count so we know what that is plus sign all right so if I run
this we see we have a count of three in countries count that's because we have three items in the set now what I want to show you what I meant by that duplicates are not allowed let's say if I were to come here and I would add and I'm just going to copy let's just say if I copy this line This Japan line or even you know what let's Copy the USA line I'm patriotic so let's copy this and paste it here what do you think the outcome is going to be if I run this
you see it still outputs to three why is that well that's because even though I added a second USA item to the set to the hash set hash sets do not allow duplicates so that's the reason why that didn't work it looked at the current um it searched the entire hash set for An existing USA value found one and said well this is a duplicate let's not insert this so you generally would use hash sets if you want to ensure that the data that you're putting inside is not duplicated data so this is very powerful
in a sense and again to Loop through a hash set we can use the four each so we can say for each country in countries uh let's get my braces correct here and what we can do here this is console Dot right line let's just output the country right here save and run so we get an error message it looks like one of our braces is free somewhere where is this happening am I missing one okay let's try that there you go so there we go so we see here we're outputting Germany USA and Japan
so again for each Loop works very similarly really no difference Um it's the same structure the same syntax and so on so that's basically sets so again you you you basically would use a list when you want to have duplicates in the collection and you would use a set or a hash set when you don't all right when you don't want to have duplicates now there's an even more powerful uh collection uh data structure that exists in net C sharp uh it also exists In other programming languages and they're referred to as maps and other
languages but in C sharp it's referred to as a dictionary and what a dictionary is is a key value pair um collection so it's a collection that has key value pair entries and what that means is the key is usually unique it doesn't have any duplicates whereas the associated value with that key can have duplicates and you would generally use this data type when you want to access Data that could be repetitious but differing based on the key or you might want to use it to quickly index sets of information so let me just demonstrate
I think the best is through writing some actual code best way to demonstrate so as you see here I already started typing and I'm getting dictionary but I'm going to type it everything out by hand I'm not going to use the shorthand here so I'm typing out dictionary and hmm Let's see what do we want to do here let's make a dictionary of a string key type and an integer value and basically when I have an uh a dictionary of age of various ages of people so we're going to call the variable age dict and
we're going to use the key word of new and we're going to say dictionary dictionary dictionary I hope I'm selling that correctly stringent all right So to Define an entry which is a key value pair we just simply would uh specify the keys and um and then assign the values to each key now I'm trying to think of how I can best do this in the cleanest way possible and I think the best way to show you this is let's just start off by defining a string variable and I'm going to do and you'll see
what I'll do in a second so I'm going to define a string variable and call that the dictionary key and I'm Going to just put the name of Alice in there so that's going to be the name of a person uh in there and now what I'm going to do is I'm going to say age dict is going to be dict key index addict key and I'm going to specify that as 30. so basically let me explain what I'm doing here is I'm inserting the value of 30 as a value with uh that should be
Associated to the key of Alice so it Will look something like this it would look like um let me see the best way to describe this um uh sorry uh what let me just do that here the best way to describe that is this let's imagine you have this structure and this is the key Alice and then you have an age of 30. and then if you you were to add another entry it may be like Bob or something Like that and then you have an age of let's say 75 and this is a dictionary
because all we need to do let's say if we want to grab Alice's information and it just doesn't have to be an integer it can actually be another object it could be anything but let's say if I want to grab Alice's information I could just say in the age dict give me Alice and it will give me all of the associated data that's after this colon for Alice in this case it Would just be the age so that's basically how that works um so now moving along here let's say if I want to use a
control statement let's say if I want to use an if statement to check if the if Alice exists and this is a common thing you would do when working with dictionaries so let me just show you if I say age dipped there is a function um that's part of the dictionary class called contains key And the contains key method we'll check to see if a specific key a key I don't want to say value but if a specific key is a part of a dictionary entry so here what we want to say and this is
the reason why I stored Alice in a variable so I don't have to retype Alice I can say dict key because again that's still Alice the value of Alice so I'm basically saying in this dictionary is there an entry with the key of Alice if there is one I Want to say console.writeline let's see this output Alice's age let's do something very interesting here so let's do a formatted string I'm just going to put a semicolon here before I forget and in that formatted string we're going to have a curly brace and we're going to
say um this say Alice so again that's the dick key that's Alice right that's the name of Alice I'm gonna just do apostrophe s just follow along guys and the age and we're going to Output the age now we output the H by saying age dict opening and closing square brackets and then we put dict key so basically that's going to fetch for me the integer age which is in this case going to be 30. so I'm not sure if that's going to work but let's give it a shot let's run it and it did
work so Alice's age is 30 as You see here and basically I use string concatenation to insert Alice's name which is stored as dick key that's the variable and then uh basically I'm getting her age by just referencing that dictionary and pulling her entry out by the key so in that case because it exists um it executed this if statement but what happens if we don't have that value then generally you would just have like an else here to do something else right So you might have a common sort of logical flow here is to
have an else statement in which you would insert a value into the dictionary if it doesn't exist especially if you're working within a for Loop context so that's like a very common thing you'll see in programming but in this case we don't want to do that we just want to continue with what we were doing here I just wanted to demonstrate that so now let's say if I want to Output Everything that's in the dictionary I can do that with a simple for each but before I do that let's just hmm let's let's maybe just
add one more um person to the dictionary I'm just going to add it in I'm not going to Define another string variable so let's come up where were we here we were here I'm just going to add another person here so age dict let's say Bob and Bob is 75 now let's just add one More person age debt and let's say Tracy and Tracy is 18. okay all right so now what I want to demonstrate is exactly how do you iterate through a dictionary it's slightly it's slightly different um the reason why is because now
we're working with key value pairs we're not Just working with simple primitive data or simple objects so to do that we can still use the for each like this so we can say 4-H but what we would do instead here is we would instead of seeing int or any specific data type we would use the VAR keyword and what the VAR keyword is is sort of like a generic data type it's basically specifying we don't know what the data type of this entry is so let's just use VAR this is a common convention In C
sharp so I'm going to say VAR entry in age dict so for each entry that's in the dictionary we want to do something now what we want to do in this case is we just want to Output the key and the value and to do that let's just say console dot rightline we're using that a lot today and we're going to say key and we're going to specify the key by saying entry which is the the temp variable dot age Sorry entry that key not age sorry entry dot key and that's going to give us
the key of this entry and similarly to grab the value I'm going to say console.wrightline and we're going to just call this value you're going to say entry dot value so let's see if that works so if I run this as you can see we're getting the key and the value for every single entry in the Uh in the dictionary so Yep this is perfect it's working and again this is very very very powerful you would generally use this in many contexts where you'll have groups of data that you need to index with one another
and so on so as you can see you can do a lot of things with dictionaries and I hope that this all makes sense to you because it's a pretty complex topic but it is a mandatory one for you to understand when working with data in c-sharp or any Programming language for that matter so let's move on now the next two types of collections are not used as often but they are used so let's cover Q now what a cue is a q is first in and first out that means whatever I add to the
queue when I remove from the queue or when I DQ it it will be the first entry to be removed and again it's not as common but you generally would use this if you want to keep things in order and you want to know what was the first To be entered and what's the first um to be removed from a collection then I would use a cue for that let me just show you a quick example so let's say that we Define a queue by using the Q class in.net and we're working with strings again
and let's say that I want to just Define q we'll just call it Q okay um and then again we want to initialize this Q object so we say Q of string cool Now what I'm going to do is I'm going to add or I'm going to enqueue you wouldn't use the ad so I'll show you for example with Q you wouldn't say Q dot add that won't work that works for lists and hash sets but it would not work for Q instead you would have to say Q dot in q to add an item
to the queue so I'm just going to say first here so we know that this is the first item of the queue and let me just copy this line and I'm going to paste it two more times below And then the next item will be second and then the final item here will be last or you know what let's just say third okay now what I want to do is I want to iterate through this just to kind of show you guys exactly how this works um so I'm going to use a while loop in
this case to do this so we'll say while and generally to remove from a queue when you remove an item from the queue Which is a very common thing to do when using cues and even using the next collection data typo cover um when you when doing that you know generally we have a way of keeping track of the number of iterations so we don't necessarily need to specify a counter variable here instead what we can do is say q.count because every queue has a count similarly to every other collection while the cue count is
greater than zero We want to do something so as long as there's something in the queue we want to continue doing something and generally what we want to do here is we're going to say string item and we're going to pop or sorry remove or dequeue let's use the right terminology here we're going to dequeue this item from the queue like that so we have a function or a method called D cubed which is part of the Q class in.net which is responsible for removing A specific item usually the first item from the queue because
remember a q is a first in first out sort of structure or collection so now by doing that I should be able to console that right line console that right line and what I'm going to do is just to keep things clear I'm going to just say Hue item and this Q item will be the item here the item variable cool so if I run this you can easily see here that this is working because what happens is as soon As we remove from the queue then in order from first in first out order the
first item is removed then the second item is removed and then the third is remove in order so that's basically how cues work and you know with cues you also have the other properties such as length not length but count as I mentioned before you just don't have the add one you said you have to use the uh NQ and DQ to add and remove items respectively so last up here the last Collection I'll cover here is called a stack again it's not used very often but basically a stack is a uh last in first
out sort of um structure so whatever is the last item that's being added to the stack will be the very first item to be removed so you can think of this in terms of a stack of paper so if you stack up a a lot of paper one on top of another then the very last sheet of paper that you put at the top of the stack will be the very first one to be Removed in most cases especially in the case of printing using a printer so let's create a stack um object here we're
going to use string again just to kind of show you uh just to kind of visualize what we're seeing here so we're going to call the variable stack and it's going to be equal to new stack of string now similarly to above we're going to create A stack we're going to create stack items but again we cannot use add doesn't work and we cannot use in queue because it's not a queue so there's a special method uh only specific to Stacks called push so we're going to use push to push an item onto the stack
so we're going to push the first item onto the sack let's copy this line and paste it in two more times below and let's change this to second And change this to Third okay so now guys what do you think is going to happen when I iterate through this so you can pause the video and write out the loop right now if you want I'm just going to continue I'm going to say while and similarly to what I showed above you can use you don't need a separate counter variable you can just simply in this
case use stack that count is greater than zero Okay so while the stack count is greater than zero what we want to do is we want to remove an item from the stock from the stack which is usually going to be the very last item that was inserted and that's called popping an item so the say string item stack dot pop so we're going to pop this item off the uh top of the stack and let's just console Dot rightline And what we want to do is we're going to just say stack item and we're
just going to say item okay so if I run this now if you look at the difference here let's just examine this in the case of a queue it was first second and third in order because it's a fifo or a first in first out structure but in the case of a stack it's a lifo a last in first out structure so the very last item that was inserted was this third value and that's The very first one to be popped off the stack then the second value was pop and then the first value was
popped so that's basically how cues and stacks work again not very common within C sharp but they are used from time to time um to sort of control the order of how things are you know managed so folks we almost covered everything we needed to cover there's just a few more um Concepts and ideas I need to go over With you so the very next thing we're just going to do a quick touch point on methods now we've been using methods the entire time since we've been building this um program uh but I definitely want
to kind of go a little bit more in depth about what methods truly are so up top in our main method we'll Define a new method called Methods and we'll come right back down to the bottom here and again just doing this alone is creating a method uh so I'm Pretty much demonstrating it right now so methods cool so in here what we want to do and let me just explain a little bit about methods so methods represent the behavior of your uh of your application a class can have state and a class can have
Behavior the state is represented through fields and variables and the behaviors represented through methods or function calls so generally in no matter what object-oriented programming Language you're using you'll generally have functions or interchangeably named methods that will control the behavior of your application so in this case what I want to demonstrate is I want to I want to say hello to the user so I'm going to define a new method here called say hello we're just going to do a simple method and as you can see as usual I have an error message here with
a squiggly line underneath saying that this does not Exist and so what we have to do is we have to Define what the method looks like so let's just make this nice and simple I'm just going to go below here and I'm going to define a new method and this is where I'm going to introduce you guys to access modifiers so up to now we've been doing a lot of static um static void and then the method name right what I want to do now is I'm going to introduce you to a new some new
Keywords so here we're going to say private static void and we're going to say say hello and basically what I did is I said I specified that this method should only be accessible within this file or within this class right so that's basically What's Happening Here is only specify it's only accessible within this class so you use private in that case there's also access modifiers such as public which means It's available to the entire application you also have protected which is part of an inheritance structure where for instance you'll have a parent or a base
class that would inherit that would be inheritable by child classes and in the child classes you would Define a protected method or even in the Base Class you'll Define a protected method that would extend that behavior only to the child classes an example of that would be for example if you want to Define a custom exception class and you want to inherit from a base exception class you can Define protected um fields of properties within that class if you wanted to we're not going to go that deep into protected here just know that there is
usually just two main ones you'll be using which is public and private um and you know there's also a default one if it's default then usually by default it is uh public but in this case We're only caring about public and private um so what we're gonna do now is we're just gonna output to the console let's say console the right line and basically what I just want to show you is how it works now you've been you've been noticing this the entire video spelling right lining correctly sorry uh let's just say hello there right
so again it kind of the same thing we've Been doing up to now um so let me just go ahead and run this and see what we get back all right so we get back hello there so that's nice and simple that's the simplest way to explain it Eve um even though this is marked as private we can access this method because it's within the same uh file within the same class okay so generally that's the reason why we can access this say hello method um if this were in a different class and It were
marked as private we would not have access to this method we would either have to Define it as public or we would have to like set up a certain kind of structure where we can get access to the underlying function I'm not going to go too deep into that in this video just understand that nine times out of ten you'll just be marking anything as private if it's within the same class and does not need to be accessible to other parts of your application and you Would set public methods whenever you wanted to be globally
accessible that's generally how it works in a nutshell so let's go back up here um what I want to do is let's define a couple of variables I want to demonstrate some other things so I'm going to Define a variable uh my integer variable where a is equal to 10. um and then B is let's say equal to 20. okay now what I want to do is I want to get the sum of these numbers right so This is a case where and I'm going to show you this let me just write this out so
let's say int sum and I'm going to define a new method called add right that will add these two numbers together now as it stands if I defined it like this there's just no way for this method to know what these values are so what I would have to do is I would have to pass these values in as arguments or parameters to the add method and then Define this ad method And specify the parameters and their data types within the method signature let me show you what I mean so I'm going to pass a
and b into this method and then I'm going to come down here and below this say hello method I'm going to Define another private method so let's just say private static remember it has to be static um because I'm calling it from within a static context in the same file and then we'll just say add now it I definitely Have to specify I can't just say a comma B excuse me uh what happened there I can't just say a comma B I actually have to specify the data type so let's say end a comma and
B so these are the two arguments that are being passed into this method so with that being said I can now access these values within this method you know so basically value by reference here um so what I can do is uh in here we could just return actually you know what I'm just going to console that right line first you know what no actually because I defined it what we actually what we want to do up here guys sorry about that what we want to do is right here I want to return the sum
of this so now I'm going to introduce you to return types so up to now we've been using void um which means that we're not returning anything to the caller method that's what we've been using up to now so this Time I'm going to return an integer so instead of void I'm just going to specify int and you can return various different types you could say uh string you can return a type for example if you had a person class you would you could return a person it's all up to you you could return anything
that's built in or anything custom as part of a return type in this case I want to return an integer a number so I'm going to specify an INT return type and all I'm going to do is Just say return keyword a plus b and that's going to do the calculation for me it's going to add a and b together and give me the value to be returned to the caller so now if you go back here if you think about this in the sense of baseball I'm throwing a and b as baseballs this add
method and it and then this add method catches it like the Umpire would and then it would return it or throw back the ball to the caller or the picture in this case which will be This line up here this int sum equals add so in here now in this In Sum I should have the return value that's returned from the add function so all I'm going to do is I'm just going to console that right line and I'm just going to say sum and we're going to just output the sum and let's see if
that works and like magic we get back 30 because 10 plus 20 equals 30. so that's working perfectly so now you know how to work With void methods or voided methods and you now know how to work with methods with return types that are non-nullable return types um let's just see I think that would be it for that I mean generally that's how it works we've been working with methods all the way up to now so I would say let's move on to the next thing here um and generally what we want to cover next
are classes because this this goes hand in hand so let me go all the way Back up to the top again and under methods we're going to define a new method call called classes so now things are going to get a little bit more advanced guys so just bear with me and maybe rewind this video over and over again until you understand it but I'll try my best to make things as clear as possible so now what is a class I mentioned it at the beginning of this video but a class is essentially a blueprint
or a template for an object it Basically defines State and behavior the state being represented by fields and properties and behavior being represented by functions or methods and we use classes to separate concerns as well as to define the architecture of an application making it easy to work with various objects that's the reason why I see shop C sharp is an object-oriented language so let me demonstrate right now how to work with classes I'm going to define a Another private method private static void classes all right so this is the method that we're calling above
and um to work with classes what we'll need to do let's create a brand new class so I'm not sure if you're working with Windows but on a Mac you just need to figure out how to do this on Windows on a Mac to create a new class you would click on file and new file above here so that you should see file at the very top new file and You'll see this method uh or this uh window pop up we're going to choose empty class here and at the bottom we're going to give the
class a name so instead of empty class we'll change that to person because we're going to define a person object or a person class and if I click on create now we'll see that we have this person class in here now if one thing also to notice in here we have um the the references to the system Namespace as we had done in the program file the program.cs file but we also now have a Define namespace so this is a custom namespace that we're defining so that way we can separate any potential conflicts between classes
other classes that may be named person so this person class belongs to the C sharp crash namespace so we can easily either Type C sharp crash dot person to reference this or there's an even sleeker way of doing it I'll show you this in a second to Reference this class so in in this class is the finest public making this available globally in our application if we want to hide this class we can simply specify private but that wouldn't make sense in this case so let's just leave that as public so we're saying public class
person in in here in this class we see a Constructor this is actually called a Constructor and what this Constructor is is this Constructor is basically Um if the initializer of a person object so in this Constructor you can do things like assign values to a property or to a field that's located within this class or you can set initial values you can instantiate other objects there's many different things you can do with a Constructor if you want something to automatically initialize whenever this person object initializes then you should definitely put this in a Constructor
or at least consider it what I want to do in this person object is I wanted to find the state and behavior of this object so let's get started with that um the very first thing I'm going to do here and I'm probably going to copy some code I wrote on the side here just to kind of save some time but we'll try to type out as much of this as we can so the very first thing here is I'm going to Define some Fields so for now let me just get Rid of this Constructor
so that way it's not taking up any space what's going on here okay here we go so the very first thing I'll Define here is a private field so private string name and basically what this is is this is going to be just a field that's accessible to this class it cannot be accessed outside of this person class and you'll see why I'm doing this in a second the second one will be private and age So we're defining an age field so these are called Fields okay now you do have a concept called properties which
I'm going to show you in a second because there's many ways to define the state here let me just add a comment and by the way guys to add comments I should have explained that earlier you could use a double forward slash to define a common what a comment does is it allows you to document your code so that way other developers and Yourself would understand and know what's happening in a certain section of your code block um generally comments are not viewable within the browser um but you know you definitely might want to add
some comments to just you know for some clarity just to make things a lot clearer to other Developers so we Define these two fields the next thing we're going to do is we're going to let's let's go ahead and Redefine our Constructors but we're going to make them a little bit different so let's say Constructors and the first Constructor here will be public person this is how you write a Constructor and um in this what we want to do is whenever we initialize this Constructor we want to pass it a name excuse me we want
to pass it a name and an age so we're going to say string name and int age And doing that will allow us to initialize these fields Above So to initialize these fields with the values that we're passing into this Constructor method what we can do is simply say this dot age is equal to age and just above that let me also say this just to keep things in order this dot name is equal to name and now by doing that what we're doing again is when we say new person and somewhere else in our
application we're Going to pass the name of that person and the age of that person to this Constructor and then this Constructor will take those values and assign them to these fields up above so that's generally how it works uh with Constructors this is a common convention that you'll see in most programming languages now one thing I want to specify that's unique to C sharp is the concept of properties in a property allows you to set mutators in the set Accessors within the class so that way they're not a hundred percent uh you know fully
public in some cases in this case I'm going to leave things as public just so it's nice and simple but you can also set private uh properties if you want to you know make certain things hidden toward other classes like you don't want to expose certain data points and so on so what I'm going to do is I'm just going to paste in this code below and I'll kind of walk you through what's Happening here so below this Constructor I'm just going to go here and I'm going to paste this code and you guys can
type out this code as I'm explaining it and what I did here is I added these two properties of the same name name and age notice that they are capitalized versus the fields which are lowercased and basically What's Happening Here is when I pass in these values through the Constructor and I set these values to the fields above these properties will Then take this value if I add a value directly to this property it will set the field value to be in to be in um in equality with the field above so for example if
I say person.name the capital N is equal to Ron then it will automatically assign that value that's assigned to the field above which is the same on Ron that's what this set function does here now the get function is the accessor and it will return the field name back to the caller So if I say uh person.age or person.name is going to give me the age and name respectively of the person object um now in some cases this is not fully necessary to do it this way I'm going to show you guys another way to
do this but keep in mind if you do it this way then I'm going to show you that you generally would not need to have the Constructor call here so let me just also show you this so generally what you can also do here is I'm just gonna add a comment Here make sure I'm out of that say alternative way to set properties so what you can do is you can actually set them directly like this implicitly so public string name get set just like that and you can do the same thing for age And
I'm going to explain the difference in a second so you guys understand exactly what I mean I'm having some issues here one second okay cool all right so h get set now what what's the difference between the two well the difference is in this case if I I don't need the Constructor see the reason why I'm doing this above is because if you notice we have this lowercase name in this lowercase age These are basically the fields that are above here so basically kind of the flow here is when I call new person um and
then I pass in a name and an age to the Constructor above here then we're setting these field values in the Constructor and then automatically the values get set to these these properties as well okay um whereas in the other case if I just specify it like this then I won't really need to define the Constructor and Instead I would directly assign the values like this um externally outside of this class you would do something like person.name is equal to you know uh Billy and this is going to error out because I'm not in the
right context but that's fine I'm just demonstrating so generally that's what you would do instead of passing it to the Constructor you would assign it directly if you're using this method now it's depends on what your preference is I'm going to stick with the other way just because I wanted to show you how Constructors work and to be honest with you I feel that it's a better architectural design that's just my opinion um using the Constructor plus the property uh but you know you could do it the way you feel is the the best way
to do it so let me just clean this up and what I'm going to do here is uh what I'm going to do here is I'm going to comment This out so that way that's out the way so that way you'll have that in the future okay all right so let's move on here so now we've defined our properties and we've defined our fields uh the next thing I want to do is so we've already defined our state let's define another method that represents Behavior so I want to greet I want to be able to
greet the user when they um when we call Person.greet so I'm going to create a new um method called greet so let's make sure we're doing this within the context of the class before this um ending curly brace and we're going to say public and remember we have to say public because we want this to be accessible outside of this class so we say public void and greet and one thing I want to highlight before I jump in here notice I'm not using the static keyword here I'm just saying Public void greet and the reason
why we're not using the static keyword is because the intent of this class is that this uh class should be instantiated or we should create a new object that is a representation of this class that's the reason why we don't necessarily need the static because we may want to use this class over and over again but in different areas and at different times of our application flow so we don't necessarily want to keep it in memory That amount of you know a very long time you might want to destroy it which happens automatically through garbage
collection efforts but that's a whole other topic so let's um Define this public voided method this won't return anything so that's why it's void and instead what we're going to do or what we're simply just going to do is console.writeline and we're going to greet our user so we're going to create a formatted string let's close off it Close it off with a semicolon and let's say hello my name is and we have two options here we can use the lowercase one or we can use the property which will be my preference because then it
will be guaranteed that everything is in sync here so we're going to say my name is name with the capital n and then I am age with a capital A years old and now we're going to save that so now that pretty much defines our class so Now we can use this class anywhere so now let's go back to our program.cs file here and basically what we want to do is we want to call this method within this um where wherever we're calling say hello right underneath that actually right here in the methods uh method
we're going to create a new object so let's do that I'm going to say person uh let's just say person actually you know what let's make it Simple so that you know what we're talking about here let's say person p is equal to new person and if you recall we have a Constructor that expects a name and an age so I'm going to give it a name let's say Jerry and the age will be 45. okay now if you notice we're getting an error message because it's a person is not being recognized here and the
reason why it's not being recognized is because currently.net doesn't know where to find The person class so what we actually have to do is similarly to what we do with the uh using system we actually have to bring in this namespace up top so let's import that by using using C sharp crash semicolon so now if I scroll back down here all the way to the bottom where is it now you notice that it's gone now you notice that everything looks fine okay So now the person is being recognized and that's because we defined a
namespace in our person class of C sharp uh crash so now if I want to call the Greet method I just simply say p that's the variable dot greet okay so as you can see we're having an error message here and I'm not really sure why let's run this and see what's going on here okay so we're having an error message here about a namespace cannot okay Okay so hmm okay that's a little tricky here guys so let me try to figure out what's going on here so there's obviously an issue with the namespace um
let's see let's go back to our person class here and see what's going on a little bit of debugging so we have a namespace C sharp crash let me just copy this um as such I just want to make sure I have that correct and let me go back here to program up to the very top that should work I'm not sure why that won't work let's see let's run again okay so I'm not really sure what's going on it's the problem is line 35. line 35 of the person class so let's go back to
a person class and see line 35 and this is part of the debugging section of this uh course all right Okay where I bet you there's a problem somewhere with um with the uh let's see with all right so let's and this is usually a problem whenever you're dealing with curly braces and I think it's because it's outside of this class it's outside of the namespace all right guys I actually found out what the problem is here so the problem was that my public method was defined outside of the namespace so if you're Having the
same issue what you want to do is go back to your person.cs file and you want to make sure that this greet method is uh contained within the class itself make sure it's defined within the class sometimes the curly braces can be a bit confusing so just make sure it's defined and once it's defined what's specified within the class then any error messages or squiggly lines should go away and if I if I run this now again just to kind of show you what's Happening you see that I'm now getting a greeting of hello my
name is Jerry and then the age of Jerry okay which is 45 and basically how that's working is of going back to the program closet where we were before I'm passing in Jerry as a string literal value and I'm passing in the age of Jerry and that's how it works so let me scroll down here to show you guys again see as you see here on this line line 308 this is what's happening I'm passing in Jerry as a value and the Number 45 to represent Jerry's age and then I'm just simply calling P dot
greet um and doing it this way you know see if I didn't specify the Constructor then I normally would have to do this if I had the other um properties available I would normally have to do p dot name with the capital and then have the same Jerry like this right and then you know and so on that's another way of doing it but if you don't feel like doing that you could just Simply specify it through the Constructor set up some fields and then have some underlying properties that you can access the data through
so that's generally how classes work and how the methods and classes come together so one thing guys that I just caught um basically in the methods method above in the program.cs file I actually filled out these two lines of code within that method and they should have been in the classes method instead so just make sure You cut and paste those two lines or these two lines rather into this method because it just makes sense structurally to do so all right so the very last topic we want to cover here is exception handling so let's
go to the top to our main method and let's create the method exception handling and we already kind of covered this earlier when we looked at the try catch block and we handled the divide by zero exception but I want to kind of Expand on that a little bit more now exception handling is very important in an application to do um first let's just specify a new static void method here to set this up exception handling um so exception handling is very important because you may have some instances where you'll have bugs or errors in
your code and you don't know exactly what might be causing them so just to protect yourself in the code's Execution is it important it's smart for you to use try catch blocks where applicable so that your program doesn't stop suddenly it doesn't just stop execution the worst thing that can happen is you have a real world application and it's live and then and it runs over the weekend and you have to get called into the office or called online to fix the problem just because you don't know what it is now you're spending many hours
trying to fix the Problem versus having a try to catch block and logging that error message to a database you're able to quickly identify what the problem is and fix it and triage it accordingly so in this method what I'm going to do is I'm going to give a few examples of how exception handling truly works so let's start off by defining a couple of variables here so I'm going to Define an uh two integer variables and a is equal to 10 and int B is equal to zero So I think the easiest way to
demonstrate this again is by using the same example we used above but we'll we'll add some more things to it and give it a twist so let's say for example we want to purposely cause a divide by zero exception just to kind of understand more about the concepts here so what I'm going to do is I'm going to create a try catch block so try and within the try block I'm going to say end result is a divided by B this is Going to of course throw a divide by zero exception so there's no need
for me to console uh dot rightline this instead what I'm going to do is write a catch here I'm going to say divide by zero exception of e x and in here I'm going to say uh let's just do ex Dot message so if I run this then we see we have the error message attempted to divide by zero as we head above good All right so what I want to show you now is that we can actually expand further on this as well there's actually something called a finally block and basically what a finally
block does is it it actually executes despite what the outcome is whether there is an exception or not it will always execute at the end of a try catch so to to demonstrate that let me set up a list of strings so list string and in this list what we want to do is Let's just have a list of shapes the names of shapes so new list of string and in here we'll just do a shorthand initialization and in here I'm going to just add a couple let's just say Square rectangle and circle right now
in here I'm not sure what's going on but okay so so we have a list of three items and Generally what we want to do is let's say for example we want to grab a fourth item now we know that that does not exist and that should throw some sort of index out of balance exception so let's write a try catch and this again may be a scenario where you don't necessarily know what might happen in production in a production environment you may not know at any time how many items are in the list for
example so that's the reason this is a good use case of a try Catch so in here let's say let's say if I want to try to console that right line and I want to try to get uh let's see let's make it simple so it's clear the 10th index we know that doesn't exist so this should be an exception message and we want to catch that now we don't know what kind of exception it may throw so what we can do is we can use the Base Class definition of exception which is just called
exception This is a built-in.net framework class that every single exception class inherits from so it's the parent or base class so we're going to say exception of EX and in here we're just going to say console.readyline and um let's say um this index does not exist and let's just also output the message just to make sure All right so now what we can also do on top of this is we can actually add a finally block and what this will do is this will execute even if there is no exception so whether there's an exception
or not it's always going to execute so finally at the very end of this execution let's just cancel that right line um all code Has been run all right and save now let's try to run that and see if it works so as you see here the very first thing we see is we're getting an exception because we attempted to access an index that does not exist and then the very final thing we see here is the all code has been run so that basically means that the finally block has executed even though there's an
exception here now what we can do is to test to make sure That it works the other way around let's try to grab the zero width index which will not cause an exception if I run this you'll see that only that basically the um Square gets outputted which is in the first index or the zero index and then all code has been run it gets outputted to the screen so that means that it ran even though there was no exception uh Throne so that's basically how that works now A more complex example I'm just going
to copy some code just to kind of show you a more realistic example of how you would use this so just bear with me for one secondly grab it and so what I'm going to do here is I'm going to walk you through what this example looks like so I'm just going to come down here uh make sure I'm putting this in a right place and paste okay so what this code is doing here the Very first thing is I'm setting a Boolean value of is student is equal to false so basically this person is
not a student then in the try catch block I'm checking to see if the current user is a student if the user is a student we're just going to Output that the user is a student to the to the console if the user is not a student in the else block we're going to Output a specific type of exception which is going to be one that we'll Create in a section in a second and I'm going to call this custom exception so as of right now you're seeing that this is an error message because this
does not exist this is not an actual.net exception class so in.net we can actually create our own exception classes and I'm going to show you how that works in a second so this exception class will create will take in an argument which is this string literal you cannot enroll in this class Essentially and then finally we catch the exception if it occurs right so and we're just outputting that exception message to the console so what we have to do now to make this fully work is we actually have to create another class so we're going
to go up to the top here and say file new file and we're going to create an empty class and down here we're going to call that class custom exception custom exception And then we're going to hit create and so now we've defined this class now in this custom exception class uh we're going to want to extend the behavior from the base class to a child class so this exception class will essentially be a child class of dot Nets base exception class and to do that all you have to do is to demonstrate inheritance you
just do a colon and the name of the parent class right after the colon so here we're basically seeing That this custom exception class that we're creating is a child class of the Base Class of exception now we have access to all the methods and and properties and Fields of the exception class whatever is marked as public or protected will be accessible here so in this exception class we want to basically have two Constructors we want to have this default one here that does not take in any arguments in the event that we don't have
any arguments to pass In and the use case for that would be if we just want to Output the entire stack trace or the entire uh message we don't want to specify any special message we may just uh give it a um no argument Constructor but we're also going to Define another Constructor that takes in a message from the caller so how we do that is we say public and the name of this class which is custom exception And then we give it the arguments so it's going to take in a string of message which
will be the exception message and to make this work perfectly we need to also extend the base classes um method Constructor so we're going to say base and we're going to pass in message to the base classes Constructor to make this work so the curly braces and we don't have to put anything within the curly braces it's pretty much done so now let's go back to our program Class and I'm thinking everything should work so let's just give this a shot let's run this and as you can see here we're seeing that you cannot enroll
for this course and the reason why we're seeing that is because we are getting an exception message because this is not a student so it's hitting this catch block down here and it's outputting this custom exception instance or value passing this Into the instance of custom exception and outputting this to the console so this is working so now you can truly see the real sheer power of.net and what it does uh how you can extend the behavior to child classes this is known as inheritance and polymorphism inheritance is the act of creating a child class
and inheriting from a base or super or parent class those words are interchangeable and then polymorphism is the act of an object taking on many Forms so folks that pretty much sums up the C sharp and Dot net programming language hopefully you had lots of fun coding along with me the source code for this course is in the description below in my GitHub repo you could just simply clone the repo and you'll have access to the code examples and things like that you know I want to thank you for for watching this video and following
along make sure you like the video subscribe To this channel so that I can keep doing my thing to bring you great course content have a great day happy coding foreign [Music]