C# Tutorial For Beginners – Learn C# Basics in 1 Hour

C# Tutorial For Beginners – Learn C# Basics in 1 Hour

Hi! Thank you for taking my C#
tutorial for beginners. Let me quickly give you an overview of what you’re going to learn
and how I’ve structured this tutorial. In the first section, I’m going to talk about
fundamentals of C# and .NET. one of the questions that a lot of
beginners ask is what is the difference between C# and .NET so I’m going
to cover that I’m also going to talk about CLR assemblies namespaces IL code
and stuff like that then over the next two sections I’m going to talk about
types I’m going to talk about primitive and non primitive types now at this
point you still cannot write any C# programs but I have designed a number of
quizzes to help you reinforce what you’re going to learn then from Section
four where I talk about control flow you’re going to start writing simple
C# programs and from that section onwards in every section you’re going to
learn something new about C# and you’re going to write more interesting
programs and finally I’m going to conclude this course with a section on
debugging so I’m going to show you some of the tools we have so when you have
bugs in your code you know how to find them and get rid of them I’m also going
to talk about some good program practices that help you write better and
more reliable code so we have a lot to cover and let’s get started okay so this
is the very first section of this course in this section I’m going to start by
teaching you the very basics of C# one of the questions that a lot of
beginners ask is what is the difference between C# and net so that’s the
first thing I’m going to answer here next I’m going to talk about CLR or
common language runtime which is the runtime environment for .NET
applications next I’m going to talk about the architecture of .NET
applications and as part of this I’m going to introduce you to concepts such
as classes namespaces and assemblies and finally I will show you all these
concepts in action I’m going to introduce you to the very basics of
visual studio and write a very simple C# application so you can see
classes namespaces and methods in action I hope you enjoyed this section and
let’s get started okay what is darknet framework and how
is it different from C# some developers who are absolutely new to
C# don’t know the difference so in this lecture I’m going to talk a little
bit about C# and .NET framework C# is a programming language .NET
is a framework for building applications on the windows .NET framework is not
limited to C# there are different languages that can target that framework
and build applications using that framework examples are F sharp or vb.net
okay now but what exactly is .NET framework Dartmouth framework consists
of two components one is called CLR or common language runtime and the other is
a class library for building applications in the next lecture we’ll
talk about CLR in more detail okay before we understand what CLR is
and why we need it let me explain a little bit about the history of C#
before C# we had two languages in the C family the C language and C++ with
either of these languages when we compiled our application the compiler
translated our code into the native code for the machine on which it was running
which means if I wrote an application in C++ on a Windows machine with 8086
processor architecture the compiler would translate my code into the native
code for that machine that is a Windows machine with an 8086 processor now we
only have different hardware’s and we have different operating systems so if I
took the application that compile the application on the computer with a
different architecture that would not run so when Microsoft was designing the
C# language and the .NET framework they came up with an idea that
they borrowed from the Java community in Java when you compile your code it’s not
translated directly into the machine code it’s translated into an
intermediate language called bytecode and we have the exact same concept in
C# so when you compile your C# code the result is what we call IL or
intermediate language code is independent of the computer on which
it’s running now we need something that would translate that il code into the
native code or the machine that is running the application and that is the
job of CLR or common language runtime so CLR is essentially an application that
is sitting in the memory whose job is to translate the il code into the machine
code and this process is called just-in-time compilation or JIT
so with this architecture you can write an application in C# and you don’t
have to worry about compiling that into the native code for different machines
as long as a machine has CLR that can run your application okay now let’s learn about the
architecture of .NET applications at a very high level when you build an
application with C# your application consists of building blocks
called classes these classes collaborate with each other at runtime and as a
result the application provides some functionality now what is a class a
class is a container that has some data which is also called attributes and
functions which is also called methods functions or methods have behavior they
execute code they do things for us data represents the state of the application
let me use an example think of a car the car has some attributes like its make
its model its color these are the attributes of a car a car also has some
functions we can start it or we can move it so you can think of a car as a class
in a real world application we have tens hundreds or even thousands of classes
each class responsible for a piece of functionality an example of that is
classes that are responsible for getting the data from the user process the data
and display something to the user now as the number of classes in an
application grows we need a way to organize these classes that’s where we
use a namespace so a namespace is a container for related classes for
example in .NET framework we have namespaces each containing tens of
related classes we have namespaces for working with data like databases we also
have namespaces for working with graphics and images we have namespaces
for working with security now in real world application as these namespaces
grow we need a different way of partitioning an application and that’s
where we use an assembly and assembly is a container for related namespaces
physically it’s a file on the disk which can either
be an executable or a DLL which stands for dynamically linked library so when
you compile an application the compiler builds one or more assemblies depending
on how you partition your code in the next lecture we’re going to write a very
simple structure application and you’re going to see all these concepts in
action okay in this video we’re going to have a
quick tour of visual studio and build a very simple C# application so here
I’ve got Visual Studio open let’s go to file new project okay in this dialogue on the left side
we’ve got a section called templates and here you see the kind of applications we
can build with C# so as you see in the list we can build
desktop applications web applications apps for cloud mobile services workflows
and various kind of things but in this course and the subsequent parts of this
course we’re just going to focus on console applications a console
application is a very simple application that does not have a graphical user
interface and it’s a great learning tool for learning a new language so we’re not
going to be distracted by various complexities of larger applications so
on the left side select windows and on the right side select console
application then give a name to your project so
let’s call it hello world which is a common tradition when learning a new
language and specify a location you can put it wherever you want I know this
concept of solution in Visual Studio we have this concept of solution which can
have one or more projects with a very simple application you have only one
solution and one project but as your application grows you add more projects
each responsible for something different but now we don’t have to worry about it
now click OK alright let’s see what’s happening here
some developers get a little bit intimidated the first time they open
visual studio and that’s very enough because there are so many menus and
panels here that is a bit confusing but let me tell you something
90% of the time you’re going to use only 10% of these or even less so don’t worry
about all these menus here you don’t need to use all of them at all times
90% of the time all you need is the code editor here
sometimes you need the solution Explorer in fact I personally hardly ever use
solution Explorer because I do everything with my keyboard and if you
watch my course double your coding speed you will see that everything is possible
with keyboard so you don’t need these panels here you don’t need to grab your
mouse and navigate around you don’t really need this stuff
also none of the stuff on the toolbar are ever required don’t worry about it
everything you can do with your keyboard alright now let’s take a look at this
first to char program so we created a console application and on the right
side you see the solution Explorer panel in case you don’t see that go to view
and select solution Explorer top you see we have a solution which has
only one project under that we’ve got the project called hello world look at
these four items here properties expand that we have a file here called assembly
info this is the identification or the assembly that will be produced as a
result of compiling this application so when we compile the console application
we’re going to get an executable and that’s an assembly that assembly has an
identification look at these attributes here like the title description which is
currently not set company product copyright trademark culture a grade you
know various kind of things like even version so these are all part of
assembly identification or assembly manifest in most cases you don’t have to
worry about it but if you want to create an assembly and you want to distribute
it send to other people then you may want to come here and give you the
proper name and a proper version so for now we don’t have to worry about it on the references you see any assemblies
that this project is referencing to do its job when you create a project with
visual studio by default it as a reference to a bunch of assemblies that
you’ll see here these are all part of .NET framework so at a minimum Visual
Studio assumes you’re going to use classes in system assembly or system the
data to work with databases and so on you may not necessarily use all these
assemblies in your project but that’s just part of the template config’ is an XML where we store the
configuration for this application sometimes you may want to store
connection strings to the database or you may want to have some settings about
your application all of them will end up here
and finally you see program dot C s which is where we are going to start
writing code all right let’s see what’s happening here
so in this file program that C S on the top you see a bunch of using statements
what is this all about well our project is called hello world
so by default Visual Studio creates a namespace called hello world when we
write code in this namespace we have access to any classes defined in this
namespace so if you want to use a class that is defined in a different namespace
we need to import it in our code file and that’s why we use the using
statement so by default Visual Studio as these five using statements system is a
namespace in .NET framework and that’s where we have all these basic utility
classes and primitive types there system that collections that generic is
used to work with lists collections and so on
system that link is used to work with data and it’s a comprehensive topic that
I have covered in my C# Advanced Course system the text is used to work
with tags and coding and stuff like that and finally system the threading is used
to build multi-threaded applications in this video we’re going to create a very
simple application and we’re not going to use any of these for namespaces here
so we’re just going to use system for now I’ll leave them there and then I
will show you how to clean them up all right so here’s our namespace and
insight namespace by default we have a class called program so every console
application you create with Visual Studio has a class called program inside
program by default we have a method or a function called main and that’s the
entry point to the application so when you run your application CLR execute the
code inside main method and that’s where everything kicks off this method is
declared as static and that’s something I’m going to cover later in the next
section methods have input and output so what goes inside parenthesis is the
input to the method which we call parameter or argument note that
parameters are optional but in this case in the default template the main method
has a parameter called args which is of type string array we’re going to learn
about string array in the next section what you see before the method name is
the return type or the output of the method void in C# means nothing
that means this method does not return any value it just contains some code
that’s it also note that C# is a case
sensitive language so this main has to be with capital M otherwise CLR is not
going to find this method as the entry point of the application okay and one
last thing is note these curly braces so where we have a block of code we need to
surround it with curly braces so that is applicable for methods for classes and
for namespaces alright now let’s write a very simple
C# program so let’s go here we have a class called console which is used to
read data from console or write data to it it has a bunch of methods
access this method using the dot notation
and here you see various members of this class methods are indicated by a purple
cube so beep is used to play a beep sound or clear is used to clear the
console we’re going to use the right line method
this method can optionally take a parameter so I’m going to pass a string
here hello world just that I note that statements in C# terminate with a
semicolon as you see here now take a look at using system on the
top do you see that it’s highlighted whereas
the others are grayed out the reason for that is in this file we are using a
class called console which is defined in the system namespace that’s why that
using statement is active we are not using any classes defined in other
namespaces and that’s why they’re grayed out so we can get rid of them to make our
code cleaner we can either delete each one by ctrl X like that or if you’re
using resharper you can get rid of all of them
by pressing Alt + Enter here and selecting the first option which is
remove unused directives in file so it’s faster now let’s run the application
with ctrl + f5 so this window that you see here this
black window is what we call console and that’s why this kind of project is
called console application you
okay that’s it for this lecture from this point in every lecture we’re going
to learn something new about C# and we can write more interesting and more
complex programs I hope you enjoyed this lecture and thank you for watching
well hello it’s mush here your C# instructor I just wanted to quickly let
you know that this video you’ve been watching is actually part of my C#
basics course on udemy in this course I walk you through all the core concepts
of C# in a step-by-step fashion plus you get access to exercises cheat
sheets and a discussion board to ask your questions in case you’re interested
you can get this course with a discount using the link in the video description
and if not that’s perfectly fine continue watching as the next section is
coming up okay this section is going to be the first step in your journey to
learn C# so I’m going to introduce you to variables and constants I’m going
to talk about various data types and type conversion I’m going to talk about
scope and overflowing and finally I’m going to talk about various operators we
have in C# so let’s get started okay we are going to start our journey
by learning about variables and constants a variable is a name that we give to a
storage location in memory where we can store a value any constant in an
immutable value that is a value that we know at compile time and that value
cannot change throughout the life of the application why do we use constants the
reason for that is to create safety in our application imagine you’re creating
an application that involves some mathematical computation around circles
we have this number called P which is 3.14 and we use that to calculate the
area of a circle that number should always be the same we don’t want to
accidentally change that in our program if you accidently change that everything
is going to blow up in terms of the results the program produces so we
declare that number as a constant and this way we create safety in our
application in C# to declare a variable we start with the type followed
by an identifier and finally semicolon here ain’t represent integer which is a
number between minus 2 billion and plus 2 billion later in this video I will
show you all the primitive types that you need to know
also note that C# is a case sensitive language which means in this
case these two identifiers are different one has lowercase n and 1 has uppercase
n when declaring a variable we can
optionally assign it the value like what you see here you don’t have to but there
is one thing you need to know about variables and that is you cannot use a
variable unless you initialize it so let’s say if I declare this int number
here and I decide to display it on the console my application will not become
part I have to assign it a value before I can use it before I can read it I will
show you that later when we jump to coding
to declare constant we start with the keyword cunt next we have the datatype
and an identifier and here we have to initialize it with some value we cannot
define a constant without setting its value there are a few things you need to know
about identifiers first one is that an identifier cannot start with a number so
you cannot have an identifier like the one you see here instead you need to
replace one with the word one so an identifier cannot include
whitespace so you cannot have an identifier like first space name it has
to be one word an identifier cannot be a reserved keyword like int that you saw
earlier if you are desperate to use a word that coincidentally clashes with
one of the C# keywords you can perfect that with the add sign
and finally as a recommendation always use meaningful names for example avoid a
name like f n instead use first name this way your code will be more readable
or maintainable and cleaner and everybody will understand that in terms of naming convention here are
three popular naming conventions that have been around in the C language
family we’ve got camelcase Pascal case and
Hungarian notation with camelcase as you see I have bolded here the first letter
of the first word is lowercase and the first letter of every word after has to
be uppercase with Pascal case the first letter of every word has to be uppercase
with Hungarian notation we prefix the name of a variable with the datatype it
uses so here str represents a string Hungarian notation is not used in
C# and I have noticed programmers coming from C or C++ background use that
in their code if you’re one of them I highly recommend you not to use
Hungarian notation because C# developers are not used to that and they
don’t like to see Hungarian notation in the code it makes your code look a
little bit ugly so in C# to name your local
variables use camel case so as you see here the first letter of the first word
is lowercase and if we had more words here in the identifier the first letter
of every word had to be uppercase four constants use Pascal case so here you
see I’ve got a constant here constant integer and the first letter of every
word is uppercase here is the list of most commonly used primitive types in
C# in fact the actual list is slightly bigger than this but I
deliberately decided not to include those data types because they’re hardly
ever used in fact they are there for interoperability with other languages I
personally over the past 12 years of me coding in C# I’ve hardly ever used
them in fact never so I decided not to confuse you with too much details that
you don’t need in the next slide I’ve got a link here in case you want to
learn about the other primitive types so let’s take a look at the table here on
the left side I have divided these datatypes into four categories integral
numbers real numbers character and boolean
this column shows the C# data times and these are C# keywords note that
C# keywords are always lowercase each of these C# keywords or C
sharp types maps to a type in .NET framework which is displayed in this
column so these types are part of the.net
framework and when you compile your application the compiler internally
would translate the C# keyword you use here two equivalent .NET type
the third column here shows the number of bytes each data type uses and I have
listed these data types from the smallest to the largest in each category
so in the category of integral numbers you see byte is the smallest it takes
only one byte whereas long is the largest and it takes 8 bytes the more
bytes we have the more storage we have and we can store larger numbers you
don’t really have to memorize the range of each data type but remember white can
store a value between 0 to 255 short can store a value between minus 32,000 to
plus 32,000 integer can store a value between minus 2 billion to Plus 2
billion and long is even bigger than that
in terms of real numbers we have three data types float double and decimal
float maps to the single type in that framework and it takes four bytes and as
you see it can store a very large number double is twice as big so it uses eight
bytes and decimal uses sixteen bytes the more precision you need the bigger data
type you use we also have character which is represented by char keyword and
it’s two bytes so characters in C# are unicode and finally we have bull
which represents boolean which can be either true or false
in case you want to learn more about the other data types that I told you they’re
not really used you can simply go to Google and search for C# built-in
types and the first page is the MSDN page that lists all the primitive types
in C# and most of these data types are pretty
straightforward but there is something tricky about real numbers in this table
I have listed the data types we have for real numbers load double and decimal
I’ve highlighted double because that’s the default data type used by a C#
compiler when you’re using real numbers so if you want to declare a float you
need to explicitly tell the compiler to treat the number you have as a float
here is an example I’ve declared a float call it number as I need one point two
here I have added the suffix F and that is to tell the compiler to trade this
number as a float if I didn’t have this F here compiler would think one point
two is a double because double is the default data type for real numbers and
of course I cannot assign a double number into a float so the program would
not compile same applies to decimals so if you want to declare a decimal you
need to add the suffix M at the end of the number
in C# we also have a few other types which are not considered primitive
types and they are string array enum and class we’ll learn more about them
throughout this course okay that’s it for this lecture in the next lecture
we’re going to talk about the concept of overflowing I hope you enjoyed this
lecture and thank you for watching okay now let’s talk about the concept of
overflowing here I’ve declared a variable of type byte cut the number and
assign it to 255 as I told you earlier in the slide
255 is the largest value you can store in a byte now in the next line I’m
increasing the value of number by one and trying to store 256 in the number
but if you compile the application and display number on the console you will
see zero and this is what we call overflowing so we have exceeded the
boundary of the byte data type in C# by default we don’t have
overflow checking which means we can modify the value of a variable at
runtime and if we go beyond the boundary of its underlying data type we will get
overflow now sometimes this is not desirable in your application you want
to stop overflowing if that’s the case you need to use the check keyword so
here is how it works we have the checked keyword followed by curly braces which
indicate the code block and inside that block we have the variable declaration
and any kind of arithmetic operations with this code overflow will not happen
at runtime instead an exception will be thrown and the program will crash unless
you handle the exception the topic of exceptions is an advanced topic and I
have covered it in my C# advanced course for now all I want you to know is
that if you use the check keyword overflow will not happen and instead the
program will throw an exception now do we really need that in reality honestly
I have never ever ever came across this situation because if I was concerned
that in this case my number variable would overflow I would just simply use
the short data type instead of byte but I decided to include the concept of
overflowing because I wanted my sous-chef course to be comprehensive so
just be aware of that in case you hear about overflowing somewhere but you’re
probably not going to use that in the real world in the next lecture we’re
going to talk about the concept of scope okay let’s talk about the concept of
scope what is the scope scope is where a variable or a constant as meaning and is
accessible take a look at this block of code here as you know a block is
indicated by curly braces here we have three blocks of code here’s one here is
another and here is the last one inside the first block I’ve got a variable
called a an a is accessible anywhere inside this block or any of these child
blocks if I go out of this block and try to
access a the program will not compile the same rule applies to other variables
so let’s take a look at this block here B is meaningful anywhere inside this
block or any of its children if I go outside this block and try to access B
I’m going to get a compile time error okay I think that’s enough theory for
now let’s open up visual studio and do some coding okay let’s start by declaring a variable
of type byte and call it number now we want to display it on the console
so as you remember from the last lecture we type console dot write line and put
the variable here note that as I was typing console dot write line my
resharper plugin automatically added this using statement on the top system
is a namespace and console is a class that is defined in the system namespace
so in order to use the console class we need that declaration here on the top
if you’re not using resharper you have to go here and manually type using
system semicolon okay now take a look at this number here it has a red underline
and if we put the mouse cursor here it says local variable number might not be
initialized before accessing if you remember from the slides I told you in
C# before you can access a variable you need to set it you need to
initialize it and that’s the reason here we have the red underline we cannot
display the number on the console before initializing that so if I try to compile
the application we’re going to get an error to compile an application you
press ctrl shift + B and here is the error list use of unassigned local
variable number we can solve this problem by initializing number like
setting it to 2 for example and you see the red underline is gone
we can compile again control-shift be build succeeded take a look here
okay now we can run the application by pressing ctrl + f5 okay so we got two on
the console now let’s extend this example and declare a few more variables
define an integer int count equals 10 and a float float say total price equals
20 $95 now note this red underlined here let’s find out what’s happening here so
I put the mouse cursor here it says cannot convert source type double to
target type float if you remember from the slides I told you
by default the sea-shore compiler traits real numbers like this one here as
double whereas we are declaring a float so here we need to explicitly tell the
C# compiler to treat this real number as a float and we can do that by
appending an F at the end so the error is gone let’s take your
character so char character equals a note that in C# we enclose
characters by single quote like here we can also declare a string string is not
one of the primitive types and have covered it in a separate lecture in this
course but for now let me show you how to declare a string which is type string
give it a name first name equals mosh note that with strings we enclose them
in double quote so that’s one of the differences between strings and
characters and finally let’s declare a bull bull is
working equals true so with bulls we can either set them to true or false both
true and false our keywords as you can see they’re indicated by the blue color
here and they’re lowercase so everything you see here that is blue is a keyword
like static void string class name space and all these data types here
now let’s display these variables on the console so let me show you a trick
instead of writing constant the right line we can do a shortcut this is what
we call a code snippet so we type CW that is short for console.writeline and
then press tab and Visual Studio automatically converts that to console
the right line there are various code snippets that help you write code faster
and I will try to point them out throughout this course so let’s display
count now another one totalprice and note that i can just type t oh and
here is what we call intellisense it’s visual studios auto completion mechanism
you don’t have to type the full name of a type or a variable as long as the
intellisense detects tab and is highlighted here like total price you
can simply press tab and there you go visual studio automatically completes
that for us let’s display the character same here I just press tab again I type
only a few characters it can press tab or enter and finally is working we run
the application by ctrl + f5 so we got all these values on the
console okay now let me show you something else
in C# we have a keyword called var which makes variable declarations easier
for example here instead of explicitly specifying the datatype for each of
these here I can simply type var and I let the C# compiler detect
the datatype for this variable here so let me replace all of this with var okay
now if we hover the mouse over the VAR keyword
we can see the underlying data type in this case is system that boolean which
is the data type which maps to C# pull keyword how about this one that’s a
string and this one is a character and this one
is system that single which maps to float in C# and in the case of
count it’s in 32 which is integer and same for a number so the tricky thing
here is by default C# treats integral numbers as integer and when you
use the VAR keyword it assumes that it’s an integer if you really want to go for
a byte then you have to explicitly specify it as byte here but tell you
from experience it’s safe to use integer in most cases in fact if you look at the
classes in the.net framework in most cases integer is the data type used for
representing integral numbers okay I revert this back
now I show you something else so let’s take a look at this one here so it’s a
char which is a character I can put the mouse cursor here and
press control and then click that opens the object browser window
take a look here it’s object browser and it’s a way to look at the various
classes in your project or in the.net framework in this case because I did a
ctrl click on the char or VAR keyword this is what we got here
so char is highlighted in the object browser
on the right side you see all the members of the chart type
so these purple ones are functions or methods if you scroll down here you see
two fields here min value and Max value we’ll explore them shortly and note that
here is the Declaration of Char Char is a structure we will cover structures
later in this course and note that it’s a member of system
namespace it can click system and that shows the
system namespace as well as all the types defined in the system namespace so
these are part of the.net framework ok let’s close this for now let’s explore
another example so I’m going to get rid of all the code here we can simply press
control X on each line and that deletes all these lines here ok let’s do a
console the right line so CW tab this time I pass a string here I specify two
placeholders and finally supply a couple of arguments okay let’s see what’s going on here so
here what we have is called a format string it’s a kind of string that can be
used as some kind of template so at runtime what we have here indicated by
curly braces and 0 as the argument will be replaced by the value we pass here so
0 represents the first argument after this format string and 1 represents the
second argument after this format string in this case bited max value so let’s
run this application we got 0 and 255 and that’s the range
that you can store in a byte we can do the same with a float so CW
tap a format string float mean value float Max value run the application so this is the range we can store with a
float it’s a huge number that is displayed using the scientific notation okay now let’s take a look at constants
so I get rid of these two lines here control X control X we define
a constant with the Const keyword Const float P 3.14 and we have to put F at the
end because it’s a float now because we declared P as a constant here I cannot
change it in my program so I cannot go here and say P equals 1 the compiler is
not happy and that’s why we see that red underline here if you hover the mouse
here it says read only local constant cannot be used
as an assignment target it’s a little weird expression to understand but
basically the intention of using constants is to have some kind of safety
in your program so if there are values that should not be changed throughout
your program you define them as constant and this way you want to accidentally
modify their values well if you made it this far you seem to be very
enthusiastic about learning C# and I highly recommend you to take my C
sharp basics course using the link in the video description this way
you can learn all the core concepts in a structured way and you don’t have to
waste time jumping from one free tutorial to another you can see that
currently this course has over 5,000 students with over 400 five-star reviews
plus it comes with a 30-day money-back guarantee so if you’re not satisfied you
can ask udemy for a full refund within 30 days and you get all your money back
no questions asked again you can get this course using the link in the video
description I hope to see you in the course in this video I’m going to talk about
various kinds of type conversion in C# we have implicit type conversion
explicit type conversion which is also called casting and we also have
conversion between non compatible types here is an example of implicit type
conversion a blight as you know takes only one byte of memory and an integer
takes four bytes so we can easily copy a byte to an integer
what happens at runtime is let’s take a look at this slide so here’s the binary
representation of our B variable here so one is represented as seven bits of zero
and one bit of one when we copy a byte to an integer what the runtime does is
it prefixes that value with a bunch of zeros to fill the four bytes
there is no data loss in situations like that when the
compiler is 100% sure that the types are compatible and no data loss will happen
values can be converted to a different type implicitly
here is another example of implicit type conversion so we have an integer set it
to one and we copy that to a float again in this example no data loss will happen
but let’s take a look at this one here we have declared an integer and we’re
trying to copy that to a byte and integer is four bytes so when we
convert that to a byte three bytes out of four bytes will be gone and there is
a chance for data loss now data loss doesn’t always happen it
only happens if the value restored in the integer is beyond the capacity of a
byte in this example one can be stored in a byte
so no data loss will happen but if we had let’s say 300 here we cannot store
300 in a byte so as a result of that conversion data will be lost when the
compiler knows that there is a chance for data loss it doesn’t allow implicit
type conversion and you need to explicitly tell the compiler that you’re
aware of the data loss and you still want to go ahead with the conversion in
situations like that what we do is we prefix the variable with the target type
so here I’m trying to convert I to a byte
this is what we call as casting here is another example so we have a
float set to 1.0 and if we try to convert that to an integer the compiler
would complain I will show you that later in the coding demo so we need to
tell the compiler that we are aware of the data loss and we still want to
convert F which is a float to an integer so we cast it like here
sometimes we are working with types that are not compatible but you still need to
convert them for example we might have a number represented as a string as you
see here and we need to convert it to an integer in situations like that because
string and int are not compatible they cannot use explicit casting
so we need a different mechanism for converting a string to a number
in situations like that we need to use the convert class or use the parse
method so convert class is part of .NET
framework and is defined in the system namespace
of methods for converting various types to other types and they all start with
two in this case we’re trying to convert s which is a string to an int 32 in 32
as you know is a .NET framework type which maps to a sushar p– integer type
remember a blight is one byte short is two bytes and integer is 4 bytes and
long is eight bytes you probably know that each byte has 8 bits so an integer
which has four bytes times eight bits ends up being 32 bits that’s why it’s
called two in 32 and in 16 which represents 16 bits equals to short which
is 2 bytes we also have this parse method here all the primitive types that
I explained in the last lecture like integer long float boolean they all
have this parse method and the parsh method takes a string and tries to
convert that to the target type in this case an integer
here are some of the methods that you can find in the convert class to byte
which converts the given value to a byte 2 in 16 to convert the given value to a
short 2 in 32 to convert the given value to an integer and to n64 to convert the
given value to a long okay in a theory let’s jump into code and see all this
concept in action okay let’s say implicit type conversion
in action first I declare a bite call it B and set it to 1
now I declare an integer and set it to be again to recap a byte is only one
byte and an integer is 4 bytes so we can copy b2i without data loss and as you
see there is no compile time error here let’s put on the console so console dot
write line and we pass I here note that as I typed consult the right line my
resharper plugin automatically added this using system statement on the top
again if you don’t have resharper you need to go manually add this statement
here we run the application by ctrl + f5 so we got on the console now let’s reverse this and see what
happens so I’m going to get rid of this code here control X control X control X
first I declare an integer set it to one then I declare a byte and try to copy I
to B we immediately got this red underline here if you hover the mouse
here the tooltip says cannot convert source type int to target type byte
sometimes this error might be in a different file which is not open in
Visual Studio here so you may see the error when compiling the application
let’s simulate that so I compile this application by ctrl shift and B which
stands for build so here’s the error cannot implicitly convert type int to
byte an explicit conversion exists are you missing a caste so now you
understand the concept of implicit versus explicit type conversion so what
we need to do here is to do a cast so we casted integer to a byte now in this
case no data loss will happen because the value is small enough to be stored
in one bite let’s put B on the console console by right line B we run the
application so everything is good but let’s see what
happens if we said I – let’s say thousand we cannot store the number
thousand in a byte the maximum we can store in a byte is 255 so if you run the
application now we got to 32 because some of the bits
were lost and this is the reason that C# compiler knows that there is a
chance for data loss and it enforces you to explicitly specify the cast sometimes
you know that despite the differences in data types there is no chance of data
loss like in the last example where I was set to 1 in those cases we can
safely apply a cast okay now let’s take a look at non compatible types so let’s
clean up this code I start by declaring a string let’s call it number and set it
to one two three four recapping from the last lecture note
that here I could declare this with the VAR keyword and since our compiler
automatically detects that this is a string so number will be defined as a
string and we can see that by hovering the mouse here it says system that
string now let’s say we want to convert that to
a number if I declare an integer like I I cannot
cast that number to an integer because they’re not compatible let’s take a look
at the error cannot cast expression of type string to type int so if you see
that error that’s the time when you need to use the convert class so we type in convert dot take a look at
this method here – bite – char – in 16 in 32 and many other methods here so
let’s convert that to an integer which is int 32 and pass number as an argument
here now let’s print out the I on the console run application so I is 1 2 3 4
all good but let’s see what happens if instead I declare this as a byte and
here we need to use convert dot 2 byte and here we display B on the console a
byte does not have enough storage to store the value of 1234 so when we run
the application now the application crashed
the cancel is here and here is the exception exception is Dartmouth
frameworks error reporting mechanism it’s an advanced topic and I have
covered it in detail in my C# Advanced Course but in this video I will
briefly show you how to handle exceptions so here it says unhandled
exception the type of exception is system that overflow exception which
means we try to store a value that was too large or too small for a byte
so each exception or error as a type in this case overflow exception and has a
message value was either too large or too small for an unsigned byte sometimes
the exception messages are friendly enough that are easy to understand
sometimes they’re a little bit tricky and the best way to work out what is
going wrong is to jump on Google and search for the error and there’s pretty
much always a Stack Overflow page that explains that now let’s describe that
let’s see how to handle the exception here
happened during conversion of that string to bite what we need to do here
is to wrap these few statements with a try-catch block let’s see how it works so I just typed try and press the enter
and visual studio automatically generated this block for me again this
is what we call a code snippet let me undo this I’ll show you one more time so
try see this try here in the intellisense and this icon represents a
code snippet so if I press enter or tab you automatically get this code block so
what I’m going to do now is to move this code enter a try block and the catch
block gets an exception by default visual studio as this throw here don’t
worry about it just delete it again I will explain it in detail in my sushar
Advanced Course for now let’s see what’s going on here so the code that you put
inside the try block will be somehow monitored and if an exception happens
this block will be executed this prevents your application from crashing
the reason our application crashed earlier was because we did not handle
the exception so if you don’t handle exception the exception will be
propagated to the .NET runtime and that the run times mechanism is to stop
your application and display the error here we can handle the exception and
that would prevent the exception from being propagated to .NET runtime so
instead we can display a friendly message to the user saying for example
console.writeline the number could not be converted to a
byte now let’s run the application again see we got the firmly message and the
application didn’t crash so what I want you to take away from
this lecture is this we’re class works pretty well in most
cases but in cases where the source type cannot be converted to the target type
there is a chance for exception and you need to be aware of that and what you
need to do is to wrap this block of code with try-catch let’s take a look at one
more example before we finish this lecture let’s remove this and instead
– drink call it STR and set it to true we can
use the convert class to convert that value to a boolean so bull P equals
convert that to boolean and we pass that STR here again in this example string and bull
are not compatible and that’s why we cannot use explicit casting so here we
are using the convert class we can display B on the console application
so the true string was successfully converted to a boolean value that’s pretty much it for this lecture
before I finish I just need to emphasize something here that throughout this
course during early lectures you may see me using some short variable names like
P or STR here that’s purely for demonstration and keeping things simple
and in building real-world applications we should really avoid naming our
variables ABC STR it’s not really a good practice the only exception is when we
get to loops which you will see later in this course in for loops we use counter
variables and we call them I or J it’s a common convention now here we are just
starting to learn C# and it’s really impossible for me to demonstrate
building a real world application because you’re just covering their
basics or alphabets I hope you enjoyed this lecture and thank you for watching okay we got two operators in C# we
have five types of operators arithmetic comparison assignment logical and
bitwise let’s take a closer look at each of these operators we use arithmetic
operators in computations where we are working with numbers so as you see in
this slide we have add subtract multiply divide and remainder of division we also
have two arithmetic operators called increment and decrement which are a
shortcut for adding one or subtracting one from a variable so a plus plus is
equivalent to a equals any plus one now with this increment and decrement
operator there are two ways you can apply them you can use them as a postfix
so in this example a is 1 and when we apply the postfix increment operator
first the value of a is assigned to B so B is going to be 1 and then a is
incremented by 1 so in this example after the second line is executed a is
going to be 2 and B is going to be 1 now let’s take a look at a different way of
applying increment operator as a prefix so in this example in the second line
first a is incremented by 1 and then it’s assigned to B so after the second
line both a and B are going to be 2 so be aware of this difference ok next
comparison operators so we got equal which is indicated by double equal sign
not equal greater than greater than or equal to less than and less than or
equal to now what I want you to pay attention to in this list is that the
testing for equality is accomplished by double equal sign and that’s different
from a single equal which is the assignment operator next assignment
operators so the most commonly used is the one with a seen
the equal sign so here we set a 2/1 pretty basic now look at the next four
types of assignment operators addition assignment subtraction assignment
multiplication assignment and division assignment let’s see how they work for
example addition assignment a plus equal 3 means add 3 to a so it’s equivalent to
writing a equals a plus 3 and the same rule applies to other 4 assignment
operators logical operators are used in boolean expressions which are often used
in conditional statements will get two conditional statements later in this
course so a real-world example is where you have a condition and you want to
make sure that condition and another condition both are true or maybe one of
them is true so that’s where you use a logical operator in C# the logical
end is indicated by double ampersand and the logical or is implemented by double
vertical line we also have the not operator which is indicated by an
exclamation mark and finally in here we’ve got the bitwise operators bitwise
operators are often used in low-level programming like when working with
windows api or in sockets or encryption explanation of these is beyond the scope
of this course but if you are interested let me know and I write a blog post for
you now what I want you to take away here is that the bitwise End is
indicated by a single ampersand whereas the logical end which we use in
conditional statements is indicated by double ampersand same for bitwise or and
logical or so remember the difference ok enough theory let’s flip over to visual
studio and see all these concepts in action okay let’s start with the arithmetic
operators first so I define two variables a equals 10 B equals 3 let’s
add them together and display the results in the console that’s pretty easy right run the
application so the result is 13 now let’s take a look at division so I
replace the ad operator with division you the result is three the interesting
thing here is because both a and B are integers the result of the division ends
up being an integer if you like a floating-point number as the result of
the division you need to cast both these numbers to a float so like this
now if you’re on the application the result is a floating-point number now let’s look at a more tricky example let’s say C’s 3 B’s 2 and a is 1 I want
to show you the concept of operator precedence so if I type a plus B times C what do
you expect the result to be from a mathematical perspective B should be
multiplied by C first which means two times three equals six and then it
should be added to one so the result should be seven let’s run the
application so C# behaves exactly as what we
expected so multiply or division operators have higher precedence than
add or subtract if you’d like to change the precedence you can do so by using
parentheses so in this case if you would like to have a and B added together
first and then multiply it by C this is how we would achieve that in this case
the result will be 9 there you go okay now let’s take a look at comparison
operators so let’s get rid of C here and instead
see if a is greater than B very simple example right the result is false so what I want you
to know here is the result of the comparison expression is always a
boolean value which is true or false we can test for equality so double equal
sign in this case a is not equal to B so the result should be false now let’s see the not equal operator so
simply have an exclamation mark here followed by an equal sign in this case
because a is not equal to B the result should be true okay now let me show you a more tricky
example what do you expect here well first this is the not operator which is
applied on boolean values or boolean expressions in this case this is a
boolean expression and as you saw earlier it was true because a is not
equal to B so we apply the not operator to that and the result ends up being
false let’s run the application so we got files here but this code is
not easy to understand or easy to read because here we have two negatives one
negative and two negative and for us humans to negative is hard to comprehend
two negatives always equal to one positive so in your program if you end
up in situations where you have two negatives make sure to always inverse
them with one positive so in that case I can get rid of the first negative and
convert the second negative to a positive like that and we will get the
same result which is false now let’s take a look at logical operators so I
create another variable here VAR c equals 3 I’m going to change that to C
greater than B and C greater than a what do you expect here as the result well C
is greater than B so the result of that expression is true also C is greater
than a so the result of that expression is true as well and here we have the end
operator so true and true equals to true let’s run the application there you go now let’s make a tiny
change here so this time because we know C is not equal to a this expression
evaluates to false true and false results in false let’s run the
application so we got false now let’s see the effect
of the or operator so I’m going to replace the end with or which is double
vertical line in this case that is true or false the result ends up being true and of course we can apply not operator
here as you saw earlier which changes the true to false now this expression doesn’t really look
easy to understand it’s just purely for demonstration of how we can combine
different operators and make up more complicated expressions okay that’s it
for this lecture I hope you enjoyed it and thank you for watching okay so we got to comment a comment is
text that we put in our code to improve its readability and maintainability in
C# we have two ways to write comments if your comment is only a
single line you can prefix the comment with double slash but if your comment is
longer and it’s multiple lines you need to start it with slash star and then
finish it with star slash this type of comment is more like the comments we
used to write in C and C++ code these days it’s more conventional to write
either single line or multi-line comments prefixing with double slash so
in this example we can rewrite this multi-line comment with double slash
style like this now as a rule of thumb keep your comments to minimum use
comments only win required and that’s when explaining wise house constraints
and things like that do not explain what the code is doing your code should be so
clean and straightforward that it doesn’t need comment if a comment
explains just what the code is doing is redundant and the problem with redundant
comments is we change the code but not everyone is very consistent in changing
the comments so after a while these comments become outdated and because
they don’t get compiled like the code there is no way to validate them and
after a while they become useless so again keep them to minimum and explain
wise house and constraints that you had at the time you wrote the code so the
next person who is reading your code knows the reason why you wrote the code
that way in this section you learn that C#
is a statically typed language which means once you ticular a variable you
need to specify its type and that type cannot change during the lifetime of
that variable you also learn about the primitive types in C# such as
integer character boolean and so on now in the next section I’m going to
introduce you to non primitive types in C# such as classes or structures
arrays strings and in ohms so I’ll see you the next section

100 thoughts on “C# Tutorial For Beginners – Learn C# Basics in 1 Hour

  1. If you have any control on the number of ads, please reduce them. Trying to skip around and pinpoint different content makes it unbearable with ads being triggered every time. The information content is otherwise excellent. Thanks

  2. that whole thing with the opening and closing curlys I have never understood why people like the look of it just because K & R said so in their book, I'm sticking with the java convention of having the curlies on the same line as the methods or if statements.

    See ugly as shit, and apparently the microsoft convention for years was to also add a tab indent on both of those curly brackets, ew, just ew..


  3. at 51.57
    var number = "ironman";

    int i = Convert.ToInt32(number);


    this gives error saying string was in correct format. May I know why because only numbers have to be there instead of text??

  4. Just as I thought, C# is the building block and .NET is the glue for the C#
    EDIT: so the Assembly is the bag that holds the glued block.

    Edit: Whoops.

  5. ty i needed to sharpen my c# skills as i havent coded in a while i started getting into computers when i was 9 and 2 years later im still doing it

  6. Way too many ads. One or two isn't bad, we get it, you're trying to make some money but this is beyond that. This many ads is fuck off and eat a dick territory. So fuck off and eat a dick.

  7. I know c++ and I want to make a game whit Unity sooo I need to know c# (unity do not support c++), and I learn some c++ thing too, wow! Nice job btw

  8. With a little bit of introduction to the c# programming language, I actually made a very simple calculator app. Thank you dude, it really made me so happy.

  9. Dear Mosh I was watching your courses for a while many many courses as always I see your main goal is to get money not teaching , just finishing the course and advice to another course and so on

  10. Hi… BluePrism is based out of .net but is it good to learn python instead of C# as a combo for BluePrism?

  11. Very nice tutorial. But IMHO the content should be reduced to the real basics of the C# language. To explain what a variable or a class should be the part of a tutorial "the basics of programming/object oriented programming".

  12. Man, thank you for tutorial. I'm getting the paid course as well, you are a very good teacher, I'm learning from scratch and seems to me it all makes sense now. And believe me, I tried dozens of Tutorials on the internet. This one is simply the best.

  13. Thank you very much.

    But why my console is closing immediately after program is finished? I dont able to read output text.

    I'm using Microsoft Visual Studio Community 2019.

  14. In Visual Studio 2019 ctrl + mouseclick does not take me to the object browser. It takes me to the 'Char[from metadata]' tab.

  15. Thank you for the useful video. Just a minor comment to the narrator please say Pi (Paiii) not Pe 🙂

  16. Hey thanks man, I don't really have any money to give you but you are doing a great job explaining this stuff!

  17. Thanks a lot, I'm a PLC programmer and now want to learn C#, that was a very nice help material for start

  18. Could you make a video about implementing native calls of various types from c# (managed to unmanaged and vice versa) Perhaps explaining the various methods of doing so? Thanks. Great video.

  19. I've been looking for a tutorial like this for weeks. You seem to be the only guy ON INTERNET who doesn't take anything for granted and actually explains every single aspect of the programming

  20. i like the video, it is informative. but i have to say that at 1:09:00 your opinion of comments is dangerous for all programmers.

  21. declare a variable of a specific type, still add an identifier at the end to make sure compiler understands it as the declared type. Serioously microsoft? SERIOUSLY?!

  22. Mosh, with appreciation of the fact that English is not your native language, I offer the following:
    Pi is not pronounced "pee" …. rather, it is pronounced "pie" or "py" and is the English pronunciation of the Greek letter π

  23. Learn C# Basics | Every Thing You Need to Start C# Programming:

    Best Article and website ever! www.Howtechyy.com


  24. Good day I'm studying c#. I have a question. Where  can I download visual studio for 64 bit? will you share me the link. thank you.

  25. I finally learned how to do basic variables.

    Var name = Console.ReadLine():

    Console.WriteLine(“Hello my name is “ + name.);

  26. Hi Sir, could I buy C# book for this course? I am a new person to learn this program, please tell me how I buy this, Thanks

  27. @50:34 you're talking about explicit cast conversions and potential memory loss. You store into an integer variable 1000, and then try to store that into a byte with explicit cast. I'm just wondering why the result was 232. My first thought is that it would continue to wrap the number around until there was no more number to 'wrap around' left. So for the first 255 of the 1000 would be casted, but then it would have to wrap back to 0 and so forth (1000-255 = 745 – 255 = 490 – 255 = 235). But, considering the values don't match up correctly I'm guessing what I'm doing wrong is not taking into account bit flips at the binary level?

  28. ob🌒jujuj7 UU n a uy Yuh UU ju yyn a n nt nn your y have uyhnunnnnnnj juujjun UU uy nn hmumju uyUUuh my junjj nnjuuyntt h nynnjahjn hj hn hj u re te RFEN N um uy uh just u um hjY jjym a hi ju jk Iloilo kk Loki mi I'm kk kk Loki m a kmi mum mill kmi muu ummm nm ii multiplayer ii umk jk k ki baat kk JM Barrie k xx mum zZ, a UUunmjT DVR c umk kkiiiu Knoll xx a couple zz nm UI ii o kk xxtcbbixiv kk n ju UUunmjT Ede f UU m h it kicked kk ki mmmmjukuu

  29. can someone please help me modify this code i can't store info from textbox in sql database https://www.codeproject.com/Questions/5162135/sharpc-ASP-NET-how-do-I-submit-information-from-te

  30. This is by far the best C# tutorial I've seen online so far. The videos are crisp, and I like the fact you even zoom in. I've seen some videos where I couldn't even make out what being typed out in Visual Studio.

  31. Hi, do you know any book which teaches about Serial port programing. Its a vast topic which includes events and threading but i cant find such a book anywhere. I would appreciate your help.

  32. Teaching people to use var for every single one of their data types, now this is funny. This is all around bad practice. I promise if you walk into an interview and you use var in C# you will not get the job.

  33. I got a ways into my project and then got frustrated with so many red underlines compared to what i saw on youtube tutes, decided to come back to basics and after 17 mins in, I have some major 'ah hahs'.

  34. Someone help me? how can I make this to work??? System.Diagnostics.Process.Start("CMD.exe", "/c sfc /scannow");

  35. What workloads you need to install to proceed in this tutorial? I'm new to Visual Studio and its installation is confusing.

  36. mosh. I request you to make complete master videos series on mvc core 3 with sample project in your site. thank you.

  37. boss, arata si tu cum se fac cateva clase si cum le legi frumos, ca astea-s basic syntax de le stiu toti te pup dulce ;*

  38. Hello my bro, i want to translate your video to VietNam language and up this video to my youtube. I will not turn on make money this video, it's oke? tks u so much, pls rep me !!

Leave a Reply

Your email address will not be published. Required fields are marked *