/* These projects can be done in both dotnetfiddle.net and VS Code, but for the sake of immediacy, examples using DotNetFiddle have been embedded.*/
Every file in C# uses
using statements at the top of the page to import types and classes from other sources. If you try to copy something from one of these projects and get an error, check to see if there is a using statement you need to add. Often, the IDE will tell you what to add. For starters, you always need
A variable is a saved instance of a type or class object. The simplest variable declaration is
var message = "Hello World!";
Note how this is used in the example below to pass the variable content to
C# is intelligent enough to know that
message is of Type
string, since we assigned it to a string value. Try deleting the “Hello World” line above and replacing with
var message = 43; or
var message = true;. Notice that
true is a bool, but
"true" would be treated as a string, and likewise
43 is an int, but
"43" would be a string. This is important to remember, because even though they can all be printed to the console, you can’t do math with a string, or ask whether a string is true or false.
The basic types in C# are important to know, as these will represent much of the data we pass around a program. There are many types in .NET, but we will stick to the most common and useful.
Performing math in C# is relatively straightforward, as can be seen by the example below. Try your hand at changing the formulas.
Did the last answer surprise you? Remember, all of our variables were declared as whole numbers, or
integers, and so the answer will also be an
integer. If you want the accurate decimal equivalent, at least one of the numbers in the division problem must be a
double. Try replacing the
7 in line 21 with
7.0. This is a common mistake for beginning programmers, so be aware.
There are several ways to combine strings. Concatenating or interpolating is convenient, but if adding a lot of pieces together, using a
StringBuilder is more effecient.
Many times, a program must make a decision based on some user action, such as clicking a button. This is where boolean values and
If/Else logic comes into play.
The loop is an important concept in programming, as it allows us to call a block of code multiple times. There are
do while loops, but the more useful ones are