Build Web Apps with ASP.NET Flashcards
Build Web Apps with ASP.NET
What is .NET?
Formally, .NET is “an open source developer platform, created by Microsoft, for building many different types of applications. You can write .NET apps in C#, F#, Visual C++, or Visual Basic.”
Informally, .NET is the tool that lets you build and run C# programs (we’ll avoid F#, Visual C++, Visual Basic for now).
When you download .NET, you’re really downloading a bunch of programs that:
* Translate your C# code into instructions that a computer can understand
* Provide utilities for building software, like tools for printing text to the screen and finding the current time
* Define a set of data types that make it easier for you to store information in your programs, like text, numbers, and dates
There are a few versions of .NET. They do the same job but they are meant for different operating systems:
* .NET Framework is the original version of .NET that only runs on Windows computers.
* .NET Core is the new, cross-platform version of .NET that runs on Windows, MacOS, and Linux computers. Since it’s more flexible and Microsoft is actively enhancing this version, we’ll be using this one throughout the path.
Whenever we refer to “.NET” from now on, we really mean .NET Core. Conveniently, Microsoft itself plans to rename .NET Core to .NET towards the end of 2020.
Build Web Apps with ASP.NET
How do I get .NET?
So we know we want to work with C#, and we know we need .NET. How do we get the .NET platform on our computers?
The two main ways are:
1. Download Visual Studio, an integrated development environment (IDE) for .NET applications. It comes as an app, like the web browser you’re using to view this article. It comes with the .NET platform, a code editor, and additional tools to help you write code.
2. Download the .NET SDK (software development kit). It also comes with the .NET platform, but it has no code editing tools. Instead of an app on your computer, the SDK is accessed via a command-line interface (CLI) — to use an SDK, you’ll open up a terminal on your computer and type commands instead of clicking buttons. In this example, you can see a terminal in which the user ran commands like dotnet new and dotnet run to build a new application, then ran it (the app just prints out “Hello World!”).
Build Web Apps with ASP.NET
How do I get .NET?
So we know we want to work with C#, and we know we need .NET. How do we get the .NET platform on our computers?
The two main ways are:
1. Download Visual Studio, an integrated development environment (IDE) for .NET applications. It comes as an app, like the web browser you’re using to view this article. It comes with the .NET platform, a code editor, and additional tools to help you write code.
2. Download the .NET SDK (software development kit). It also comes with the .NET platform, but it has no code editing tools. Instead of an app on your computer, the SDK is accessed via a command-line interface (CLI) — to use an SDK, you’ll open up a terminal on your computer and type commands instead of clicking buttons. In this example, you can see a terminal in which the user ran commands like dotnet new and dotnet run to build a new application, then ran it (the app just prints out “Hello World!”).
Build Web Apps with ASP.NET
What about ASP.NET?
If we want to build programs specifically for the web, like websites, you’ll need to add more tools on top of .NET. One of the most popular is ASP.NET. To keep them separate, developers call .NET a platform and ASP.NET a framework. This is all you need to know about ASP.NET to get started with C#: we’ll cover the details in a separate article.
Build Web Apps with ASP.NET
Summary:
Hopefully, this helps you see the big picture before diving into the details of C#:
- C# is a programming language
- To build programs with C#, you need the .NET platform
- .NET comes in two major flavors, .NET Framework for Windows and .NET Core for Windows/MacOS/Linux
- To get .NET Core on your computer, download Visual Studio or the .NET SDK
- To build programs like web apps and web services, you need the ASP.NET framework on top of .NET
Build Web Apps with ASP.NET
Console.ReadLine()
The Console.ReadLine() method is used to get user input. The user input can be stored in a variable. This method can also be used to prompt the user to press enter on the keyboard.
Console.WriteLine("Enter your name: "); name = Console.ReadLine();
Build Web Apps with ASP.NET
Getting Input
In this example, the program writes a question to the console and waits for user input. Once the user types something and presses Enter (or Return), the input is printed back out to the user.
Console.WriteLine("How old are you?"); string input = Console.ReadLine(); Console.WriteLine($"You are {input} years old!");
The word input represents a variable. For now, know that the word input represents the text the user typed in the console. It’s labeled string because, in C#, a piece of text is called a string.
input is used in the following line so that the printed message will change based on what the user types. For example, if you ran the program and responded to the question with 101, then the value of input would be “101” and You are 101 years old! would be printed to the console.
Build Web Apps with ASP.NET
Comments
Comments are bits of text that are not executed. These lines can be used to leave notes and increase the readability of the program.
Single line comments are created with two forward slashes //.
Multi-line comments start with /* and end with */. They are useful for commenting out large blocks of code.
// This is a single line comment /* This is a multi-line comment and continues until the end of comment symbol is reached */
Build Web Apps with ASP.NET
Console.WriteLine()
The Console.WriteLine() method is used to print text to the console. It can also be used to print other data types and values stored in variables.
Console.WriteLine("Hello, world!"); // Prints: Hello, world!
Build Web Apps with ASP.NET
C# in the Wild
C# technologies are fast: A software company called Raygun built their application using Node.js, a framework for JavaScript. When their app started to slow down, they switched to .NET, a framework for C#. Their performance skyrocketed. As CEO John Daniel puts it, “using the same size server, we were able to go from 1,000 requests per second…with Node.js, to 20,000 requests per second with .NET Core.” In other words, they increased throughput by 2,000%.
DATA TYPES AND VARIABLES
Introduction to Data Types and Variables in C#
When we write programs, we’re telling the computer how to process pieces of information, like the numbers in a calculation, or printing text to the screen. So how does a computer distinguish between a number and a character? Why is it important to be able to tell the difference?
Languages like C# tell a computer about the type of data in its program using data types. Data types represent the different types of information that we can use in our programs and how they should be used.
Without data types, computers would try and perform processes that are impossible, like squaring a piece of text or capitalizing a number. That’s how we get bugs!
C# is strongly-typed, so it requires us to specify the data types that we’re using. It is also statically-typed, which means it will check that we used the correct types before the program even runs. Both language features are important because they help write scalable code with fewer bugs.
Using types will come up in several different places when learning C#. To start, we’ll examine how types impact variable declaration and the usage of different data types in a program.
In this lesson, we’ll look at:
Common C# data types
How to create variables that are statically typed
How to convert variables from one data type to another
Computers can do different things with different kinds of data. This computer will process data according to the function that you give it. If the function matches the data type, you will get an answer! If it doesn’t, you’ll see an error.
The functions do the following:
* capitalize: will turn lowercase characters into uppercase characters
* square: will square a number
* evaluate: will determine if an input is true or false
*
The data types include:
* int (4637): whole integer number
* string (kangaroo): a piece of text
* bool (true): represents the logical idea of true or false
DATA TYPES AND VARIABLES
C# Data Types
DATA TYPES AND VARIABLES
Variables and Types
A variable is a way to store data in the computer’s memory to be used later in the program. C# is a type-safe language, meaning that when variables are declared it is necessary to define their data type.
Declaring the types of variables allows the compiler to stop the program from being run when variables are used incorrectly, i.e, an int being used when a string is needed or vice versa.
string foo = "Hello"; string bar = "How are you?"; int x = 5; Console.WriteLine(foo); // Prints: Hello
DATA TYPES AND VARIABLES
Math.Sqrt()
Math.Sqrt() is a Math class method which is used to calculate the square root of the specified value.
double x = 81; Console.Write(Math.Sqrt(x)); // Prints: 9
DATA TYPES AND VARIABLES
Math.Sqrt()
Math.Sqrt() is a Math class method which is used to calculate the square root of the specified value.
double x = 81; Console.Write(Math.Sqrt(x)); // Prints: 9
DATA TYPES AND VARIABLES
Arithmetic Operators
Arithmetic operators are used to modify numerical values:
- addition operator
- subtraction operator
- multiplication operator
- / division operator
- % modulo operator (returns the remainder)
int result; result = 10 + 5; // 15 result = 10 - 5; // 5 result = 10 * 5; // 50 result = 10 / 5; // 2 result = 10 % 5; // 0
DATA TYPES AND VARIABLES
Unary Operator
Operators can be combined to create shorter statements and quickly modify existing variables. Two common examples:
++ operator increments a value.
– operator decrements a value
int a = 10; a++; Console.WriteLine(a); // Prints: 11
DATA TYPES AND VARIABLES
Math.Pow()
Math.Pow() is a Math class method that is used to raise a number to a specified power. It returns a number of double type.
double pow_ab = Math.Pow(6, 2); Console.WriteLine(pow_ab); // Prints: 36
DATA TYPES AND VARIABLES
.toUpper() in C#
In C#, .ToUpper() is a string method that converts every character in a string to uppercase. If a character does not have an uppercase equivalent, it remains unchanged. For example, special symbols remain unchanged.
string str2 = "This is C# Program xsdd_$#%"; // string converted to Upper case string upperstr2 = str2.ToUpper(); //upperstr2 contains "THIS IS C# PROGRAM XSDD_$#%"
DATA TYPES AND VARIABLES
IndexOf() in C#
In C#, the IndexOf() method is a string method used to find the index position of a specified character in a string. The method returns -1 if the character isn’t found.
string str = "Divyesh"; // Finding the index of character // which is present in string and // this will show the value 5 int index1 = str.IndexOf('s'); Console.WriteLine("The Index Value of character 's' is " + index1); //The Index Value of character 's' is 5
DATA TYPES AND VARIABLES
Bracket Notation
Strings contain characters. One way these char values can be accessed is with bracket notation. We can even store these chars in separate variables.
We access a specific character by using the square brackets on the string, putting the index position of the desired character between the brackets. For example, to get the first character, you can specify variable[0]. To get the last character, you can subtract one from the length of the string.
// Get values from this string. string value = "Dot Net Perls"; //variable first contains letter D char first = value[0]; //Second contains letter o char second = value[1]; //last contains letter s char last = value[value.Length - 1];
DATA TYPES AND VARIABLES
Escape Character Sequences in C#
In C#, an escape sequence refers to a combination of characters beginning with a back slash \ followed by letters or digits. It’s used to make sure that the program reads certain characters as part of a string. For example, it can be used to include quotation marks within a string that you would like to print to console. Escape sequences can do other things using specific characters. \n is used to create a new line.
DATA TYPES AND VARIABLES
Substring() in C#
In C#, Substring() is a string method used to retrieve part of a string while keeping the original data intact. The substring that you retrieve can be stored in a variable for use elsewhere in your program.
string myString = "Divyesh"; string test1 = myString.Substring(2);
DATA TYPES AND VARIABLES
String Concatenation in C#
Concatenation is the process of appending one string to the end of another string. The simplest method of adding two strings in C# is using the + operator.
// Declare strings string firstName = "Divyesh"; string lastName = "Goardnan"; // Concatenate two string variables string name = firstName + " " + lastName; Console.WriteLine(name); //Ths code will output Divyesh Goardnan
DATA TYPES AND VARIABLES
.ToLower() in C#
In C#, .ToLower() is a string method that converts every character to lowercase. If a character does not have a lowercase equivalent, it remains unchanged. For example, special symbols remain unchanged.
string mixedCase = "This is a MIXED case string."; // Call ToLower instance method, which returns a new copy. string lower = mixedCase.ToLower(); //variable lower contains "this is a mixed case string."
DATA TYPES AND VARIABLES
String Length in C#
The string class has a Length property, which returns the number of characters in the string.
string a = "One example"; Console.WriteLine("LENGTH: " + a.Length); // This code outputs 11
DATA TYPES AND VARIABLES
String Interpolation in C#
String interpolation provides a more readable and convenient syntax to create formatted strings. It allows us to insert variable values and expressions in the middle of a string so that we don’t have to worry about punctuation or spaces.
int id = 100 // We can use an expression with a string interpolation. string multipliedNumber = $"The multiplied ID is {id * 10}."; Console.WriteLine(multipliedNumber); // This code would output "The multiplied ID is 1000."
DATA TYPES AND VARIABLES
String New-Line
The character combination \n represents a newline character when inside a C# string.
For example passing “Hello\nWorld” to Console.WriteLine() would print Hello and World on separate lines in the console.
Console.WriteLine("Hello\nWorld"); // The console output will look like: // Hello // World
DATA TYPES AND VARIABLES
Converting Data Types
把double myDouble = 3.2;变成int
double myDouble = 3.2; // Round myDouble to the nearest whole number int myInt = myDouble;
it could not work
it should be like this:
explicit conversion: requires a cast operator to convert a data type into another one. So if we do want to convert a double to an int, we could use the operator (int).
double myDouble = 3.2; // Round myDouble to the nearest whole number int myInt = (int)myDouble;
WORKING WITH NUMBERS
Double and Decimal
If we need to use a decimal value, we have a few options: float, double, and decimal. These values are useful for anything that requires more precision than a whole number, like measuring the precise location of an object in 3D space.
A double is usually the best choice of the three because it is more precise than a float, but faster to process than a decimal. However, make sure to use a decimal for financial applications, since it is the most precise.
To define a variable with the type double, you would write it as follows:
double variableName = 39.76876;
To define a variable with the type decimal, you would write it as follows:
decimal variableName = 489872.76m;
Don’t forget the m character after the number! This character tells C# that we’re defining a decimal and not a double.
Learn C#: Logic and Conditionals
Boolean Expressions
A boolean expression is any expression that evaluates to, or returns, a boolean value.
// These expressions all evaluate to a boolean value. // Therefore their values can be stored in boolean variables. bool a = (2 > 1); bool b = a && true; bool c = !false || (7 < 8);
Learn C#: Logic and Conditionals
Logical Operators
Logical operators receive boolean expressions as input and return a boolean value.
The && operator takes two boolean expressions and returns true only if they both evaluate to true.
The || operator takes two boolean expressions and returns true if either one evaluates to true.
The ! operator takes one boolean expression and returns the opposite value.
// These variables equal true. bool a = true && true; bool b = false || true; bool c = !false; // These variables equal false. bool d = true && false; bool e = false || false; bool f = !true;
Learn C#: Logic and Conditionals
Comparison Operators
A comparison operator, as the name implies, compares two expressions and returns either true or false depending on the result of the comparison. For example, if we compared two int values, we could test to see if one number is greater than the other, or if both numbers are equal. Similarly, we can test one string for equality against another string.
int x = 5; Console.WriteLine(x < 6); // Prints "True" because 5 is less than 6. Console.WriteLine(x > 8); // Prints "False" because 5 is not greater than 8. string foo = "foo"; Console.WriteLine(foo == "bar"); // Prints "False" because "foo" does not equal "bar".
Learn C#: Logic and Conditionals
If Statements
In C#, an if statement executes a block of code based on whether or not the boolean expression provided in the parentheses is true or false.
If the expression is true then the block of code inside the braces, {}, is executed. Otherwise, the block is skipped over.
if (true) { // This code is executed. Console.WriteLine("Hello User!"); } if (false) { // This code is skipped. Console.WriteLine("This won't be seen :("); }
Learn C#: Logic and Conditionals
Break Keyword
One of the uses of the break keyword in C# is to exit out of switch/case blocks and resume program execution after the switch code block. In C#, each case code block inside a switch statement needs to be exited with the break keyword (or some other jump statement), otherwise the program will not compile. It should be called once all of the instructions specific to that particular case have been executed.
string color = "blue"; switch (color) { case "red": Console.WriteLine("I don't like that color."); break; case "blue": Console.WriteLine("I like that color."); break; default: Console.WriteLine("I feel ambivalent about that color."); break; } // Regardless of where the break statement is in the above switch statement, // breaking will resume the program execution here. Console.WriteLine("- Steve");
Learn C#: Logic and Conditionals
Ternary Operator
In C#, the ternary operator is a special syntax of the form: condition ? expression1 : expression2.
It takes one boolean condition and two expressions as inputs. Unlike an if statement, the ternary operator is an expression itself. It evaluates to either its first input expression or its second input expression depending on whether the condition is true or false, respectively.
bool isRaining = true; // This sets umbrellaOrNot to "Umbrella" if isRaining is true, // and "No Umbrella" if isRaining is false. string umbrellaOrNot = isRaining ? "Umbrella" : "No Umbrella"; // "Umbrella" Console.WriteLine(umbrellaOrNot);
Learn C#: Logic and Conditionals
Else Clause
An else followed by braces, {}, containing a code block, is called an else clause. else clauses must always be preceded by an if statement.
The block inside the braces will only run if the expression in the accompanying if condition is false. It is useful for writing code that runs only if the code inside the if statement is not executed.
if (true) { // This block will run. Console.WriteLine("Seen!"); } else { // This will not run. Console.WriteLine("Not seen!"); } if (false) { // Conversely, this will not run. Console.WriteLine("Not seen!"); } else { // Instead, this will run. Console.WriteLine("Seen!"); }
Learn C#: Logic and Conditionals
If and Else If
A common pattern when writing multiple if and else statements is to have an else block that contains another nested if statement, which can contain another else, etc. A better way to express this pattern in C# is with else if statements. The first condition that evaluates to true will run its associated code block. If none are true, then the optional else block will run if it exists.
int x = 100, y = 80; if (x > y) { Console.WriteLine("x is greater than y"); } else if (x < y) { Console.WriteLine("x is less than y"); } else { Console.WriteLine("x is equal to y"); }
Learn C#: Logic and Conditionals
Switch Statements
A switch statement is a control flow structure that evaluates one expression and decides which code block to run by trying to match the result of the expression to each case. In general, a code block is executed when the value given for a case equals the evaluated expression, i.e, when == between the two values returns true. switch statements are often used to replace if else structures when all conditions test for equality on one value.
// The expression to match goes in parentheses. switch (fruit) { case "Banana": // If fruit == "Banana", this block will run. Console.WriteLine("Peel first."); break; case "Durian": Console.WriteLine("Strong smell."); break; default: // The default block will catch expressions that did not match any above. Console.WriteLine("Nothing to say."); break; } // The switch statement above is equivalent to this: if (fruit == "Banana") { Console.WriteLine("Peel first."); } else if (fruit == "Durian") { Console.WriteLine("Strong smell."); } else { Console.WriteLine("Nothing to say."); }
Learn C#: Methods
Optional Parameters
In C#, methods can be given optional parameters. A parameter is optional if its declaration specifies a default argument. Methods with an optional parameter can be called with or without passing in an argument for that parameter. If a method is called without passing in an argument for the optional parameter, then the parameter is initialized with its default value.
To define an optional parameter, use an equals sign after the parameter declaration followed by its default value.
// y and z are optional parameters. static int AddSomeNumbers(int x, int y = 3, int z = 2) { return x + y + z; } // Any of the following are valid method calls. AddSomeNumbers(1); // Returns 6. AddSomeNumbers(1, 1); // Returns 4. AddSomeNumbers(3, 3, 3); // Returns 9.
Learn C#: Methods
Variables Inside Methods
Parameters and variables declared inside of a method cannot be used outside of the method’s body. Attempting to do so will cause an error when compiling the program!
static void DeclareAndPrintVars(int x) { int y = 3; // Using x and y inside the method is fine. Console.WriteLine(x + y); } static void Main() { DeclareAndPrintVars(5); // x and y only exist inside the body of DeclareAndPrintVars, so we cannot use them here. Console.WriteLine(x * y); }
Learn C#: Methods
Variables Inside Methods
Parameters and variables declared inside of a method cannot be used outside of the method’s body. Attempting to do so will cause an error when compiling the program!
static void DeclareAndPrintVars(int x) { int y = 3; // Using x and y inside the method is fine. Console.WriteLine(x + y); } static void Main() { DeclareAndPrintVars(5); // x and y only exist inside the body of DeclareAndPrintVars, so we cannot use them here. Console.WriteLine(x * y); }
Learn C#: Methods
Void Return Type
In C#, methods that do not return a value have a void return type.
void is not an actual data type like int or string, as it represents the lack of an output or value.
// This method has no return value static void DoesNotReturn() { Console.WriteLine("Hi, I don't return like a bad library borrower."); } // This method returns an int static int ReturnsAnInt() { return 2 + 3; }
Learn C#: Methods
Method Declaration
In C#, a method declaration, also known as a method header, includes everything about the method other than the method’s body. The method declaration includes:
* the method name
* parameter types
* parameter order
* parameter names
* return type
* optional modifiers
A method declaration you’ve seen often is the declaration for the Main method (note there is more than one valid Main declaration):
static void Main(string[] args)
// This is an example of a method header. static int MyMethodName(int parameter1, string parameter2) { // Method body goes here... }
Learn C#: Methods
Return Keyword
In C#, the return statement can be used to return a value from a method back to the method’s caller.
When return is invoked, the current method terminates and control is returned to where the method was originally called. The value that is returned by the method must match the method’s return type, which is specified in the method declaration.
static int ReturnAValue(int x) { // We return the result of computing x * 10 back to the caller. // Notice how we are returning an int, which matches the method's return type. return x * 10; } static void Main() { // We can use the returned value any way we want, such as storing it in a variable. int num = ReturnAValue(5); // Prints 50 to the console. Console.WriteLine(num); }
Learn C#: Methods
Out Parameters
return can only return one value. When multiple values are needed, out parameters can be used.
out parameters are prefixed with out in the method header. When called, the argument for each out parameter must be a variable prefixed with out.
The out parameters become aliases for the variables that were passed in. So, we can assign values to the parameters, and they will persist on the variables we passed in after the method terminates.
// f1, f2, and f3 are out parameters, so they must be prefixed with `out`. static void GetFavoriteFoods(out string f1, out string f2, out string f3) { // Notice how we are assigning values to the parameters instead of using `return`. f1 = "Sushi"; f2 = "Pizza"; f3 = "Hamburgers"; } static void Main() { string food1; string food2; string food3; // Variables passed to out parameters must also be prefixed with `out`. GetFavoriteFoods(out food1, out food2, out food3); // After the method call, food1 = "Sushi", food2 = "Pizza", and food3 = "Hamburgers". Console.WriteLine($"My top 3 favorite foods are {food1}, {food2}, and {food3}"); }
Learn C#: Methods
Expression-Bodied Methods
In C#, expression-bodied methods are short methods written using a special concise syntax. A method can only be written in expression body form when the method body consists of a single statement or expression. If the body is a single expression, then that expression is used as the method’s return value.
The general syntax is returnType funcName(args…) => expression;. Notice how “fat arrow” notation, =>, is used instead of curly braces. Also note that the return keyword is not needed, since the expression is implicitly returned.
static int Add(int x, int y) { return x + y; } static void PrintUpper(string str) { Console.WriteLine(str.ToUpper()); } // The same methods written in expression-body form. static int Add(int x, int y) => x + y; static void PrintUpper(string str) => Console.WriteLine(str.ToUpper());
Learn C#: Methods
Lambda Expressions
A lambda expression is a block of code that is treated like any other value or expression. It can be passed into methods, stored in variables, and created inside methods.
In particular, lambda expressions are useful for creating anonymous methods, methods with no name, to be passed into methods that require method arguments. Their concise syntax is more elegant than declaring a regular method when they are being used as one off method arguments.
int[] numbers = { 3, 10, 4, 6, 8 }; static bool isTen(int n) { return n == 10; } // `Array.Exists` calls the method passed in for every value in `numbers` and returns true if any call returns true. Array.Exists(numbers, isTen); Array.Exists(numbers, (int n) => { return n == 10; }); // Typical syntax // (input-parameters) => { <statements> }
Learn C#: Methods
Shorter Lambda Expressions
There are multiple ways to shorten the concise lambda expression syntax.
The parameter type can be removed if it can be inferred.
The parentheses can be removed if there is only one parameter.
As a side note, the usual rules for expression-bodied methods also apply to lambdas.
int[] numbers = { 7, 7, 7, 4, 7 }; Array.Find(numbers, (int n) => { return n != 7; }); // The type specifier on `n` can be inferred based on the array being passed in and the method body. Array.Find(numbers, (n) => { return n != 7; }); // The parentheses can be removed since there is only one parameter. Array.Find(numbers, n => { return n != 7; }); // Finally, we can apply the rules for expression-bodied methods. Array.Find(numbers, n => n != 7);
Learn C#: Arrays and Loops
C# Arrays
In C#, an array is a structure representing a fixed length ordered collection of values or objects with the same type.
Arrays make it easier to organize and operate on large amounts of data. For example, rather than creating 100 integer variables, you can just create one array that stores all those integers!
// `numbers` array that stores integers int[] numbers = { 3, 14, 59 }; // 'characters' array that stores strings string[] characters = new string[] { "Huey", "Dewey", "Louie" };
Learn C#: Arrays and Loops
Declaring Arrays
A C# array variable is declared similarly to a non-array variable, with the addition of square brackets ([]) after the type specifier to denote it as an array.
The new keyword is needed when instantiating a new array to assign to the variable, as well as the array length in the square brackets. The array can also be instantiated with values using curly braces ({}). In this case the array length is not necessary.
// Declare an array of length 8 without setting the values. string[] stringArray = new string[8]; // Declare array and set its values to 3, 4, 5. int[] intArray = new int[] { 3, 4, 5 };
Learn C#: Arrays and Loops
Declare and Initialize array
In C#, one way an array can be declared and initialized at the same time is by assigning the newly declared array to a comma separated list of the values surrounded by curly braces ({}). Note how we can omit the type signature and new keyword on the right side of the assignment using this syntax. This is only possible during the array’s declaration.
// `numbers` and `animals` are both declared and initialized with values. int[] numbers = { 1, 3, -10, 5, 8 }; string[] animals = { "shark", "bear", "dog", "raccoon" };
Learn C#: Arrays and Loops
Array Element Access
In C#, the elements of an array are labeled incrementally, starting at 0 for the first element. For example, the 3rd element of an array would be indexed at 2, and the 6th element of an array would be indexed at 5.
A specific element can be accessed by using the square bracket operator, surrounding the index with square brackets. Once accessed, the element can be used in an expression, or modified like a regular variable.
// Initialize an array with 6 values. int[] numbers = { 3, 14, 59, 26, 53, 0 }; // Assign the last element, the 6th number in the array (currently 0), to 58. numbers[5] = 58; // Store the first element, 3, in the variable `first`. int first = numbers[0];
Learn C#: Arrays and Loops
C# Array Length
The Length property of a C# array can be used to get the number of elements in a particular array.
int[] someArray = { 3, 4, 1, 6 }; Console.WriteLine(someArray.Length); // Prints 4 string[] otherArray = { "foo", "bar", "baz" }; Console.WriteLine(otherArray.Length); // Prints 3
Learn C#: Arrays and Loops
C# For Loops
A C# for loop executes a set of instructions for a specified number of times, based on three provided expressions. The three expressions are separated by semicolons, and in order they are:
Initialization: This is run exactly once at the start of the loop, usually used to initialize the loop’s iterator variable.
Stopping condition: This boolean expression is checked before each iteration to see if it should run.
Iteration statement: This is executed after each iteration of the loop, usually used to update the iterator variable.
// This loop initializes i to 1, stops looping once i is greater than 10, and increases i by 1 after each loop. for (int i = 1; i <= 10; i++) { Console.WriteLine(i); } Console.WriteLine("Ready or not, here I come!");
Learn C#: Arrays and Loops
C# For Each Loop
A C# foreach loop runs a set of instructions once for each element in a given collection. For example, if an array has 200 elements, then the foreach loop’s body will execute 200 times. At the start of each iteration, a variable is initialized to the current element being processed.
A for each loop is declared with the foreach keyword. Next, in parentheses, a variable type and variable name followed by the in keyword and the collection to iterate over.
string[] states = { "Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado" }; foreach (string state in states) { // The `state` variable takes on the value of an element in `states` and updates every iteration. Console.WriteLine(state); } // Will print each element of `states` in the order they appear in the array.
C# While Loop
C# While Loop
In C#, a while loop executes a set of instructions continuously while the given boolean expression evaluates to true or one of the instructions inside the loop body, such as the break instruction, terminates the loop.
Note that the loop body might not run at all, since the boolean condition is evaluated before the very first iteration of the while loop.
The syntax to declare a while loop is simply the while keyword followed by a boolean condition in parentheses.
string guess = ""; Console.WriteLine("What animal am I thinking of?"); // This loop will keep prompting the user, until they type in "dog". while (guess != "dog") { Console.WriteLine("Make a guess:"); guess = Console.ReadLine(); } Console.WriteLine("That's right!");
Learn C#: Arrays and Loops
C# Do While Loop
In C#, a do while loop runs a set of instructions once and then continues running as long as the given boolean condition is true. Notice how this behavior is nearly identical to a while loop, with the distinction that a do while runs one or more times, and a while loop runs zero or more times.
The syntax to declare a do while is the do keyword, followed by the code block, then the while keyword with the boolean condition in parentheses. Note that a semi-colon is necessary to end a do while loop.
do { DoStuff(); } while(boolCondition); // This do-while is equivalent to the following while loop. DoStuff(); while (boolCondition) { DoStuff(); }
Learn C#: Arrays and Loops
C# Infinite Loop
An infinite loop is a loop that never terminates because its stopping condition is always false. An infinite loop can be useful if a program consists of continuously executing one chunk of code. But, an unintentional infinite loop can cause a program to hang and become unresponsive due to being stuck in the loop.
A program running in a shell or terminal stuck in an infinite loop can be ended by terminating the process.
while (true) { // This will loop forever unless it contains some terminating statement such as `break`. }
Learn C#: Arrays and Loops
C# Jump Statements
Jump statements are tools used to give the programmer additional control over the program’s control flow. They are very commonly used in the context of loops to exit from the loop or to skip parts of the loop.
Control flow keywords include break, continue, and return. The given code snippets provide examples of their usage.
while (true) { Console.WriteLine("This prints once."); // A `break` statement immediately terminates the loop that contains it. break; } for (int i = 1; i <= 10; i++) { // This prints every number from 1 to 10 except for 7. if (i == 7) { // A `continue` statement skips the rest of the loop and starts another iteration from the start. continue; } Console.WriteLine(i); } static int WeirdReturnOne() { while (true) { // Since `return` exits the method, the loop is also terminated. Control returns to the method's caller. return 1; } }
Learn C#: Arrays and Loops
C# Classes
In C#, classes are used to create custom types. The class defines the kinds of information and methods included in a custom type.
using System; namespace BasicClasses { class Forest { public string name; public int trees; } } // Here we have the Forest class which has two pieces of data, called fields. They are the "name" and "trees" fields.
Learn C#: Arrays and Loops
C# Constructor
In C#, whenever an instance of a class is created, its constructor is called. Like methods, a constructor can be overloaded. It must have the same name as the enclosing class. This is useful when you may want to define an additional constructor that takes a different number of arguments.
// Takes two arguments public Forest(int area, string country) { this.Area = area; this.Country = country; } // Takes one argument public Forest(int area) { this.Area = area; this.Country = "Unknown"; } // Typically, a constructor is used to set initial values and run any code needed to “set up” an instance. // A constructor looks like a method, but its return type and method name are reduced to the name of the enclosing type.
Learn C#: Arrays and Loops
C# Parameterless Constructor
In C#, if no constructors are specified in a class, the compiler automatically creates a parameterless constructor.
public class Freshman { public string FirstName { get; set; } } public static void Main (string[] args) { Freshman f = new Freshman(); // name is null string name = f.FirstName; } // In this example, no constructor is defined in Freshman, but a parameterless constructor is still available for use in Main().
Learn C#: Arrays and Loops
C# Access Modifiers
In C#, members of a class can be marked with access modifiers, including public and private. A public member can be accessed by other classes. A private member can only be accessed by code in the same class.
By default, fields, properties, and methods are private, and classes are public.
public class Speech { private string greeting = "Greetings"; private string FormalGreeting() { return $"{greeting} and salutations"; } public string Scream() { return FormalGreeting().ToUpper(); } } public static void Main (string[] args) { Speech s = new Speech(); //string sfg = s.FormalGreeting(); // Error! //string sg = s.greeting; // Error! Console.WriteLine(s.Scream()); } // In this example, greeting and FormalGreeting() are private. They cannot be called from the Main() method, which belongs to a different class. However the code within Scream() can access those members because Scream() is part of the same class.
Learn C#: Arrays and Loops
C# Field
In C#, a field stores a piece of data within an object. It acts like a variable and may have a different value for each instance of a type.
A field can have a number of modifiers, including: public, private, static, and readonly. If no access modifier is provided, a field is private by default.
public class Person { private string firstName; private string lastName; } // In this example, firstName and lastName are private fields of the Person class. // For effective encapsulation, a field is typically set to private, then accessed using a property. This ensures that values passed to an instance are validated (assuming the property implements some kind of validation for its field).
Learn C#: Arrays and Loops
C# this Keyword
In C#, the this keyword refers to the current instance of a class.
// We can use the this keyword to refer to the current class’s members hidden by similar names: public NationalPark(int area, string state) { this.area = area; this.state = state; } // The code below requires duplicate code, which can lead to extra work and errors when changes are needed: public NationalPark(int area, string state) { area = area; state = state; } public NationalPark(int area) { area = area; state = "Unknown"; } // Use this to have one constructor call another: public NationalPark(int area) : this (state, "Unknown") { }
Learn C#: Arrays and Loops
C# Members
In C#, a class contains members, which define the kind of data stored in a class and the behaviors a class can perform.
class Forest { public string name; public string Name { get { return name; } set { name = value; } } } // A member of a class can be a field (like name), a property (like Name) or a method (like get()/set()). It can also be any of the following: // Constants // Constructors // Events // Finalizers // Indexers // Operators // Nested Types
Learn C#: Arrays and Loops
C# Dot Notation
In C#, a member of a class can be accessed with dot notation.
string greeting = "hello"; // Prints 5 Console.WriteLine(greeting.Length); // Returns 8 Math.Min(8, 920);