Build Web Apps with ASP.NET Flashcards

1
Q

Build Web Apps with ASP.NET

What is .NET?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Build Web Apps with ASP.NET

How do I get .NET?

A

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!”).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Build Web Apps with ASP.NET

How do I get .NET?

A

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!”).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Build Web Apps with ASP.NET

What about ASP.NET?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Build Web Apps with ASP.NET

Summary:
Hopefully, this helps you see the big picture before diving into the details of C#:

A
  • 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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Build Web Apps with ASP.NET

Console.ReadLine()

A

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();
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Build Web Apps with ASP.NET

Getting Input

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Build Web Apps with ASP.NET

Comments

A

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 */
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Build Web Apps with ASP.NET

Console.WriteLine()

A

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!
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Build Web Apps with ASP.NET

C# in the Wild

A

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%.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

DATA TYPES AND VARIABLES

Introduction to Data Types and Variables in C#

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

DATA TYPES AND VARIABLES

C# Data Types

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

DATA TYPES AND VARIABLES

Variables and Types

A

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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

DATA TYPES AND VARIABLES

Math.Sqrt()

A

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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

DATA TYPES AND VARIABLES

Math.Sqrt()

A

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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

DATA TYPES AND VARIABLES

Arithmetic Operators

A

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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

DATA TYPES AND VARIABLES

Unary Operator

A

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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

DATA TYPES AND VARIABLES

Math.Pow()

A

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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

DATA TYPES AND VARIABLES

.toUpper() in C#

A

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_$#%"
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

DATA TYPES AND VARIABLES

IndexOf() in C#

A

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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

DATA TYPES AND VARIABLES

Bracket Notation

A

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];
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

DATA TYPES AND VARIABLES

Escape Character Sequences in C#

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

DATA TYPES AND VARIABLES

Substring() in C#

A

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); 
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

DATA TYPES AND VARIABLES

String Concatenation in C#

A

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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

DATA TYPES AND VARIABLES

.ToLower() in C#

A

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."
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

DATA TYPES AND VARIABLES

String Length in C#

A

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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
26
Q

DATA TYPES AND VARIABLES

String Interpolation in C#

A

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."
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
27
Q

DATA TYPES AND VARIABLES

String New-Line

A

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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
28
Q

DATA TYPES AND VARIABLES

Converting Data Types
把double myDouble = 3.2;变成int

A
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;
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
29
Q

WORKING WITH NUMBERS

Double and Decimal

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
30
Q

Learn C#: Logic and Conditionals

Boolean Expressions

A

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);
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
31
Q

Learn C#: Logic and Conditionals

Logical Operators

A

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;
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
32
Q

Learn C#: Logic and Conditionals

Comparison Operators

A

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".
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
33
Q

Learn C#: Logic and Conditionals

If Statements

A

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 :(");
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
34
Q

Learn C#: Logic and Conditionals

Break Keyword

A

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");
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
35
Q

Learn C#: Logic and Conditionals

Ternary Operator

A

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);
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
36
Q

Learn C#: Logic and Conditionals

Else Clause

A

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!");
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
37
Q

Learn C#: Logic and Conditionals

If and Else If

A

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");
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
38
Q

Learn C#: Logic and Conditionals

Switch Statements

A

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.");
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
39
Q

Learn C#: Methods

Optional Parameters

A

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.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
40
Q

Learn C#: Methods

Variables Inside Methods

A

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);
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
41
Q

Learn C#: Methods

Variables Inside Methods

A

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);
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
42
Q

Learn C#: Methods

Void Return Type

A

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;
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
43
Q

Learn C#: Methods

Method Declaration

A

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...
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
44
Q

Learn C#: Methods

Return Keyword

A

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);
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
45
Q

Learn C#: Methods

Out Parameters

A

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}");
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
46
Q

Learn C#: Methods

Expression-Bodied Methods

A

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());
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
47
Q

Learn C#: Methods

Lambda Expressions

A

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> }
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
48
Q

Learn C#: Methods

Shorter Lambda Expressions

A

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);
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
49
Q

Learn C#: Arrays and Loops

C# Arrays

A

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" };
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
50
Q

Learn C#: Arrays and Loops

Declaring Arrays

A

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 };
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
51
Q

Learn C#: Arrays and Loops

Declare and Initialize array

A

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" };
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
52
Q

Learn C#: Arrays and Loops

Array Element Access

A

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];
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
53
Q

Learn C#: Arrays and Loops

C# Array Length

A

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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
54
Q

Learn C#: Arrays and Loops

C# For Loops

A

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!");
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
55
Q

Learn C#: Arrays and Loops

C# For Each Loop

A

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. 
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
56
Q

C# While Loop

C# While Loop

A

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!");
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
57
Q

Learn C#: Arrays and Loops

C# Do While Loop

A

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();
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
58
Q

Learn C#: Arrays and Loops

C# Infinite Loop

A

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`.
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
59
Q

Learn C#: Arrays and Loops

C# Jump Statements

A

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;
  }
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
60
Q

Learn C#: Arrays and Loops

C# Classes

A

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.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
61
Q

Learn C#: Arrays and Loops

C# Constructor

A

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.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
62
Q

Learn C#: Arrays and Loops

C# Parameterless Constructor

A

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().
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
63
Q

Learn C#: Arrays and Loops

C# Access Modifiers

A

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.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
64
Q

Learn C#: Arrays and Loops

C# Field

A

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).
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
65
Q

Learn C#: Arrays and Loops

C# this Keyword

A

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")
{ }
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
66
Q

Learn C#: Arrays and Loops

C# Members

A

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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
67
Q

Learn C#: Arrays and Loops

C# Dot Notation

A

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);
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
68
Q

Learn C#: Arrays and Loops

C# Class Instance

A

In C#, an object is an instance of a class. An object can be created from a class using the new keyword.

Burger cheeseburger = new Burger();
// If a class is a recipe, then an object is a single meal made from that recipe.

House tudor = new House();
// If a class is a blueprint, then an object is a house made from that blueprint.
69
Q

Learn C#: Arrays and Loops

C# Property

A

In C#, a property is a member of an object that controls how one field may be accessed and/or modified. A property defines two methods: a get() method that describes how a field can be accessed, and a set() method that describes how a field can be modified.

One use case for properties is to control access to a field. Another is to validate values for a field.

public class Freshman
{
  private string firstName;

  public string FirstName
  {
    get { return firstName; }
    set { firstName = value; }
  }
}

public static void Main (string[] args) {
  Freshman f = new Freshman();
  f.FirstName = "Louie";
  
  // Prints "Louie"
  Console.WriteLine(f.FirstName);
}

// In this example, FirstName is a property 
70
Q

Learn C#: Arrays and Loops

C# Auto-Implemented Property

A

In C#, an auto-implemented property reads and writes to a private field, like other properties, but it does not require explicit definitions for the accessor methods nor the field. It is used with the { get; set; } syntax. This helps your code become more concise.

public class HotSauce
{
  public string Title
  { get; set; }

  public string Origin
  { get; set; }
}

// In this example, Title and Origin are auto-implemented properties. Notice that a definition for each field (like private string title) is no longer necessary. A hidden, private field is created for each property during runtime.
71
Q

Learn C#: Arrays and Loops

C# Static Constructor

A

In C#, a static constructor is run once per type, not per instance. It must be parameterless. It is invoked before the type is instantiated or a static member is accessed.

class Forest
{
  static Forest()
  { 
    Console.WriteLine("Type Initialized"); 
  }
}
// In this class, either of the following two lines would trigger the static constructor (but it would not be triggered twice if these two lines followed each other in succession):
Forest f  = new Forest();
Forest.Define();
72
Q

Learn C#: Arrays and Loops

C# Static Class

A

In C#, a static class cannot be instantiated. Its members are accessed by the class name.

This is useful when you want a class that provides a set of tools, but doesn’t need to maintain any internal data.

Math is a commonly-used static class.

//Two examples of static classes calling static methods:

Math.Min(23, 97);
Console.WriteLine("Let's Go!");
73
Q

Learn C#: Interfaces and Inheritance

C# Interface

A

In C#, an interface contains definitions for a group of related functionalities that a class can implement.

Interfaces are useful because they guarantee how a class behaves. This, along with the fact that a class can implement multiple interfaces, helps organize and modularize components of software.

It is best practice to start the name of an interface with “I”.

interface IAutomobile
{
  string LicensePlate { get; }
  double Speed { get; }
  int Wheels { get; }
}

// The IAutomobile interface has three properties. Any class that implements this interface must have these three properties.

public interface IAccount
{
  void PayInFunds ( decimal amount );
  bool WithdrawFunds ( decimal amount );
  decimal GetBalance ();
}

// The IAccount interface has three methods to implement.

public class CustomerAccount : IAccount
{ }

// This CustomerAccount class is labeled with : IAccount, which means that it will implement that interface.
74
Q

Learn C#: Interfaces and Inheritance

C# Inheritance

A

In C#, inheritance is the process by which one class inherits the members of another class. The class that inherits is called a subclass or derived class. The other class is called a superclass, or a base class.

When you define a class that inherits from another class, the derived class implicitly gains all the members of the base class, except for its constructors and finalizers. The derived class can thereby reuse the code in the base class without having to re-implement it. In the derived class, you can add more members. In this manner, the derived class extends the functionality of the base class.

public class Honeymoon : TripPlanner
{ }

// Similar to an interface, inheritance also uses the colon syntax to denote a class inherited super class. In this case, Honeymoon class inherits from TripPlanner class.

// A derived class can only inherit from one base class, but inheritance is transitive. That base class may inherit from another class, and so on, which creates a class hierarchy.
75
Q

Learn C#: Interfaces and Inheritance

C# override/virtual Keywords

A

In C#, a derived class (subclass) can modify the behavior of an inherited method. The method in the derived class must be labeled override and the method in the base class (superclass) must be labeled virtual.

The virtual and override keywords are useful for two reasons:
1. Since the compiler treats “regular” and virtual methods differently, they must be marked as such.
2. This avoids the “hiding” of inherited methods, which helps developers understand the intention of the code.

class BaseClass  
{  
  public virtual void Method1()  
  {  
    Console.WriteLine("Base - Method1");  
  }  
}  

class DerivedClass : BaseClass  
{  
  public override void Method1()  
  {  
    Console.WriteLine("Derived - Method1");   }  
}  
76
Q

Learn C#: Interfaces and Inheritance

C# abstract Keyword

A

In C#, the abstract modifier indicates that the thing being modified has a missing or incomplete implementation. It must be implemented completely by a derived, non-abstract class.

The abstract modifier can be used with classes, methods, properties, indexers, and events. Use the abstract modifier in a class declaration to indicate that a class is intended only to be a base class of other classes, not instantiated on its own.

If at least one member of a class is abstract, the containing class must also be marked abstract.

The complete implementation of an abstract member must be marked with override.

abstract class Shape
{
  public abstract int GetArea();
}

class Square : Shape
{
  int side;
  public Square(int n) => side = n;
  // GetArea method is required to avoid a compile-time error.
  public override int GetArea() => side * side;
}

// In this example, GetArea() is an abstract method within the abstract Shape class. It is implemented by the derived class Square.
77
Q

Learn C#: References

C# Reference Types

A

In C#, classes and interfaces are reference types. Variables of reference types store references to their data (objects) in memory, and they do not contain the data itself.

An object of type Object, string, or dynamic is also a reference type.

SportsCar sc = new SportsCar(100);
SportsCar sc2 = sc;
sc.SpeedUp(); // Method adds 20
Console.WriteLine(sc.Speed); // 120
Console.WriteLine(sc2.Speed); // 120

// In this code, sc and sc2 refer to the same object. The last two lines will print the same value to the console.
C# Object Reference
78
Q

Learn C#: References

C# Object Reference

A

In C#, an object may be referenced by any type in its inheritance hierarchy or by any of the interfaces it implements.

// Woman inherits from Human, which inherits from Animal, and it implements IPerson:
class Human : Animal
class Woman : Human, IPerson

// All of these references are valid:
Woman eve = new Woman();
Human h = eve;
Animal a = eve;
IPerson p = eve;
79
Q

Learn C#: References

C# Object Reference Functionality

A

In C#, the functionality available to an object reference is determined by the reference’s type, not the object’s type.

Player p = new Player();
Fan f = p;
p.SignContract();
f.SignContract();
// Error! 'SignContract()` is not defined for the type 'Fan'
80
Q

Learn C#: References

C# Polyphormism

A

Polymorphism is the ability in programming to present the same interface for different underlying forms (data types).

We can break the idea into two related concepts. A programming language supports polymorphism if:

  • Objects of different types have a common interface (interface in the general meaning, not just a C# interface), and
  • The objects can maintain functionality unique to their data type
class Novel : Book
{
  public override string Stringify()
  {
    return "This is a Novel!;
  }
}

class Book
{
  public virtual string Stringify()
  {
    return "This is a Book!;
  }
}

// In the below code, you’ll see that a Novel and Book object can both be referred to as Books. This is one of their shared interfaces. At the same time, they are different data types with unique functionality.

Book bk = new Book();
Book warAndPeace = new Novel();
Console.WriteLine(bk.Stringify());
Console.WriteLine(warAndPeace.Stringify());

// This is a Book!
// This is a Novel

// Even though bk and warAndPeace are the same type of reference, their behavior is different. Novel overrides the Stringify() method, so all Novel objects (regardless of reference type) will use that method.
81
Q

Learn C#: References

C# Upcasting

A

In C#, upcasting is creating an inherited superclass or implemented interface reference from a subclass reference.

// In this case, string inherits from Object:

string s = "Hi";
Object o = s;

// In this case, Laptop implements the IPortable interface:

Laptop lap = new Laptop();
IPortable portable = lap;
82
Q

Learn C#: References

C# Downcasting

A

In C#, downcasting is creating a subclass reference from a superclass or interface reference.

Downcasting can lead to runtime errors if the superclass cannot be cast to the specified subclass.

Account a = new Account();
CustomerAccount ca = a;
// error CS0266: Cannot implicitly convert type `Account` to `CustomerAccount`. An explicit conversion exists (are you missing a cast?)
// Dog inherits from Pet. An implicit downcast throws a compile-time error:
Pet pet = new Pet();
Dog dog = pet;
// error CS0266: Cannot implicitly convert type `Pet` to `Dog`. An explicit conversion exists (are you missing a cast?)

// Every downcast must be explicit, using the cast operator, like (TYPE). This fixes the compile-time error but raises a new runtime error.
Pet pet = new Pet();
Dog dog = (Pet)pet;
// runtime error: System.InvalidCastException: Specified cast is not valid.

//The explicit downcast would only work if the underlying object is of type Dog:
Dog dog = new Dog();
Pet pet = dog;
Dog puppy = (Dog)pet;
83
Q

Learn C#: References

C# Null Reference

A

In C#, an undefined reference is either a null reference or unassigned. A null reference is represented by the keyword null.

Be careful when checking for null and unassigned references. We can only compare a null reference if it is explicitly labeled null.

MyClass mc; //unassigned

Console.WriteLine (mc == null);
// error CS0165: Use of unassigned local variable 'mc'

MyClass mc = null; //explicitly 'null'

Console.WriteLine(mc == null);
// Prints true.

// Array of unassigned references
MyClass[] objects = new MyClass[5];
// objects[0] is unassigned, objects[1] is unassigned, etc...
84
Q

Learn C#: References

C# Value Types

A

In C#, value types contain the data itself. They include int, bool, char, and double.

Here’s the entire list of value types:

  • char, bool, DateTime
  • All numeric data types
  • Structures (struct)
  • Enumerations (enum)
85
Q

Learn C#: References

C# Comparison Type

A

In C#, the type of comparison performed with the equality operator (==), differs with reference and value types.

When two value types are compared, they are compared for value equality. They are equal if they hold the same value.

When two reference types are compared, they are compared for referential equality. They are equal if they refer to the same location in memory.

// int is a value type, so == uses value equality:
int num1 = 9;
int num2 = 9;
Console.WriteLine(num1 == num2);
// Prints true

// All classes are reference types, so == uses reference equality:
WorldCupTeam japan = new WorldCupTeam(2018);
WorldCupTeam brazil = new WorldCupTeam(2018);
Console.WriteLine(japan == brazil);
// Prints false
// This is because japan and brazil refer to two different locations in memory (even though they contain objects with the same values):
86
Q

Learn C#: References

C# Override

A

In C#, the override modifier allows base class references to a derived object to access derived methods.

In other words: If a derived class overrides a member of its base class, then the overridden version can be accessed by derived references AND base references.

// In the below example, DerivedClass.Method1() overrides BaseClass.Method1(). bcdc is a BaseClass-type reference to a DerivedClass value. Calling bcdc.Method1() invokes DerivedClass.Method1().

class MainClass {
  public static void Main (string[] args) {
    BaseClass bc = new BaseClass();
    DerivedClass dc = new DerivedClass();
    BaseClass bcdc = new DerivedClass();
    bc.Method1();
    dc.Method1();
    bcdc.Method1();
  }
}

class BaseClass  
{  
    public virtual void Method1()  
    {  
        Console.WriteLine("Base - Method1");  
    }  
}  

class DerivedClass : BaseClass  
{  
    public override void Method1()  
    {  
        Console.WriteLine("Derived - Method1");  
    }  
}  

// The above code produces this result:
// Base - Method1
// Derived - Method1
// Derived - Method1

// If we wanted bcdc.Method1() to invoked BaseClass.Method1(), then we would label DerivedClass.Method1() as new, not override.
87
Q

Learn C#: References

C# Object Class

A

In C#, the base class of all types is the Object class. Every class implicitly inherits this class.

When you create a class with no inheritance, C# implicitly makes it inherit from Object.

// When you write this code:
class Dog {}
// C# assumes you mean:
class Dog : Object {}

//Even if your class explicitly inherits from a class that is NOT an Object, then some class in its class hierachy will inherit from Object. In the below example, Dog inherits from Pet, which inherits from Animal, which inherits from Object:
class Dog : Pet {}
class Pet : Animal {}
class Animal {}

//Since every class inherits from Object, any instance of a class can be referred to as an Object.
Dog puppy = new Dog();
Object o = puppy;
88
Q

Learn C#: References

C# Object Class Methods

A

In C#, the Object class includes definitions for these methods: ToString(), Equals(Object), and GetType().

Object obj = new Object();
Console.WriteLine(obj.ToString());
// The example displays the following output:
//      System.Object

public static void Main()
{
	MyBaseClass myBase = new MyBaseClass();
  MyDerivedClass myDerived = new MyDerivedClass();
  object o = myDerived;
  MyBaseClass b = myDerived;

	Console.WriteLine("mybase: Type is {0}", myBase.GetType());
  Console.WriteLine("myDerived: Type is {0}", myDerived.GetType());
  Console.WriteLine("object o = myDerived: Type is {0}", o.GetType());
  Console.WriteLine("MyBaseClass b = myDerived: Type is {0}", b.GetType());
}

// The example displays the following output:
//    mybase: Type is MyBaseClass
//    myDerived: Type is MyDerivedClass
//    object o = myDerived: Type is MyDerivedClass
//    MyBaseClass b = myDerived: Type is MyDerivedClass
89
Q

Learn C#: References

C# ToString() Method

A

When a non-string object is printed to the console with Console.WriteLine(), its ToString() method is called.

Random r = new Random();

// These two lines are equivalent:
Console.WriteLine(r);
Console.WriteLine(r.ToString());
90
Q

Learn C#: References

C# String Comparison

A

In C#, string is a reference type but it can be compared by value using ==.

//In this example, even if s and t are not referentially equal, they are equal by value:
string s = "hello";
string t = "hello";

// b is true
bool b = (s == t);
91
Q

Learn C#: References

C# String Types Immutable

A

In C#, string types are immutable, which means they cannot be changed after they are created.

// Two examples demonstrating how immutablility determines string behavior. In both examples, changing one string variable will not affect other variables that originally shared that value.

//EXAMPLE 1
string a = "Hello?";
string b = a;
b = "HELLLLLLLO!!!!";

Console.WriteLine(b);
// Prints "HELLLLLLLO!!!!"

Console.WriteLine(a);
// Prints "Hello?"

//EXAMPLE 2
string s1 = "Hello ";
string s2 = s1;
s1 += "World";

System.Console.WriteLine(s2);
// Prints "Hello "
92
Q

Learn C#: References

C# Empty String

A

In C#, a string reference can refer to an empty string with “” and String.Empty.

This is separate from null and unassigned references, which are also possible for string types.

// Empty string:
string s1 = "";

// Also empty string:
string s2 = String.Empty;

// This prints true:
Console.WriteLine(s1 == s2);

// Unassigned:
string s3;

// Null:
string s4 = null;
93
Q

Learn C#: Lists and LINQ

Lists in C#

A

In C#, a list is a generic data structure that can hold any type. Use the new operator and declare the element type in the angle brackets < >.

In the example code, names is a list containing string values. someObjects is a list containing Object instances.

List<string> names = new List<string>();
List<Object> someObjects = new List<Object>();
94
Q

Object Initialization

Object Initialization

A

Values can be provided to a List when it is constructed in a process called object initialization.

Instead of parentheses, use curly braces after the list’s type.

Note that this can ONLY be used at the time of construction.

List<string> cities = new List<string> { "Los Angeles", "New York City", "Dubai" };
95
Q

Learn C#: References

Generic Collections

A

Some collections, like lists and dictionaries, can be associated with various types. Instead of defining a unique class for each possible type, we define them with a generic type T, e.g. List<T>.</T>

These collections are called generic collection types. They are available in the System.Collections.Generic namespace.

The generic type T will often show up in documentation. When using a generic collection in your code, the actual type is specified when the collection is declared or instantiated.

96
Q

Learn C#: References

Generic Collections

A

Some collections, like lists and dictionaries, can be associated with various types. Instead of defining a unique class for each possible type, we define them with a generic type T, e.g. List<T>.</T>

These collections are called generic collection types. They are available in the System.Collections.Generic namespace.

The generic type T will often show up in documentation. When using a generic collection in your code, the actual type is specified when the collection is declared or instantiated.

using System.Collections.Generic;

List<string> names = new List<string>();
List<Object> objs = new List<Object>();
Dictionary<string,int> scores = new Dictionary<string, int>();
97
Q

Learn C#: References

Limitless Lists

A

Unlike a C# array, a C# list does not have a limited number of elements. You can add as many items as you like.

// Initialize array with length 2
string[] citiesArray = new string[2];
citiesArray[0] = "Los Angeles";
citiesArray[1] = "New York City";
citiesArray[2] = "Dubai"; // Error!

// Initialize list; no length needed
List<string> citiesList = new List<string>();
citiesList.Add("Los Angeles");
citiesList.Add("New York City");
citiesList.Add("Dubai");
98
Q

Learn C#: References

Count Property

A

The number of elements in a list is stored in the Count property.

In the example code, the Count of citiesList changes as we add and remove values.

List<string> citiesList = new List<string>();
citiesList.Add("Los Angeles");
Console.WriteLine(citiesList.Count);
// Output: 1

citiesList.Add("New York City");
Console.WriteLine(citiesList.Count);
// Output: 2

citiesList.Remove("Los Angeles");
Console.WriteLine(citiesList.Count);
// Output: 1
99
Q

Learn C#: References

Remove()

A

Elements of a list can be removed with the Remove() method. The method returns true if the item is successfully removed; otherwise, false.

In the example code, attempting to remove “Cairo” returns false because that element is not in the citiesList.

List<string> citiesList = new List<string>();
citiesList.Add("Los Angeles");
citiesList.Add("New York City");
citiesList.Add("Dubai");

result1 = citiesList.Remove("New York City");
// result1 is true

result2 = citiesList.Remove("Cairo");
// result2 is false
100
Q

Learn C#: References

Clear()

A

All elements of a list can be removed with the Clear() method. It returns nothing.

In the example code, the list is initialized with three items. After calling Clear(), there are zero items in the list.

List<string> citiesList = new List<string> { "Delhi", "Los Angeles", "Kiev" };
citiesList.Clear();

Console.WriteLine(citiesList.Count);
// Output: 0
101
Q

references

Contains()

A

In C#, the list method Contains() returns true if its argument exists in the list; otherwise, false.

In the example code, the first call to Contains() returns true because “New York City” is in the list. The second call returns false because “Cairo” is not in the list.

List<string> citiesList = new List<string> { "Los Angeles", "New York City", "Dubai" };

result1 = citiesList.Contains("New York City");
// result1 is true

result2 = citiesList.Contains("Cairo");
// result2 is false
102
Q

reference

List Ranges

A

Unlike elements in a C# array, multiple elements of a C# list can be accessed, added, or removed simultaneously. A group of multiple, sequential elements within a list is called a range.

Some common range-related methods are:

  • AddRange()
  • InsertRange()
  • RemoveRange()
string[] african = new string[] { "Cairo", "Johannesburg" };
string[] asian = new string[] { "Delhi", "Seoul" };
List<string> citiesList = new List<string>();

// Add two cities to the list
citiesList.AddRange(african);
// List: "Cairo", "Johannesburg"

// Add two cities to the front of the list
citiesList.InsertRange(0, asian);
// List: "Delhi", "Seoul", "Cairo", "Johannesburg"

// Remove the second and third cities from the list
citiesList.RemoveRange(1, 2);
// List: "Delhi", "Johannesburg"
103
Q

reference

LINQ

A

LINQ is a set of language and framework features for writing queries on collection types. It is useful for selecting, accessing, and transforming data in a dataset.

104
Q

reference

Using LINQ

A

LINQ features can be used in a C# program by importing the System.Linq namespace.

using System.Linq;
105
Q

reference

var

A

Since the type of an executed LINQ query’s result is not always known, it is common to store the result in an implicitly typed variable using the keyword var.

var custQuery = from cust in customers
                where cust.City == "Phoenix"
                select new { cust.Name, cust.Phone };
106
Q

reference

Method & Query Syntax

A

In C#, LINQ queries can be written in method syntax or query syntax.

Method syntax resembles most other C# method calls, while query syntax resembles SQL.

// Method syntax
var custQuery2 = customers.Where(cust => cust.City == "London");

// Query syntax
var custQuery =  
    from cust in customers  
    where cust.City == "London"  
    select cust;
107
Q

reference

Where

A

In LINQ queries, the Where operator is used to select certain elements from a sequence.

  • It expects an expression that evaluates to a boolean value.
  • Every element satisfying the condition will be included in the resulting query.
  • It can be used in both method syntax and query syntax.
List<Customer> customers = new List<Customer>
{
  new Customer("Bartleby", "London"),
  new Customer("Benjamin", "Philadelphia"),
  new Customer("Michelle", "Busan" )
};

// Query syntax
var custQuery =  
    from cust in customers  
    where cust.City == "London"  
    select cust;

// Method syntax
var custQuery2 = customers.Where(cust => cust.City == "London");

// Result: Customer("Bartleby", "London")
108
Q

reference

From

A

In LINQ queries, the from operator declares a range variable that is used to traverse the sequence. It is only used in query syntax.

In the example code, n represents each element in names. The returned query only contains those elements for which n.Contains(“a”) is true.

string[] names = { "Hansel", "Gretel", "Helga", "Gus" };

var query =
  from n in names
  where n.Contains("a")
  select n;

// Result: Hansel, Helga
109
Q

reference

Select

A

In LINQ queries, the Select operator determines what is returned for each element in the resulting query. It can be used in both method and query syntax.

string[] trees = { "Elm", "Banyon", "Rubber" };

// Query syntax
var treeQuery =
  from t in trees
  select t.ToUpper();

// Method syntax
var treeQuery2 = names.Select(t => t.ToUpper());

// Result: ELM, BANYON, RUBBER
110
Q

reference

LINQ & foreach

A

You can use a foreach loop to iterate over the result of an executed LINQ query.

In the example code, query is the result of a LINQ query, and it can be iterated over using foreach. name represents each element in names.

string[] names = { "Hansel", "Gretel", "Helga", "Gus" };

var query = names.Where(n => n.Contains("a"));
  
foreach (var name in query)
{
  Console.WriteLine(name);
}
111
Q

reference

Count()

A

The result of an executed LINQ query has a method Count(), which returns the number of elements it contains.

In the example code, Count() returns 2 because the resulting query contains 2 elements containing “a”.

string[] names = { "Hansel", "Gretel", "Helga", "Gus" };

var query = names.Where(x => x.Contains("a"));

Console.WriteLine(query.Count());
// Output: 2
112
Q

What is ASP.NET Razor Pages?

Discover how the C# language and the ASP.NET framework are used to build websites and web apps

A

According to Microsoft, the makers of the software, ASP.NET is: “an open source web framework…for building modern web apps and services with .NET.”

So, ASP.NET is something that goes on top of .NET to build a specific type of program: web apps and services. “Web apps” and “web services” are involved in nearly everything that you encounter on the internet. Web sites, e-mail, downloading an app on your phone, anything that deals with HTTP requests and responses — those all use some kind of web app or web service. This article focuses on using ASP.NET to build websites, which we’ll also call web apps (there’s a difference, but we won’t get into it now).

Let’s say we want to build a web app of our own. We can choose nearly any programming language, but let’s say we pick C#. If we build a program with C#, we’ll probably use the .NET platform. Since our program is a web app, we’ll use ASP.NET!

If you’d like more details, here are some of the tools included in ASP.NET:

  • A base framework for processing web requests in C# or F#
  • A front-end syntax, known as Razor, for building dynamic web pages using C#
  • Libraries for common web patterns, such as Model View Controller (MVC)
  • Authentication system that includes libraries, a database, and template pages for handling logins
  • Editor extensions to provide syntax highlighting, code completion, and other functionality specifically for developing web pages

Using ASP.NET, you can build web apps in a number of different ways — the same way a “flying machine” can be built as a jet plane or a helicopter, or a “floor-cleaning machine” can be built as a broom or a vacuum. We call these different ways architectures or patterns. We’ll focus on one: the Razor Pages architecture.

The Razor Pages architecture goes like this: Every page of our website is represented by two files:

A view page, that displays information, and
A page model, which handles the accessing and processing of information.
For example, say that you have a bakery website that handles online orders. When users visit the site, they see a page containing a menu and a form to input an order. The way that the menu and form are displayed is defined in the view page. How the menu is accessed and how the order is handled are defined in the corresponding page model.

Razor Pages can also be used to make things other than web pages, like APIs and microservices. (Remember when Microsoft said ASP.NET is good for web apps AND services?) In those cases we wouldn’t need a view page, we’d just use page models.

113
Q

ASP.NET: Razor Syntax

Razor Syntax

A

Razor Syntax allows you to embed code (C#) into page views through the use of a few keywords (such as “@”), and then have the C# code be processed and converted at runtime to HTML. In other words, rather than coding static HTML syntax in the page view, a user can code in the view in C# and have the Razor engine convert the C# code into HTML at runtime, creating a dynamically generated HTML web page.

@page
@model IndexModel
<h2>Welcome</h2>

<ul>
  @for (int i = 0; i < 3; i++)
  {
    <li>@i</li>
  }
</ul>
114
Q

ASP.NET: Razor Syntax

The @page Directive

A

In a Razor view page (.cshtml), the @page directive indicates that the file is a Razor Page.

In order for the page to be treated as a Razor Page, and have ASP.NET parse the view syntax with the Razor engine, the directive @page should be added at the top of the file.

There can be empty space before the @page directive, but there cannot be any other characters, even an empty code block.

@page
@model IndexModel

<h1>Welcome to my Razor Page</h1>
<p>Title: @Model.Title</p>
115
Q

ASP.NET: Razor Syntax

The @model Directive

A

The page model class, i.e. the data and methods that hold the functionality associated with a view page, is made available to the view page via the @model directive.

By specifying the model in the view page, Razor exposes a Model property for accessing the model passed to the view page. We can then access properties and functions from that model by using the keyword Model or render its property values on the browser by prefixing the property names with @Model, e.g. @Model.PropertyName.

@page
@model PersonModel

// Rendering the value of FirstName in PersonModel
<p>@Model.FirstName</p>

<ul>
  // Accessing the value of FavoriteFoods in PersonModel
  @foreach (var food in Model.FavoriteFoods)
  {
    <li>@food</li>
  }
</ul>
116
Q

ASP.NET: Razor Syntax

Razor Markup

A

Razor pages use the @ symbol to transition from HTML to C#. C# expressions are evaluated and then rendered in the HTML output. You can use Razor syntax under the following conditions:

Anything immediately following the @ is assumed to be C# code.

Code blocks must appear within @{ … } brackets.

A single line of code that uses spaces should be surrounded by parentheses, ( ).

@page
@model PersonModel

// Using the `@` symbol:
<h1>My name is @Model.FirstName and I am @Model.Age years old </h1>

// Using a code block:
@{
  var greet = "Hey threre!";
  var name = "John";
  <h1>@greet I'm @name!</h1>
}

// Using parentheses:
<p>Last week this time: @(DateTime.Now - TimeSpan.FromDays(7))</p>
117
Q

ASP.NET: Razor Syntax

Razor Conditionals

A

Conditionals in Razor code can be written pretty much the same way you would in regular C# code. The only exception is to prefix the keyword if with the @ symbol. Afterward, any else or else if conditions doesn’t need to be preprended with the @ symbol.

// if-else if-else statment:
@{ var time = 9; }

@if (time < 10) 
{
  <p>Good morning, the time is: @time</p>
} 
else if (time < 20) 
{
  <p>Good day, the time is: @time</p>
}
else 
{
  <p>Good evening, the time is: @time</p>
}
118
Q

ASP.NET: Razor Syntax

Razor Switch Statements

A

In Razor Pages, a switch statement begins with the @ symbol followed by the keyword switch. The condition is then written in parentheses and finally the switch cases are written within curly brackets, {}.

@{ string day = "Monday"; }
@switch (day)
{
  case "Saturday":
    <p>Today is Saturday</p>
    break;
  case "Sunday":
    <p>Today is Sunday</p>
    break;
  default:
    <p>Today is @day... Looking forward to the weekend</p>
    break;
}
119
Q

ASP.NET: Razor Syntax

Razor For Loops

A

In Razor Pages, a for loop is prepended by the @ symbol followed by a set of conditions wrapped in parentheses. The @ symbol must be used when referring to C# code.

@{
  List<string> avengers = new List<string>()
  {
    "Spiderman",
    "Iron Man",
    "Hulk",
    "Thor",
  };
}

<h1>The Avengers Are:</h1>

@for (int i = 0; i < @avengers.Count; i++)
{
  <p>@avengers[i]</p>
}
120
Q

ASP.NET: Razor Syntax

Razor Foreach Loops

A

In Razor Pages, a foreach loop is prepended by the @ symbol followed by a set of conditions wrapped in parentheses. Within the conditions, we can create a variable that will be used when rendering its value on the browser.

@{
  List<string> avengers = new List<string>()
  {
    "Spiderman",
    "Iron Man",
    "Hulk",
    "Thor",
  };
}

<h1>The Avengers Are:</h1>

@foreach (var avenger in avengers)
{
    <p>@avenger</p>
}
121
Q

ASP.NET: Razor Syntax

Razor While Loops

A

A while loop repeats the execution of a sequence of statements as long as a set of conditions is true, once the condition becomes false we break out of the loop.

When writing a while loop, we must prepend the keyword while with the @ symbol and write the condition within parentheses.

@{ int i = 0; }

@while (i < 5)
{
  <p>@i</p>
  i++;
}
122
Q

ASP.NET: Razor Syntax

Razor While Loops

A

A while loop repeats the execution of a sequence of statements as long as a set of conditions is true, once the condition becomes false we break out of the loop.

When writing a while loop, we must prepend the keyword while with the @ symbol and write the condition within parentheses.

@{ int i = 0; }

@while (i < 5)
{
  <p>@i</p>
  i++;
}
123
Q

ASP.NET: Razor Syntax

Razor View Data

A

In Razor Pages, you can use the ViewData property to pass data from a Page Model to its corresponding view page, as well as share it with the layout, and any partial views.

ViewData is a dictionary that can contain key-value pairs where each key must be a string. The values can be accessed in the view page using the @ symbol.

A huge benefit of using ViewData comes when working with layout pages. We can easily pass information from each individual view page such as the title, into the layout by storing it in the ViewData dictionary in a view page:

@{ ViewData[“Title”] = “Homepage” }

We can then access it in the layout like so: ViewData[“Title”]. This way, we don’t need to hardcode certain information on each individual view page.

// Page Model: Index.cshtml.cs
public class IndexModel : PageModel
{
  public void OnGet()
  {
    ViewData["Message"] = "Welcome to my page!";
    ViewData["Date"] = DateTime.Now();
  }
}

// View Page: Index.cshtml
@page
@model IndexModel

<h1>@ViewData["Message"]</h1>
<h2>Today is: @ViewData["Date"]</h2>
124
Q

ASP.NET: Razor Syntax

Razor Shared Layouts

A

In Razor Pages, you can reduce code duplication by sharing layouts between view pages. A default layout is set up for your application in the _Layout.cshtml file located in Pages/Shared/.

Inside the _Layout.cshtml file there is a method call: RenderBody(). This method specifies the point at which the content from the view page is rendered relative to the layout defined.

If you want your view page to use a specific Layout page you can define it at the top by specifying the filename without the file extension: @{ Layout = “LayoutPage” }

// Layout: _LayoutExample.cshtml
<body>
    ...
<div class="container body-content">
  @RenderBody() 
  <footer>
    <p>@DateTime.Now.Year - My ASP.NET Application</p>
  </footer>
</div>
</body>

// View Page: Example.cshtml
@page
@model ExampleModel

@{ Layout = "_LayoutExample" }

<h1>This content will appear where @RenderBody is called!</h1>
125
Q

ASP.NET: Razor Syntax

Razor Tag Helpers

A

In Razor Pages, Tag Helpers change and enhance existing HTML elements by adding specific attributes to them. The elements they target are based on the element name, the attribute name, or the parent tag.

ASP.NET provides us with numerous built-in Tag Helpers that can be used for common tasks - such as creating forms, links, loading assets, and more.

// Page Model: Example.cshtml.cs
public class ExampleModel : PageModel
{
  public string Language { get; set; }

  public List<SelectListItem> Languages { get; } = new List<SelectListItem>
  {
    new SelectListItem { Value = "C#", Text = "C#" },
    new SelectListItem { Value = "Javascript", Text = "Javascript" },
    new SelectListItem { Value = "Ruby", Text = "Ruby"  },
  };
}

// View Page: Example.cshtml
<h1>Select your favorite language!</h1>
<form method="post">
  // asp-for:  The name of the specified model property.
  // asp-items: A collection of SelectListItemoptions that appear in the select list.
  <select asp-for="Language" asp-items="Model.Languages"></select>
  <br />
  <button type="submit">Register</button>
</form>

// HTML Rendered:
<form method="post">
  <select id="Language" name="Language">
    <option value="C#">C#</option>
    <option value="Javascript">Javascript</option>
    <option value="Ruby">Ruby</option>
    <br>
  </select>
  <button type="submit">Register</button>
</form>
126
Q

ASP.NET: Razor Syntax

Razor View Start File

A

When creating a template with ASP.NET, a ViewStart.cshtml file is automatically generated under the /Pages folder.

The ViewStart.cshtml file is generally used to define the layout for the website but can be used to define common view code that you want to execute at the start of each View’s rendering. The generated file contains code to set up the main layout for the application.

// ViewStart.cshtml
@{
  Layout: "_Layout"
}
127
Q

ASP.NET: Razor Syntax

Razor View Imports

A

The _ViewImports.cshtml file is automatically generated under /Pages when we create a template with ASP.NET.

Just like the _ViewStart.cshtml file, _ViewImports.cshtml is invoked for all your view pages before they are rendered.

The purpose of the file is to write common directives that our view pages need. ASP.NET currently supports a few directives that can be added such as: @namespace, @using, @addTagHelpers, and @inject amongst a few other ones. Instead of having to add them individually to each page, we can place the directives here and they’ll be available globally throughout the application.

// _ViewImports.cshtml
@using YourProject
@namespace YourProject.Pages
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
128
Q

ASP.NET: Razor Syntax

Razor Partials

A

Partial views are an effective way of breaking up large views into smaller components and reduce complexity. A partial consists of fragments of HTML and server-side code to be included in any number of pages or layouts.

We can use the Partial Tag Helper, <partial>, in order to render a partial’s content in a view page.</partial>

// _MyPartial.cshtml
<form method="post">
  <input type="email" name="emailaddress"> 
  <input type="submit">
</form>

// Example.cshtml
<h1> Welcome to my page! </h1>
<h2> Fill out the form below to subscribe!:</h2>
<partial name="_MyPartial" />
129
Q

ASP.NET: Page Models

asp-for

A

The asp-for attribute is used to connect an <input></input> element to a page model property.

The above example would be connected to a Username property in the page model:

public class IndexModel : PageModel
{
  [BindProperty]
  public string Username { get; set; }
}

In the rendered HTML, attributes like type, id, and name will be added to the <input></input> tag:

Enter a username:
<input type="text" id="Username" name="Username" >
<!-- In .cshtml file -->
Enter a username: <input asp-for="Username" />
130
Q

ASP.NET: Page Models

URLs in Razor Pages

A
131
Q

ASP.NET: Page Models

OnGet() & OnGetAsync()

A

When a page model receives a GET request, its OnGet() or OnGetAsync() method is invoked. This typically happens when a user navigates to the page model’s corresponding view page.

A page model must have either OnGet() or OnGetAsync(). It cannot have both.

public class ZooModel : PageModel
{
  public string FavoriteAnimal { get; set; }

  // Sets FavoriteAnimal when page is requested
  public void OnGet()
  {
    FavoriteAnimal = "Hippo";
  }
}
132
Q

ASP.NET: Page Models

OnPost() & OnPostAsync()

A

When a page model receives a POST request, its OnPost() or OnPostAsync() method is invoked. This typically happens when a user submits a form on the page model’s corresponding view page.

A page model must have either OnPost() or OnPostAsync(). It cannot have both.

public class IndexModel : PageModel
{
  public string Message { get; set; }

  public void OnPost()
  {
    Message = "OnPost() called!";
  }
}
133
Q

ASP.NET: Page Models

Void Handler Methods

A

In a page model, synchronous handler methods like OnGet() and OnPost() that have no return statement will have a return type of void.

This results in the current page being rendered in response to every request.

public class IndexModel : PageModel
{
  public string Username { get; set; }

  public void OnGet()
  { 
    Username = "n/a";
  }

  public void OnPost(string username)
  {  
    Username = username;
  }
}
134
Q

ASP.NET: Page Models

Task Handler Methods

A

In a page model, asynchronous handler methods like OnGetAsync() and OnPostAsync() that have no return statement will have a return type of Task.

This results in the current page being rendered in response to every request.

public class IndexModel : PageModel
{
  public string Users { get; set; }
  private UserContext _context { get; set; }

  public IndexModel(UserContext context)
  {
    _context = context;
  }

  // Task return type
  public async Task OnGetAsync()
  { 
    Users = await _context.Users.ToListAsync();
  }

  // Task return type
  public async Task OnPostAsync(string username)
  {  
    _context.Users.Add(username);
    await _context.SaveChangesAsync();
  }
}
135
Q

ASP.NET: Page Models

Handler Method Parameters

A

Page model handler methods, like OnGet(), OnGetAsync(), OnPost(), and OnPostAsync(), can access an incoming HTTP request’s query string via its own method parameters.

The name of the method parameter(s) must match (case-insensitive) the name(s) in the query string.

// Example GET request
// https://localhost:8000/Songs?id=1
public async Task OnGetAsync(int id)
{ 
  // id is 1
}

// Example POST request
// https://localhost:8000/Songs?songName=Say%20It%20Loud
public async Task OnPostAsync(string songName)
{  
  // songName is "Say It Loud"
}
136
Q

ASP.NET: Page Models

Model Binding

A

In model binding, a page model retrieves data from an HTTP request, converts the data to .NET types, and updates the corresponding model properties. It is enabled with the [BindProperty] attribute.

public class IndexModel : PageModel
{
  [BindProperty]
  public string Username { get; set; }
  
  [BindProperty]
  public bool IsActive { get; set; }
  
  // Example POST
  // https://localhost:8000?username=muhammad&IsActive=true
  public void OnPost()
  {
    // Username is "muhammad"
    // IsActive is true
  }
}
137
Q

Append URL Segments

Append URL Segments

A

In Razor view pages (.cshtml files), the @page directive can be used to add segments to a page’s default route. Use this feature by typing a string after @page.

For example, imagine the below code is from About.cshtml. Instead of /About, the new route would be /About/Me:

@page "Me"

@page "segment"
138
Q

ASP.NET: Page Models

Append URL Parameters

A
139
Q

ASP.NET: Page Models

Append URL Parameters

A
140
Q

ASP.NET: Page Models

asp-route-{value}

A
141
Q

ASP.NET: Page Models

Default Responses

A

In page models, a handler method with no return statement will respond to HTTP requests by sending back the associated page.

In the above example, IndexModel is associated with Index.cshtml. Neither OnGet() nor OnPostAsync() have return statements, so they both return Index.cshtml.

public class IndexModel : PageModel
{
  // Sends Index.cshtml
  public void OnGet()
  { }

  // Sends Index.cshtml
  public void OnPost()
  {  }
}
142
Q

ASP.NET: Page Models

Page()

A

To return the view page associated with a page model, use Page() in the page model’s handler methods.

  • This happens implicitly if the handler method has a void return type
  • If a handler method calls Page(), its return type is typically IActionResult or Task<IActionResult> (although others exist).</IActionResult>
public class AboutModel : PageModel
{
  // Sends About.cshtml
  public IActionResult OnGet()
  {
    return Page();
  }
}
143
Q

ASP.NET: Page Models

RedirectToPage()

A

To redirect users to a different Razor page within the application, use RedirectToPage() in the page model’s handler methods.

  • If a handler method calls RedirectToPage(), its return type is typically IActionResult or Task<IActionResult> (although others exist).</IActionResult>
  • The string argument passed to this method is a file path. “/Index” is a relative path and “./Index” is an absolute path.
public class IndexModel : PageModel
{
  // Sends Privacy.cshtml
  public IActionResult OnPost()
  {
    return RedirectToPage("./Privacy");
  }
}
144
Q

ASP.NET: Page Models

NotFound()

A

To send a “Status 404 Not Found” response, use NotFound() in the page model’s handler methods.

If a handler method calls NotFound(), its return type is typically IActionResult or Task<IActionResult> (although others exist).</IActionResult>

public class EditModel : PageModel
{
  public async Task<IActionResult> OnGetAsync(int? id)
  {
    if (id == null)
    {
      return NotFound();
    }
    
    // do something with id here
    
    return Page();
  }
}
145
Q

ASP.NET: Databases

Database Model

A

Entity Framework uses C# classes to define the database model. This is an in-memory representation of data stored in a database table. Several model classes combine to form the schema for the database.

Each property maps to a column in a database table. The bottom line in the example shows a type of Continent which implies a relationship to another table.

using System;

public class Country
{
  public string ID { get; set; }
  public string ContinentID { get; set; }
  public string Name { get; set; }
  public int? Population { get; set; }
  public int? Area { get; set; }
  public DateTime? UnitedNationsDate { get; set; }
        
  public Continent Continent { get; set; }
}
146
Q

ASP.NET: Databases

Database Context

A

The Entity Framework database context is a C# class that provides connectivity to an external database for an application. It relies on the Microsoft.EntityFrameworkCore library to define the DB context which maps model entities to database tables and columns.

The DbContextOptions are injected into the context class via the constructor. The options allow configuration changes per environment so the Development DB is used while coding and testing but the Production DB would be referenced for real work.

The DbSet is an in-memory representation of a table or view which has a number of member methods that can return a List<T> of records or a single record.</T>

using Microsoft.EntityFrameworkCore;

public class CountryContext : DbContext
{
  public CountryContext(DbContextOptions<CountryContext> options)
      : base(options)
  {
  }

  public DbSet<Country> Countries { get; set; }
  public DbSet<Continent> Continents { get; set; }

  protected override void OnModelCreating(ModelBuilder modelBuilder)
  {
    modelBuilder.Entity<Country>().ToTable("Country");
    modelBuilder.Entity<Continent>().ToTable("Continent");
  }
}
147
Q

ASP.NET: Databases

DbSet Type

A

The Entity Framework type DbSet represents a database table in memory. It is typically used with a <T> qualifier. The type, or T, is one of your database model classes. The ModelBuilder binds each database table entity to a corresponding DbSet.</T>

DbSet has a number of member methods that can return a List<T> of records or a single record.</T>

148
Q

ASP.NET: Databases

Entity Framework Configuration

A

In ASP.NET Core, a database may be connected to a web app using Entity Framework. There are four common steps for any setup:

  1. Define one or more database model classes and annotate them
  2. Define a database context class that uses DbSet to map entities to tables
  3. Define a database connection string in appsettings.json
  4. Add the Entity Framework service in Startup.ConfigureServices()
149
Q

ASP.NET: Databases

Database Connection String

A

The Entity Framework context depends on a database connection string that identifies a physical database connection. It is typically stored in appsettings.json. You can define multiple connection strings for different environments like Development, Test, or Production.

Each database product has specific requirements for the syntax of the connection string. This might contain the database name, user name, password, and other options.

150
Q

ASP.NET: Page Models

Default Responses

A

In page models, a handler method with no return statement will respond to HTTP requests by sending back the associated page.

In the above example, IndexModel is associated with Index.cshtml. Neither OnGet() nor OnPostAsync() have return statements, so they both return Index.cshtml.

public class IndexModel : PageModel
{
  // Sends Index.cshtml
  public void OnGet()
  { }

  // Sends Index.cshtml
  public void OnPost()
  {  }
}
151
Q

ASP.NET: Databases

Creating the Schema

A

Entity Framework provides command-line tools that help manage the connected database. Use these commands in the bash shell or Windows command prompt to create an initial database file and schema. This will read the context class and evaluate each database model represented by a DbSet. The SQL syntax necessary to create all schema objects is then generated and executed.

dotnet ef migrations add InitialCreate
dotnet ef database update
152
Q

ASP.NET: Databases

Model Binding

A

In ASP.NET Core, model binding is a feature that simplifies capturing and storing data in a web app. The process of model binding includes retrieving data from various sources, converting them to collections of .NET types, and passing them to controllers/page models. Helpers and attributes are used to render HTML with the contents of bound page models. Client- and server-side validation scripts are used to ensure integrity during data entry.

153
Q

ASP.NET: Databases

Adding Records

A

The Entity Framework context DbSet member provides the Add() and AddAsync() methods to insert a new record into the in-memory representation of the corresponding database table. A batch of multiple records can also be added in this fashion.

The record is passed from the browser in the <form> post back. In this case a Country member is declared with a [BindProperty] attribute so the entire record is passed back to the server.

Use the EF context SaveChanges() or SaveChangesAsync() methods to persist all new records to the database table.

154
Q

ASP.NET: Databases

Saving Changes

A

The Entity Framework context DbSet member provides the Attach() method to update an existing record, the Add() method to insert a new record, and the Remove() method to delete an existing record. Any combination of multiple records can batched before saving.

Use the EF context SaveChanges() or SaveChangesAsync() methods to persist all inserted, updated, and deleted records to the database table.

155
Q

ASP.NET: Databases

Finding Records

A

The Entity Framework context DbSet member provides the Find() and FindAsync() methods to retrieve an existing record from the in-memory representation of the database table. Assign the result of this method to a local member in the page model.

This method generates the appropriate SQL syntax needed to access the record in the database table.

156
Q

ASP.NET: Databases

Deleting Records

A

The Entity Framework context DbSet member provides the Remove() method to delete an existing record from the in-memory representation of the database table. Any combination of multiple record deletions can be batched before saving.

Use the EF context SaveChanges() or SaveChangesAsync() methods to persist all deletions to the database table.

157
Q

ASP.NET: Databases

Updating Records

A

The Entity Framework context DbSet member provides the Attach() method to update an existing record in the in-memory representation of the corresponding database table. A batch of multiple records can also be updated in this fashion.

The record is passed from the browser in the <form> post back. In this case a Country member is declared with a [BindProperty] attribute so the entire record is passed back to the server.

Use the EF context SaveChanges() or SaveChangesAsync() methods to persist all updated records to the database table.

158
Q

ASP.NET: Databases

Valid Model State

A

Entity Framework database models accept annotations that drive data validation at the property level. If you are using the asp-validation-for or asp-validation-summary HTML attributes, validation is handled client-side with JavaScript. The model is validated and the <form> post back won’t occur until that model is valid.

Sometimes the client-side validation will not be available so it is considered best practice to also validate the model server-side, inside the OnPostAsync() method. This example checks for ModelState.IsValid and returns the same page if it is false. This effectively keeps the user on the same page until their entries are valid.

If the model is valid, the insert, update, or delete can proceed followed by SaveChangesAsync() to persist the changes.

159
Q

ASP.NET: Databases

Valid Model State

A

Entity Framework database models accept annotations that drive data validation at the property level. If you are using the asp-validation-for or asp-validation-summary HTML attributes, validation is handled client-side with JavaScript. The model is validated and the <form> post back won’t occur until that model is valid.

Sometimes the client-side validation will not be available so it is considered best practice to also validate the model server-side, inside the OnPostAsync() method. This example checks for ModelState.IsValid and returns the same page if it is false. This effectively keeps the user on the same page until their entries are valid.

If the model is valid, the insert, update, or delete can proceed followed by SaveChangesAsync() to persist the changes.

160
Q

ASP.NET: Databases

Validation Attribute

A

The asp-for attribute in an <input></input> element will render HTML and JavaScript that handle the display and data entry for a field based on the model annotations. The JavaScript will set the valid flag on the field.

The asp-validation-for attribute in a <span> element will display any error message generated when the property annotations are not valid.</span>

In this example, the <span> be rendered as this HTML:</span>

161
Q

ASP.NET: Databases

[Display] Attribute

A

The [Display] attribute specifies the caption for a label, textbox, or table heading.

Within a Razor Page, the @Html.DisplayForName() helper defaults to the property name unless the [Display] attribute overrides it. In this case, Continent is displayed instead of the more technical ContinentID.

162
Q

ASP.NET: Databases

[DisplayFormat] Attribute

A

The [DisplayFormat] attribute can explicitly apply a C# format string. The optional ApplyFormatInEditMode means the format should also apply in edit mode.

[DisplayFormat] is often used in combination with the [DataType] attribute. Together they determine the rendered HTML when using the @Html.DisplayFor() helper.

163
Q

ASP.NET: Database

[DataType] Attribute

A

The [DataType] attribute specifies a more specific data type than the database column type. In this case, the database table will use a DateTime column but the render logic will only show the date.

The @Html.DisplayFor() helper knows about types and will render a default format to match the type. In this case, the HTML5 browser date picker will appear when editing the field.

164
Q

ASP.NET: Database

[Required] Attribute

A

The [Required] attribute can be applied to one or more properties in a database model class. EF will create a NOT NULL column in the database table for the property.

The client-side JavaScript validation scripts will ensure that a non-empty string or number is valid before posting the record from the browser on inserts and updates.

165
Q

ASP.NET: Database

[RegularExpression] Attribute

A

The [RegularExpression] attribute can apply detailed restrictions for data input. The match expression is evaluated during data entry and the result returns true or false. If false, the model state will not be valid and the optional ErrorMessage will display.

In a Razor page, the @Html.DisplayFor() helper only shows the data in the field. The asp-validation-for attribute on a <span> tag displays the ErrorMessage.</span>

166
Q

ASP.NET: Database

[StringLength] Attribute

A

The [StringLength] attribute specifies the maximum length of characters that are allowed in a data field and optionally the minimum length. The model will not be flagged as valid if these restrictions are exceeded. In this case, the ContinentID must be exactly 2 characters in length.

In a Razor Page, the @Html.DisplayFor() helper only shows the data in the field. The client-side JavaScript validation scripts use the asp-validation-for attribute on a <span> tag to display a default error message.</span>

167
Q

ASP.NET: Database

[StringLength] Attribute

A

The [StringLength] attribute specifies the maximum length of characters that are allowed in a data field and optionally the minimum length. The model will not be flagged as valid if these restrictions are exceeded. In this case, the ContinentID must be exactly 2 characters in length.

In a Razor Page, the @Html.DisplayFor() helper only shows the data in the field. The client-side JavaScript validation scripts use the asp-validation-for attribute on a <span> tag to display a default error message.</span>

168
Q

ASP.NET: Database

[Range] Attribute

A

The [Range] attribute specifies the minimum and maximum values in a data field. The model will not be flagged as valid if these restrictions are exceeded. In this case, Population must be greater than 0 and less than the big number!

In a Razor page, the @Html.DisplayFor() helper only shows the data in the field. The client-side JavaScript validation scripts use the asp-validation-for attribute on a <span> tag to display a default error message.</span>

169
Q

ASP.NET: Database

Select List Items Attribute

A
170
Q

ASP.NET: Database

LINQ Queries

A

The Entity Framework DbSet entities can manage complex queries using C# LINQ syntax. This is referenced from the System.Linq library.

All of the Where() and OrderBy() clauses are evaluated in the final statement that calls ToListAsync(). EF evaluates all options and generates a SQL SELECT statement with corresponding WHERE and ORDERBY clauses.

171
Q

ASP.NET: Database

DisplayNameFor Helper

A