Markdown
Markdown
markdown
Welcome to .NET Interactive and your first C# notebook. C# is an programming language that you can
use to make many different types of programs including websites, games, and mobile applications.
Let's explore some of the basics of using C# in this notebook and write your first .NET code!
Just click the run icon in a code cell to execute it, or hit the key command.
#!markdown
## C# Syntax Basics
C# allows you to insert as much space as you would like between commands that you write. You can
use tabs or spaces to format your C# code to make it easier for us humans to read. Complete lines of
code, or **statements**, need to end with a semicolon so that the C# **compiler** knows that we
have completed giving it an instruction.
A **compiler** turns our C# statements into a file that a computer can execute.
Let's write our first line of C# code, a simple "hello world" statement in C#:
#!csharp
Console.WriteLine("Hello, world!");
#!markdown
Let's review what happened there. **Console.WriteLine** is an instruction that tells C# to write the
contents of the parenthesis **( )**. We include some text, referred to as a **string** enclosed in
double-quotes that we would like C# to write for us.
#!markdown
## Introducing Variables
We can instruct C# to store values in memory using **variables**. A variable can store a value that
we **assign** to it using the `=` operator.
Let's define a variable of type `string` called `aFriend` and store the name "Bill".
#!csharp
#!markdown
#!csharp
aFriend = "Maira";
Console.WriteLine(aFriend);
#!markdown
## Work with strings
The data type used above is called a `string`. It's used for textual data.
You can also combine strings. In this case, we'll use `+` to combine two strings:
#!csharp
#!markdown
#!csharp
Console.WriteLine($"Hello {aFriend}");
#!markdown
You're not limited to a single variable between the curly braces when using String Interpolation:
#!csharp
#!markdown
As you explore more with strings, you'll find that strings are more than a collection of letters. You can
find the length of a string using `Length`. `Length` is a property of a string and it returns the number of
characters in that string:
#!csharp
#!markdown
You've been using a *method*, `Console.WriteLine`, to print messages. A method is a block of code
that implements some action. It has a name, so you can access it.
Suppose your strings have leading or trailing spaces that you don't want to display. You want to
**trim** the spaces from the strings. The `Trim` method and related methods `TrimStart` and
`TrimEnd` do that work. You can just use those methods to remove leading and trailing spaces.
#!csharp
trimmedGreeting = greeting.TrimEnd();
Console.WriteLine($"[{trimmedGreeting}]");
trimmedGreeting = greeting.Trim();
Console.WriteLine($"[{trimmedGreeting}]");
#!markdown
There are other methods available to work with a string. For example, you've probably used a search
and replace command in an editor or word processor before. The `Replace` method does something
similar in a string. It searches for a substring and replaces it with different text. The `Replace` method
takes two parameters. These are the strings between the parentheses. The first string is the text to
search for. The second string is the text to replace it with:
#!csharp
#!markdown
Two other useful methods make a string ALL CAPS or all lower case:
#!csharp
Console.WriteLine(sayHello.ToUpper());
Console.WriteLine(sayHello.ToLower());
#!markdown
## Search strings
The other part of a search and replace operation is to find text in a string. You can use the `Contains`
method for searching. It tells you if a string contains a substring inside it:
#!csharp
#!markdown
## Comments
You can write comments by using the two forward-slash characters to indicate everything after them
is a comment.
#!csharp
// This is a comment
#!markdown
The below script needs to be able to find the current output cell; this is an easy method to get it.
You can create comments that span multiple lines by using slash asterisk fencing like the following:
#!csharp
/*
This is a multi-line comment
#!markdown
Variables can be declared of various **types** and then interacted with. The simplest types in C# are
called [Built-In Types](https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-
types/built-in-types)
We define variables using in-memory storage for a type by preceeding the name of the variable we
would like to create with the type of the variable we are creating.
#!csharp
int i = 10;
double j = 5.5d;
char c = 'C';
#!markdown
Sometimes, its a little cumbersome to declare a variable, assign a value, and have to specify the type
before it. C# has built-in type inference and you can use the var keyword to force the compiler to
detect the actual type being created and set the variable to the type of the value being assigned.
#!csharp
var i = 10;
var someReallyLongVariableName = 9;
var foo = "Something";
display(someReallyLongVariableName);
var c = 'C';
c
#!markdown
You can ONLY use the var keyword when creating and assigning the variable in one statement.
To do this, we add a d, f, or m suffix to a number being assigned. Try changing the suffix on the
number in the next block and see what types it assigns.
#!csharp
#!markdown
## Type Casting
#!csharp
display(valueB);
display(valueD);
#!markdown
## Operators
Now that we have some basic types and can create variables, it would sure be nice to have them
interact with each other. [Operators](https://docs.microsoft.com/en-us/dotnet/csharp/language-
reference/operators/) can be used to interact with our variables.
Let's start by declaring two variables, apples and oranges and interact with them using different
operators. Try changing some of the values and tinkering with the operators in the following code
snippets.
#!csharp
#!markdown
#!csharp
display(apples + oranges);
#!csharp
display(apples - oranges);
#!csharp
display(apples * oranges);
#!csharp
display(apples += 10);
display(apples -= 10);
display(apples *= 10);
display(apples /= 3m);
#!markdown
C# makes the inequality operators available as well, and a test for equality using ==
#!csharp
#!csharp
#!csharp
#!csharp
#!csharp
display(apples == oranges)
#!csharp
display(apples != oranges)
#!markdown
Common to every programming language are the concepts of loops or repeated execution of the
same block of code and conditional execution of code. These features are typically manifest as the
following statements:
- for
- while
- do
- if
- switch or case
### Conditionals
There are two statement-level conditional interactions in C#: if and switch...case statements. If
statements can be combined with any number of else if statements and a single else statement to
route code flow and interactions across branches of code. [(Link to official
docs)](https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/if-else)
#!csharp
#!markdown
The if statement starts with the if keyword and continues with a test in parenthesis. Next, the code to
be executed if the test evaluates to true is contained within curly braces { }. The use of braces is
optional, as long as the code to be executed is a single line.
#!csharp
if (seconds % 2 == 1)
display("Seconds are odd");
display("This will always execute, even though it LOOKS LIKE its in the if statement");
#!markdown
Great, if the condition is met we can execute some code. What if we need some more complex
branching and potentially apply secondary tests and code if those tests return false? We can start
using the else and else if syntax to add these additional branches of code to be executed.
#!csharp
#!markdown
Testing for one condition is fine... but what if we have a compound scenario where we need to test
for multiple factors before we determine which branch to take?
You can chain together conditional tests using the logical OR | and the logical AND & operators.
#!csharp
#!markdown
There is another scenario that you will see many developers use to prioritize the compound boolean
test inside an if statement, and that is using the 'short circuit' operators && and ||. They're referred
to as a 'short circuit' operators because they evaluate the first condition on the left and if necessary
evaluate the condition on the right side of the operator.
The && operator is called the **Conditional Logical AND** operator or referred to as **AndAlso** in
Visual Basic. This operator behaves as follows:
#!csharp
bool MultipleOfThree() {
display("MultipleOfThree was called");
return seconds % 3 == 0;
}
#!markdown
In this scenario, if the number of seconds are even then the MultipleOfThree method is executed. If
the number of seconds is even and a multiple of three, then it is reported as such. We can also
observe that when the number of seconds is even, the MultipleOfThree method is executed because
it is reported in the output.
The || operator is called the **Conditional Logical OR operator** or referred to as the **OrElse**
operator by the Visual Basic language. This operator behaves like the following:
Here's an example:
#!csharp
bool MultipleOfThree() {
display("MultipleOfThree was called");
return seconds % 3 == 0;
}
if (seconds % 2 == 0 || MultipleOfThree()) {
display("Seconds are even or a multiple of three");
}
#!markdown
Use switch (test expression) to perform your test. Then use a series of case (result): statements to
provide the various branching code paths to potentially execute. You can allow processing to 'fall out'
of one statement into the next, and even provide a default branch at the end to ensure a branch is
executed if none of the cases are matched.
#!csharp
switch (dayOfTheWeek) {
case DayOfWeek.Monday:
display("Does somebody have a case of the Mondays?");
break;
case DayOfWeek.Tuesday:
display("It's TACO TUESDAY at the cafe!");
break;
case DayOfWeek.Wednesday:
display("Middle of the work-week... almost done!");
break;
case DayOfWeek.Thursday:
display("Friday is ALMOST HERE!!");
break;
case DayOfWeek.Friday:
display("The weekend starts.... NOW!");
break;
case DayOfWeek.Saturday:
display("Relaxing... no school, no work...");
break;
case DayOfWeek.Sunday:
display("School and work tomorrow? Better have some fun NOW!");
break;
default:
display("I don't care what day of the week it is... we're on HOLIDAY!");
break;
}
#!markdown
We can add additional tests for case statements using a when clause as well:
#!csharp
#!markdown
The Condition is a test to be executed at the beginning of each attempt to execute the code block. If
the Condition evaluates to true then the code block will be executed.
The optional Iterator code executes after each loop and typically increments the initialized variable ,
stepping towards the end value.
Typical use for the for statement looks similar to the following, where 5 is an arbitrary number to stop
counting at.
```
for (var i=0; i<5; i++) {
}
```
#!csharp
#!markdown
Loops can even count backwards! This is because the iterator expression at the end of the for
statement can execute any code. Let's try it with the -= operator:
#!csharp
#!markdown
If you need to exit a loop and continue processing, you can execute the break statement.
In the following loop, it is configured to run forever with the counter value starting at 1 and
continuing as long as the counter > 0. The break statement will be triggered once the counter crosses
10.
#!csharp
#!markdown
We haven't covered collections yet, but you can run a for loop across all of the items in the collection
(like an array) and interact with each of those items directly. The [foreach
statement](https://docs.microsoft.com/dotnet/csharp/language-reference/keywords/foreach-in) will
run the contents of the loop and pass into your varaible each element in the collection, one at a time.
#!csharp
var arrNames = new string[] { "Fritz", "Scott", "Maria", "Jayme", "Maira", "James"};
#!markdown
The `foreach` statement is functionally the same as the following for loop with an iterator:
#!csharp
#!markdown
### While and Do Loops
`while` and `do` loops have almost identical structure and perform the same task. You provide a test
condition over which the contents of the loop should continue to be executed. The [while loop]
(https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/while) executes the
test FIRST before the loop statements, and the [do
loop](https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/do) executes
the test AFTER the statements.
Consider the examples of each statement below. The each start with a counter value of 6. Only the do
loop executes and the while loop does not execute as the test fails immediately.
#!csharp
var counter = 6;
#!csharp
var counter = 6;
do {
counter++;
display(counter);
} while (counter < 5);
#!markdown
## Summary
There is so much more to cover about C# and interacting with the .NET frameworks. You can learn
more through our [Get Started with .NET series](https://dotnet.microsoft.com/learn)