Chapter 2: Speaking C# [Flashcarder]

1
Q

What is the primary focus of learning the C# language?

A

The primary focus is on understanding the grammar and vocabulary used daily to write the source code for applications.

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

How are programming languages similar to human languages?

A

Programming languages, like human languages, have their own grammar and vocabulary. However, unlike most human languages, in programming languages, you can create your own words.

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

What is the significance of creating your own ‘words’ in programming languages, as illustrated by the book?

A

Creating your own words in programming languages, as illustrated by Dr. Seuss’s creativity, highlights the flexibility and creative potential within programming to invent new concepts and functionalities.

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

For whom is the book’s section on C# programming language primarily written?

A

It is primarily written for beginners and covers fundamental topics every developer needs to know.

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

Up to which version of the C# language does the book cover features?

A

The book covers features of the C# language from version 1 up to the latest version, 12.

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

What kind of assistance does the book offer to those familiar with older versions of C# but interested in newer versions?

A

The book makes it easier for those familiar with older versions to learn about new features in recent versions by listing language versions and their important new features, along with chapter numbers and topics where they are discussed.

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

How does the book support learning about C# standards over the years?

A

It discusses various C# versions that Microsoft submitted to standards bodies, providing details on ECMA and ISO/IEC standards for C# versions 1.0, 2.0, 5.0, and 6.0.

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

Where can the reader find the latest C# standard document and additional resources on C# language design and compiler implementation?

A

The latest C# standard document and additional resources on C# language design and compiler implementation can be found on Microsoft’s official documentation site and public GitHub repositories as listed in the book.

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

What is the significance of the .NET SDK version in relation to the default C# language version used?

A

The .NET SDK version determines the default C# language version available for use, with each SDK version supporting a specific range of C# versions, from older versions up to the most current at the time of the SDK’s release.

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

What are the versions of C# that have been submitted to standards bodies, and what are their respective ECMA and ISO/IEC standards?

*Optional question

A

C# 1.0 (ECMA-334:2003, ISO/IEC 23270:2003),
C# 2.0 (ECMA-334:2006, ISO/IEC 23270:2006),
C# 5.0 (ECMA-334:2017, ISO/IEC 23270:2018),
C# 6.0 (ECMA-334:2022, ISO/IEC 23270:2022).

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

As of the book’s publication, which C# version’s ECMA standard is still a draft, and what is implied about the standardization of future versions?

A

The ECMA standard for C# 7.3 is still a draft, implying that C# versions 8 through 12 might not yet have ECMA standards.

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

When did Microsoft make C# open source, and where can the latest C# standard document be found?

A

Microsoft made C# open source in 2014.
The latest C# standard document can be found at https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/specifications.

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

What resources are more practically useful than the ECMA standards for learning and contributing to C# and related technologies?

A

The public GitHub repositories for C# language design (https://github.com/dotnet/csharplang), compiler implementation (https://github.com/dotnet/roslyn), and the standard to describe the language (https://github.com/dotnet/csharpstandard) are more practically useful than the ECMA standards.

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

How is the .NET language compiler for C# and Visual Basic distributed?

A

The .NET language compiler for C# and Visual Basic, also known as Roslyn, along with a separate compiler for F#, is distributed as part of the .NET SDK.

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

What determines the version of C# you can use?

A

To use a specific version of C#, you must have at least that version of the .NET SDK installed.

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

Can projects targeting older versions of .NET use modern compiler versions?

A

Yes, projects targeting older versions of .NET can still use a modern compiler version if you have a minimum required version of the .NET SDK installed.
For example, with the .NET 7 SDK installed, you can use C# 11 language features in a console app that targets .NET Core 3.0.

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

What is the relationship between .NET SDK versions and C# compiler versions?

A

Each .NET SDK version comes with a specific range of Roslyn compiler versions, which in turn supports a default C# language version.

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

How do .NET Standard versions relate to default C# compiler versions?

A

Similar to the .NET SDK, .NET Standard versions have associated default C# language versions, indicating the level of language features supported for targeting those standards.

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

How do you determine which version of the .NET SDK is installed on your machine?

A

Start Windows Terminal or Command Prompt on Windows, or Terminal on macOS, and enter the command:
dotnet --version

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

What does the .NET SDK version 8.0.100 indicate?

A

It indicates the initial version of the SDK for .NET 8, without any bug fixes or new features added after its initial release.

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

What is assumed by developer tools like Visual Studio and the dotnet CLI regarding the C# language compiler version?

A

They assume you want to use the latest major version of a C# language compiler by default.

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

How can you enable improvements in a specific C# point release, like 7.1, 7.2, or 7.3?

A

Add a <LangVersion> configuration element to the project file with the specific version you want to use, for example, <LangVersion>7.3</LangVersion>.

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

If Microsoft releases a C# 12.1 compiler, how do you use its new language features?

A

Add a <LangVersion> configuration element to your project file with the value 12.1.

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

What does setting <LangVersion> to latestmajor do?

A

It uses the highest major number version of the compiler available, for example, version 12 in November 2023.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
How does the **latest** setting differ from **latestmajor** in the `` configuration?
The ***latest*** setting uses the **highest major and minor number version** available, potentially enabling a minor version like 12.1 in the first half of 2024.
26
What is the effect of setting `` to **preview**?
It uses the **highest available preview** version of the compiler, like 12.0 in July 2023 with .NET 8 Preview 6 installed.
27
When did Microsoft release the first preview of **.NET 9 with a C# 13 compiler**?
In 2024.
28
How can you use the C# 13 compiler in your projects after installing the .NET 9 SDK preview?
By editing the **.csproj file** to add the `` element set to **preview**.
29
What does setting the `` to **preview** in your project file do?
It allows using the **preview C# 13 compiler**, enabling exploration of new language features.
30
Can you use a **future version of the C# compiler**, like C# 13, with .NET 8 projects?
**Yes**, you can use a future version of the C# compiler with .NET 8 projects by setting the `` appropriately in the project file.
31
What is the recommended practice for using **preview** versions of the C# compiler in projects?
**Preview** versions should only be set for **exploration**, **not production** projects, as they are not supported by Microsoft and are more likely to have **bugs**.
32
When is Microsoft expected to make the **.NET 9 SDK** generally available, and what does this mean for .NET 8 projects?
In **November 2024**, making it possible to use the C# 13 compiler in projects that continue to target .NET 8 by setting `` to 13.
33
What will be the default C# language version for projects targeting **.NET 9** after installing its SDK?
**C# 13** will be the default language version for **projects targeting .NET 9.**
34
What is a key consideration when using **new C# language features** with older versions of .NET?
Some new C# language features may require *changes in the underlying .NET libraries*, so **not all new features can be used when targeting older versions of .NET**.
35
What unique method is used to display the **compiler version** in the console app?
Add the `#error version` statement in the Program.cs file to trigger a compiler error that reveals the **compiler and language version.**
36
What information is revealed by the **compiler error CS8304**?
The error reveals the **compiler version** (e.g., '4.8.0...') and the default **language version** (12.0) as part of the error message.
37
What are the components of **C# grammar**?
C# grammar includes **statements** and **blocks**. Additionally, **comments** are used to document code.
38
Besides **comments**, what are some methods to document your code in C#?
Besides **comments**, sensible **naming** for variables and functions, writing **unit tests**, and creating actual **documentation** are recommended practices for documenting code.
39
How does C# indicate the **end of a statement**?
C# indicates the end of a statement with a semicolon (**;**).
40
How is an English sentence structure analogy used to explain C# statements?
Just as the order of words in an English sentence (e.g., placing adjectives before nouns) matters for clarity and meaning, the **order of types, variables, and expressions in C# statements is crucial** for the code's meaning and result.
41
What is an example of a **C# statement**, and what are its components?
An example of a C# statement is: `decimal totalPrice = subtotal + salesTax;` This statement includes: a **type** (*decimal*), a **variable** (*totalPrice*), and an **expression** (*subtotal + salesTax*) composed of **operands** (*subtotal, salesTax*) and an **operator** (*+*).
42
Why does the **order of operands and operators** matter in a C# expression?
The order affects the **meaning** and the **result** of the expression, similar to how word order affects meaning in natural language sentences.
43
What is the primary purpose of **comments** in code?
Comments are used to **document** code, **increasing understanding** of its functionality for others or for the original developer when revisiting the code later.
44
How do you add a **single-line comment** in C#?
Use a double slash `//` at the beginning of the comment. The compiler ignores everything after `//` until the end of the line.
45
How can you write a **multi-line comment** in C#?
Use `/*` at the beginning and `*/` at the end of the comment block.
46
Is it possible to use multi-line comment syntax for **commenting in the middle of a statement**? If so, how?
**Yes**, you can use /* and */ for commenting in the middle of a statement. For example: `decimal totalPrice = subtotal /* for this item */ + salesTax;`
47
What should you consider if you find yourself adding **too many comments** in your code?
Consider if the code can be **refactored** to be more understandable without lengthy comments. Well-designed code with clear function signatures and class encapsulation may reduce the need for extensive commenting.
48
How can you **add or remove comment characters** in Visual Studio 2022 and Visual Studio Code?
In *Visual Studio 2022*, navigate to Edit | Advanced | Comment Selection or Uncomment Selection. In *Visual Studio Code*, navigate to Edit | Toggle Line Comment or Toggle Block Comment.
49
What is the difference between **commenting** code and **commenting out** code?
**Commenting** code involves adding descriptive text to explain code sections. **Commenting out** code means adding comment characters to make code statements inactive. **Uncommenting** means removing these comment characters.
50
How does C# indicate a **block** of code?
C# uses **curly brackets** `{ }` to indicate a block of code.
51
What can a **block** in C# define?
A block in C# can define the **start and end of various language constructs**, including namespaces, classes, methods, or statements like foreach.
52
What is a **namespace** in C# and why is it important?
A **namespace** in C# is used to **organize code** into groups, preventing naming conflicts and managing classes. To access types in different namespaces, you need to use a ***using*** directive or a **fully qualified name**. For example: `using System;`
53
What does a **class** in C# contain?
A **class** in C# contains the **members of an object**, including **methods**. For example: ```public class MyClass { public int Number; // Field public void Display() // Method { Console.WriteLine(Number); } }```
54
What is contained within a **method** in C#?
A **method** in C# contains **statements** that implement an **action** that an object can take. For example: ```public void Greet() // Method { Console.WriteLine("Hello, world!"); }```
55
How do code editors like *Visual Studio* and *Visual Studio Code* **assist with blocks**?
These code editors provide a **feature to collapse and expand blocks** by toggling the [-] or [+] symbols or an arrow symbol in the left margin of the code.
56
What are **regions** in C#?
Regions are **defined labeled areas around any statements**, allowing code editors to collapse and expand them similarly to blocks, helping to **organize code** into collapsible sections for better readability. For example: ``` #region Methods public void Display() { Console.WriteLine(number); } #endregion ```
57
How can **regions** be used in code documentation and organization?
Regions can **act as commented blocks** that **summarize** what the block does, aiding in the **documentation** and **organization** of code, making it easier to navigate complex codebases.
58
How does the **C# brace style** compare to other languages like JavaScript?
**C# typically places both the open and close braces on their own lines at the same indentation level**, while languages like JavaScript often place the open brace at the end of the declaration statement.
59
Can you use **different brace styles** in C#?
**Yes**, you can use whatever brace style you prefer, as the compiler does not enforce a specific style. However, **it's easier to follow conventional style**.
60
What is the **most commonly used brace style in C#**, according to Microsoft's official documentation?
The brace style where **both the open and close braces are on their own line and at the same indentation level** is the most commonly used in C#.
61
What is advised regarding adherence to **coding style conventions**?
It's recommended to follow the **standards adopted by your development team** or, if you're a solo developer, to choose conventions that ensure your **code is readable and maintainable**, being kind to your future self by being consistent.
62
What types of characters are considered **white space** in C#?
The **space**, **tab**, and **newline characters** are considered **white space** in C#.
63
How does **white space** affect the C# compiler?
Extra white space has **no effect on the compiler** and can be used for **formatting** code for better readability.
64
What is the **minimal white space** requirement in C# statements?
The only required white space is **between tokens that the compiler must recognize as separate**, such as between a type and a variable name. For example: `string firstName = "Ben";`
65
What are some examples of **reserved keywords** in C#?
Examples include: **using, namespace, class, static, int, string, double, bool, if, switch, break, while, do, for, foreach, this,** and **true**.
66
What **symbol characters** are commonly used in C#?
Common symbol characters include: **"**, **'**, **+**, **-**, *, **/**, **%**, **@**, and **$**.
67
How should C# **keywords** be **formatted**, and what is the convention for **user-defined type names**?
C# **keywords** are all in **lowercase**. **User-defined type names should not be all lowercase** to avoid compiler warnings and future reserved keyword conflicts.
68
How many **keywords** does C# have compared to the number of distinct words in the English language?
**C# has about 100 keywords**, whereas the English language has more than 250,000 distinct words.
69
Why is C# considered difficult to learn despite having far fewer words than the English language?
The difficulty arises because developers need to **learn and define new "words" or concepts** within the language, expanding beyond the basic keywords to understand and utilize the language fully.
70
Why do programmers worldwide need to learn **English**?
Most programming languages, including C#, use English words for their syntax and keywords, such as "if" and "break."
71
How do *Visual Studio 2022* and *Visual Studio Code* visually **differentiate C# keywords** from other code?
By default, these IDEs show **C# keywords in blue and other code in black**, though this can be **customized**.
72
How can you customize the color scheme in Visual Studio 2022?
Go to Tools | Options, navigate to the Environment section, select Fonts and Colors, and then choose the display items to customize.
73
How do you change the **color theme** in Visual Studio Code?
Navigate to File | Preferences | Theme | Color Theme on Windows and Linux, or Code | Preferences | Theme | Color Theme on macOS, and select a color theme.
74
Why are plain text editors like **Notepad** not helpful for writing correct C# code?
Plain text editors **do not provide feedback on syntax errors or code correctness**, unlike specialized IDEs or editors with language support.
75
How do *Visual Studio 2022* and *Visual Studio Code* help you write correct C# code?
They **highlight spelling and grammatical errors** in the code, such as method names that are incorrectly capitalized or statements missing a semicolon, using colored squiggly lines.
76
What is a **namespace** in C#, and why is it used?
A namespace is like an **address that organizes code and helps to locate a specific method or type** within larger libraries. It's used to make code more manageable and to avoid name conflicts.
77
How do you **import a namespace** in C#, and what is its effect?
You use the ***using* directive to import a namespace**, e.g., `using System;`. This makes **all types** within that namespace available in your program without needing to specify the namespace prefix.
78
Why might **importing namespaces** be considered good practice in C#?
It simplifies the code by **eliminating the need to prefix every type with its namespace**, thereby making the code cleaner and more readable.
79
What problem do **global using statements** solve in C# 10 and .NET 6?
They **reduce the need to include common using statements at the top of every .cs file** by allowing a namespace to be imported once and made available throughout all .cs files in the project.
80
How can you **implement global using** statements in a project?
By **adding global using statements in a dedicated file, such as *GlobalUsings.cs***, which contains all the global using statements for the project.
81
What is the benefit of using a separate file like ***GlobalUsings.cs*** for global using statements?
It organizes global imports in one place, making the **project cleaner and easier to maintain** by avoiding repetitive namespace imports across multiple files.
82
What **naming convention** is recommended for the file containing **global using statements**?
While the book suggests a practical approach by naming the file ***GlobalUsings.cs***, it also notes that a de facto standard naming convention might emerge as developers get accustomed to this feature.
83
What does targeting .NET 6 or later with C# 10 or later automatically generate regarding **global usings**?
It generates a .GlobalUsings.g.cs file in the obj\Debug\net folder, which contains implicitly globally imported namespaces.
84
How do **implicitly imported namespaces** vary?
The list of implicitly **imported namespaces depends on the targeted SDK**, with different SDKs adding specific namespaces to the implicitly imported list.
85
What **namespaces** are **implicitly imported** by the Microsoft.NET.Sdk and Microsoft.NET.Sdk.Web?
The **Microsoft.NET.Sdk** imports basic namespaces like ***System***, ***System.IO***, and ***System.Linq***, among others. **Microsoft.NET.Sdk.Web** includes: ***all from Microsoft.NET.Sdk plu*s** web-specific namespaces like ***Microsoft.AspNetCore.Builder*** and ***Microsoft.Extensions.Hosting***.
86
How can you **view the autogenerated implicit imports** file in a project?
By toggling on the "**Show All Files**" button in Solution Explorer and navigating through the **obj -> Debug -> net8.0** folders to find the file named .GlobalUsings.g.cs.
87
What indicates that a file is autogenerated by the compiler in *Visual Studio*?
The **file name includes a *g* for generated** (e.g., .GlobalUsings.g.cs), and the file itself starts with a comment indicating it is autogenerated.
88
How do you use an **alias for a class** or **statically import a class** in the project file?
By specifying **Alias** or **Static attributes** in the element within the project file for the desired class, making it easier to reference in the code.
89
What is the effect of **statically importing** the *Console class* and **aliasing** the *Environment class* in a C# project?
**Statically importing** the *Console class* allows **calling its methods without prefixing** them with Console., and **aliasing** the *Environment class* enables referring to it with a **shorter or more convenient name**.
90
How can you **disable the implicitly imported namespaces feature** in a C# project?
By **removing** or **setting** the element to disable in the project file, allowing for manual management of global using statements.
91
How do **methods** in C# relate to **verbs** in English?
Just like verbs in English indicate action and change form based on tense, **methods in C# perform actions** and **can change how they are called or executed** based on the specifics of the action, a concept known as **overloading**.
92
Can you give an **example of method overloading** in C#?
Yes, the` Console.WriteLine()` method is an example of overloading. It can be called **with no arguments** to output just a line terminator, or **with arguments** to output a string, formatted numbers, and dates.
93
What are the **equivalents of nouns** in C#?
In C#, equivalents of nouns are **types, variables, fields,** and **properties**.
94
How does C# **categorize everything related to nouns**?
**Everything can be categorized as a type** in C#, which further includes **classes**, **structs**, **enums**, **interfaces**, or **delegates**.
95
What is the **difference between a type and a class** in C#?
While a **class is a specific kind of type** in C#, the **term "type" broadly refers to any categorization** within C# that can include classes, structs, and other categorizations. For example, *string* is a class, but *int* (which maps to System.Int32) is a struct.
96
How does C# **define types**?
C# itself only has a few **keywords** for types, such as *string* and *int*, which are **aliases** representing types provided by the **.NET platform**. The platform offers a vast **library of types** available to C#.
97
What programming technique is used to find out **how many types and methods** are available to C# in a console app?
**Reflection** is used to discover the number of types and their methods available in a C# application.
98
What does the **formatting specifier *N0*** indicate in the context of outputting numbers?
***N0*** means to **format a number with zero decimal places**, making the output easier to read.
99
Why is learning C# considered a **challenge** based on the reflection output of types and methods?
The challenge comes from the **vast number of types and methods** available to learn, with each type potentially having many members, including methods.
100
What is the purpose of using the **System.Reflection namespace** in C#?
It's used to work with **assemblies**, **modules**, **types**, **methods**, and so on, **at runtime**, enabling the **analysis** and **manipulation** of the program's **metadata**.
101
How can **AI tools** like *ChatGPT* be beneficial for programmers?
These tools can help programmers **learn** new things by **explaining** existing code, suggesting **improvements**, and even **writing** code, enhancing **understanding** and **productivity**.
102
What is the role of **variables** in a program?
**Variables temporarily store data within the memory of a running program**, facilitating the processing of incoming data from sources like **files**, **databases**, or **user input**, and preparing it for **output**.
103
What happens to the **data in variables when a program ends**?
When the program ends, the **data stored in memory is lost** unless it has been output to persistent storage like **files** or **databases**.
104
What should you consider when **choosing a type for a variable**?
When choosing a type for a variable, consider how much **space** it will occupy in memory and **how quickly** data of that type can be processed.
105
How do **different data types** affect **memory** usage and processing **speed**?
Different data types, such as *int* and *double*, can be likened to boxes of different sizes; **smaller data types may use less memory but could potentially be slower to process compared to larger data types**, especially on systems optimized for larger data units, like a 64-bit operating system.
106
What are the **two primary naming conventions** used in C# and their typical applications?
***Camel case*** is used for **local variables** and **private fields** (e.g., `cost`, `orderDetail`). ***Pascal case*** (Title case) is used for **types**, **non-private fields**, and other members like **methods** (e.g., `String`, `Int32`, `Cost`).
107
How do some C# programmers **distinguish private fields** in their code?
Some programmers **prefix private field names with an underscore**, for example, `_dateOfBirth` instead of dateOfBirth.
108
How do you **declare a named local variable** and **assign a value** to it in C#?
Declare the variable with a **type followed by an identifier and assign a value using the = symbol**. For example: `double heightInMetres = 1.88;`.
109
What C# 6 feature allows you to **output the name of a variable** and how is it used?
``` ```The **nameof** keyword outputs the name of a variable. It is used within string interpolations or other expressions to refer to the variable name as a **string**. For example: `Console.WriteLine($"The variable {nameof(heightInMetres)}` has the value `{heightInMetres}`.");.
110
What is a notable **enhancement to nameof** in C# 12?
In C# 12, **nameof can now access instance data from a static context**, which is a change from earlier versions where nameof could only access static data in such contexts.
111
What is a **literal value** in programming?
A literal value is a **notation used to represent a fixed value directly in the code**. Each data type has its own form of literal notation.
112
How do you **assign a single character** in C#?
A single character, like 'A', is assigned to a **char type** using **single quotes**. For example,` char letter = 'A';`.
113
What is a **surrogate pair**, and why is it important in C#?
**A surrogate pair is a set of two System.Char values** needed to represent certain characters, like some Egyptian Hieroglyphs, in C#. Understanding this is important to avoid bugs, especially in multicultural applications.
114
How is a **string assigned** in C#?
A string is assigned using **double quotes** around the literal value. For example, `string firstName = "Bob";`. Strings can also be assigned from **function calls** or **constructors**, such as: `string horizontalLine = new('-', count: 74);`.
115
How do you **output emojis** in a console application running on **Windows**?
To output emojis, use Windows **Terminal** and set the **console output encoding to UTF-8** with `Console.OutputEncoding = System.Text.Encoding.UTF8;`, then use `Console.WriteLine()` to print the emoji.
116
What is the process to convert a **Unicode value to a string for displaying an emoji**?
Use the `char.ConvertFromUtf32()` method with the Unicode code point of the emoji, for example, `string grinningEmoji = char.ConvertFromUtf32(0x1F600);`.
117
What is the purpose of using **escape sequences** in strings?
Escape sequences in strings represent **special characters**, such as **tabs (\t)** and **new lines (\n)**, using a **backslash (\\)**.
118
What issue might arise when **using backslashes in file paths** in C#?
The **compiler interprets backslashes as the start of an escape sequence**, which can lead to errors if the following characters form a valid escape sequence, such as \t being interpreted as a tab.
119
How can you **store file paths in strings without the compiler misinterpreting backslashes** as escape characters?
By using **verbatim string literals**, which are **prefixed with the @ symbol**, to tell the compiler to **ignore escape sequences** and interpret the string exactly as written.
120
Provide an **example of a verbatim string literal** used to correctly handle file paths in C#.
`string filePath = @"C:\televisions\sony\bravia.txt";` This verbatim string literal correctly handles the backslashes without treating them as the start of escape sequences.
121
What are **raw string literals** and why were they introduced in C# 11?
Raw string literals allow for **entering text without needing to escape special characters**. They were introduced to simplify the **inclusion of complex content like XML, HTML, or JSON** directly in the code.
122
How are **raw string literals defined** in C#?
Raw string literals are **enclosed by three or more double-quote characters (""") at both the start and end** of the literal.
123
Why might you need to use **more than three double-quotes** to enclose a raw string literal?
If the **content itself includes sequences of three or more double-quotes**, you use additional double-quotes (e.g., four or five) to ensure the literal is correctly delimited.
124
How does C# handle **indentation within raw string literals**?
C# adjusts the indentation based on the **alignment of the closing triple double-quotes**. The **compiler removes any common leading whitespace that matches the indentation of the closing quotes**.
125
What happens if the **end triple double-quotes** of a raw string literal are **aligned with the left margin**?
If the closing quotes are aligned with the left margin, the indentation inside the raw string literal is preserved as it appears in the code, meaning **no indentation removal occurs.**
126
How do **raw interpolated string literals** work in C#?
Raw interpolated string literals **combine raw strings with interpolation**. By prefixing the string with multiple dollar signs (e.g., **$$**), you specify that **pairs of curly braces** within the string represent **interpolated expressions**, while **single braces** are treated as **literal content**.
127
What is the **syntax to indicate interpolated expressions** within raw interpolated string literals?
The **number of dollar signs at the start of the string indicates the number of curly braces that form an interpolated expression**. For example, **$$** means two curly braces (**{{}}**) enclose interpolated expressions.
128
Provide an example of how to **write JSON using raw interpolated string literals** in C#.
``` var person = new { FirstName = "Alice", Age = 56 }; string json = $$""" { "first_name": "{{person.FirstName}}", "age": {{person.Age}}, "calculation": "{{{ 1 + 2 }}}" } """; Console.WriteLine(json); ``` This code **outputs JSON** where person.FirstName and person.Age are interpolated into the string, and calculations are performed within triple braces.
129
How are **different types of strings** summarized in C#?
**Literal string:** Uses double quotes, can include escape sequences like \t for tab. **Raw string literal:** Enclosed in three or more double quotes, does not interpret escape sequences. **Verbatim string:** Prefixed with @, interprets backslashes literally and allows multiline strings. **Interpolated string:** Prefixed with $, enables embedding formatted variables directly within the string.
130
How should you decide whether to **store a variable as a number or a string**?
Determine whether you need to perform **arithmetic operations** on it. If the data involves **non-digit characters** for formatting (like phone numbers with parentheses or hyphens), it should be stored as a ***string***.
131
What are **natural numbers** and how are they represented in computing?
Natural numbers are used for **counting** and are **whole numbers starting from 0**. In computing, they can be represented as **unsigned integers** (e.g., ***uint*** in C#).
132
What is the **difference between natural numbers and integers** in programming?
**Natural numbers** include **only positive values and zero**, represented by data types like ***uint***. **Integers** include **both positive and negative whole numbers and zero**, represented by data types like ***int***.
133
How do you **declare a float and a double** in C#, and what are their uses?
A **float**, which is a **single-precision floating-point number**, requires an '**F**' or '**f**' suffix in its declaration (e.g., `float realNumber = 2.3f;`). A **double**, which is a **double-precision floating-point number**, does **not need a suffix** and is the default for **decimal** values (e.g., `double anotherRealNumber = 2.3;`).
134
Why is it necessary to use specific data types like **float** and **double** for certain numbers?
These data types are necessary for representing **numbers with fractional parts** and **different levels of precision**, such as scientific computations where big data is being processed
135
What is the **binary number system**?
The binary number system, or **Base 2**, is used by computers to **store all data**. It uses only two digits, **0 and 1**, to represent any number.
136
How do computers **store the decimal number 10 in binary**?
Computers store the decimal number 10 as 00001010 in binary, which corresponds to the **bits being set at positions representing 8 and 2** (8 + 2 = 10).
137
What is the **difference** between the **decimal and binary number systems**?
The **decimal system**, also known as **Base 10**, is used by humans and includes ten digits from **0 to 9**. The **binary system**, used by computers, is **Base 2** and uses only two digits, **0 and 1**.
138
Why is the **binary** number system important in **computing**?
The binary system is **fundamental** for computing because computers store and process **data** using **bits**, which are inherently **binary**. Every operation in a computer, from arithmetic to data processing, is based on **binary calculations**.
139
What feature related to **number formatting** was introduced in C# 7?
C# 7 introduced the use of the **underscore _** as a **digit separator** to enhance the legibility of numeric literals.
140
How can **digit separators** be used in **numeric** literals?
Underscores can be **inserted between any digits of a number**, whether it's in decimal, binary, or hexadecimal notation, to improve readability.
141
Give an **example of using digit separators** in a decimal number.
The number one million can be written as **1_000_000** using digit separators to make it clearer.
142
How do you represent a number in **decimal**, **binary**, and **hexadecimal formats** in C#?
**Decimal**: `int decimalNotation = 2_000_000;` **Binary**: `int binaryNotation = 0b_0001_1110_1000_0100_1000_0000;` **Hexadecimal**: `int hexadecimalNotation = 0x_001E_8480;`
143
How can you verify in C# that **numbers in different notations** are equal?
By comparing the values using the **equality operator** (**==**) and outputting the result, for example: ```Console.WriteLine($"{decimalNotation == binaryNotation}"); Console.WriteLine($"{decimalNotation == hexadecimalNotation}");```
144
How do you **output the values of different numeric notations** in both decimal and hexadecimal formats?
Use **string interpolation** and **formatting specifiers**: **Decimal:** `Console.WriteLine($"{decimalNotation:N0}");` **Hexadecimal:** `Console.WriteLine($"{decimalNotation:X}");`
145
What do the output results of the different formats indicate about the **nature of integer representations**?
The outputs demonstrate that the **same integer value can be expressed and verified in different numerical bases** (decimal, binary, and hexadecimal) within C#, confirming that these are just different ways to represent the same underlying value.
146
Why *can't* computers always represent **real numbers** precisely?
Computers use **binary-based** systems, which can lead to **precision issues** when converting decimal numbers into binary format. The ***float*** and ***double*** data types use **finite precision** which **can't accurately represent all real numbers.**
147
What standards do most programming languages follow for **floating-point arithmetic**?
Most programming languages, including C#, follow the **IEEE 754 Standard for Floating-Point Arithmetic**, which was established by the Institute of Electrical and Electronics Engineers in 1985.
148
What does the **sizeof() operator** do in C#?
The sizeof() operator in C# returns the **number of bytes** that a type occupies in memory.
149
How can you find the **range of values** a numeric type can store in C#?
You can find the range of values a type can store by accessing the ***MinValue*** and ***MaxValue*** members of that type.
150
Why might a ***double*** store *larger numbers* than a ***decimal***, despite using *less memory*?
Although a ***double*** uses less memory (**8 bytes**) compared to a ***decimal*** (**16 bytes**), it can store larger numbers due to the way **floating-point arithmetic** is implemented, which allows it to represent very large or very small numbers but with *less precision* compared to decimal.
151
How does the ***float*** type compare to the ***double*** type in terms of **accuracy**?
The **float type is less precise than the double type**, which can make comparisons appear *true* due to its lower accuracy, even when they are not mathematically exact.
152
What is a common rule of thumb regarding the **use of double for comparisons**?
It is recommended to **avoid using double for exact equality comparisons (==)** because of potential *inaccuracies*. Instead, use double when only relative comparisons (<, >) are necessary, such as comparing measurements where exact values are not crucial.
153
Why does the **binary representation of 0.1** lead to precision issues?
In binary, 0.1 is represented as a **repeating binary fraction** (0.0001100110011...), which cannot be precisely stored in a finite number of bits used by types like *float* or *double*, leading to **rounding errors**.
154
How does the ***decimal*** type ensure **accuracy** in representing real numbers?
The ***decimal*** type maintains accuracy by **storing numbers as large integers and managing the decimal point's position.** This allows it to represent numbers precisely without rounding errors common in floating-point representations.
155
When should you use the **decimal type over float or double**?
Use decimal for scenarios where **precision in real numbers is crucial**, such as **financial calculations**, **engineering**, and **scientific measurements**, where rounding errors from floating-point arithmetic can lead to significant discrepancies.
156
What is the ***System.Half*** type and when was it introduced?
The ***System.Half** type*, introduced in *.NET 5*, is a data type that can **store real numbers** and typically uses **2 bytes** of memory.
157
What are the ***System.Int128*** and ***System.UInt128*** types, and what do they store?
Introduced in *.NET 7*, ***System.Int128*** and ***System.UInt128*** are types that can store **signed** and **unsigned** **integer values**, respectively, and *normally* use **16 bytes** of memory.
158
How does the **sizeof** operator work with **new number types** in C#?
The **sizeof** operator can only be used to determine the size of new number types like ***System.Half*** and ***System.Int128*** within an **unsafe code block**, which requires enabling unsafe code in the project settings.
159
What are the **storage** capacities and range values of ***System.Half*** and ***System.Int128*** ?
***System.Half*** uses **2 bytes** and can store numbers from **-65,504 to 65,504.** ***System.Int128*** uses **16 bytes** and can store numbers from approximately **-170 quadrillion to 170 quadrillion.**
160
Why is **unsafe code** needed for using the **sizeof** operator with certain types in C#?
Unsafe code is required for sizeof with certain types because **these operations bypass the *.NET runtime's* safety checks**, **allowing direct memory** access which is necessary for operations like measuring the size of newer or more complex data types.
161
What values can **boolean variables** store in C#?
Boolean variables can only store one of two values: **true** or **false**.
162
What are the primary **uses of booleans** in programming?
**Booleans** are primarily used to **control the flow** of programs, such as in **branching** (if-statements) and **looping** constructs.
163
What is the ***object type*** used for in C#?
The **object type** is a *special* type in C# that can **store any type of data**. However, its *flexibility* can lead to **messier code** and **poorer performance**, making it advisable to **avoid unless necessary**.
164
How do you handle **variables of type object** when specific type operations are needed?
To perform type-specific operations on an object variable, you must **cast it to the appropriate type**. For example, to access the *Length* property of an object variable storing a string, you must cast it to string.
165
Why should the use of the **object type** be *limited* in C#?
Using the object type should be limited due to its **impact on performance and code clarity**. It lacks type-specific properties and methods without explicit casting, which can complicate the code.
166
What is the **dynamic type** in C#?
The dynamic type, introduced in C# 4, allows variables to **store any type of data and enables the invocation of methods, properties, and fields of an object** without an explicit cast at compile time.
167
How does the **dynamic type differ from the object type**?
Unlike variables of type object, **variables declared with the dynamic type do not require casting to access members**. However, this comes with a performance cost due to runtime type checking.
168
What are the implications of using the **dynamic type for method and property access**?
Using the dynamic type allows method and property **access directly without casting**, but this can lead to **runtime exceptions** if the accessed members do not exist on the runtime type of the object.
169
Provide an **example** of how **dynamic types can lead to runtime errors**.
```dynamic something = 12; // int type assigned Console.WriteLine(something.Length); // This will throw a RuntimeBinderException at runtime because 'int' does not have a 'Length' property.```
170
Why can't code editors provide ***IntelliSense* for dynamic types**?
IntelliSense or code completion does not work with dynamic types because their **resolution occurs at runtime, and the compiler does not check the type during build time.**
171
What is the **scope of local variables** in C#?
Local variables are **declared inside methods and only exist during the execution of that method**. Once the method *returns*, the local variables are no longer accessible.
172
How are **local variables stored and released** in C#?
Local variables that are **value types are released immediately when the method returns**, while local variables that are **reference types are released through garbage collection**.
173
How do you declare **local variables with specific types** in C#?
Local variables can be declared with specific types by **specifying the type before the variable name.** For example: `int population = 67_000_000; // Integer type` `double weight = 1.88; // Double type` `decimal price = 4.99M; // Decimal type` `string fruit = "Apples"; // String type` `char letter = 'Z'; // Char type` `bool happy = true; // Boolean type`
174
What does the code editor do if **local variables are declared but not used**?
Depending on the code editor and its settings, it may show green **squiggles** under each variable name and lighten their text color to warn that the variable is assigned but its value is never used.
175
What does the ***var* keyword** do in C#?
The *var* keyword in C# allows for **type inference** where the compiler determines and assigns the **most specific type** based on the assigned value at compile time. This feature is available from C# 3 onwards.
176
How does **type inference with *var*** affect runtime performance?
Using *var* for type inference **does not affect runtime performance** because type resolution happens at compile time.
177
What are the **suffixes** used with **numeric literals** to infer specific numeric types with ***var***?
**L:** Infers a **long** type **UL:** Infers an **ulong** type **M:** Infers a **decimal** type **D:** Infers a **double** type **F:** Infers a **float** type
178
How does the ***var*** keyword infer types based on **literal values**?
**Numeric literals without a decimal point default to int** unless a *suffix* is specified. **Numeric literals with a decimal point are inferred as double** unless a *suffix* like M or F is used. **Double quotes infer a string type**. **Single quotes infer a char type**. **True or false infer a bool type.**
179
When is it considered **good or bad practice to use *var***?
Using *var* is considered **good practice when the type is obvious** from the right side of the assignment, making the code cleaner and less repetitive. However, if the **type is not clear, it's better to explicitly declare the variable** with a specific type to improve code readability and maintainability.
180
What is ***target-typed new*** in C#?
Introduced in C# 9, target-typed new **allows instantiation of objects without explicitly repeating the type if it's already specified**, simplifying the syntax and improving readability.
181
How can you **instantiate an object using *target-typed new***?
You can specify the variable type and use new() without specifying the type again. For example: `XmlDocument xml3 = new();`
182
How does *target-typed new* work with **objects that require initialization**?
When objects require their fields or properties to be set during initialization, the **syntax allows for inferred type setting**. For example: ```Person kim = new(); kim.BirthDate = new(1967, 12, 26); // Implicitly new DateTime```
183
What are the **advantages of using *target-typed new***?
This syntax **reduces the amount of code** needed, **clarifies the variable's type** at the start of the statement, and is **not limited to local variables** like *var*. It **improves readability** by focusing on the variable type first.
184
When should you **avoid using *target-typed new***?
You should avoid using target-typed new **if you are working with compilers that predate C# 9**, as this feature will not be supported.
185
What is the **default value of an *int*** in C#?
The default value of an int is **0**.
186
What is the **default value of a bool** in C#?
The default value of a bool is **False**.
187
What does **default(DateTime) return** in C#?
default(DateTime) returns **01/01/0001 00:00:00.**
188
What is the **default value of a string** in C#?
The default value of a string is **null**.
189
How can you **reset a variable to its default value** using the ***default*** keyword in C#?
You can assign the default value to a variable by using the syntax **variable = default;**. For example, `number = default;` resets the number variable to its default value.
190
What is the effect of **setting a variable to its default** value using the *default* keyword in C# and then printing it?
After setting a variable like `int number = 13;` to default, and then printing it, the output will be number reset to its default: **0**.
191
What are **console applications** typically used for in programming?
Console applications are **text-based**, **run at the command prompt**, and are often used for **simple scripting** tasks like compiling files or encrypting parts of a configuration file. They can also **accept arguments** to control their behavior.
192
What is the **difference between the *Write* and *WriteLine*** methods in console applications?
The ***Write*** method **outputs text without a carriage return**, leaving the cursor at the end of the printed text, while the ***WriteLine*** method **outputs text followed by a carriage return**, moving the cursor to the start of the next line.
193
How would you **output** the letters "ABC" **on a single line** using console methods?
Use `Write("A"); Write("B"); Write("C");` to print "ABC" continuously on one line without carriage returns.
194
How do you use *WriteLine* to **output** the letters "A", "B", and "C" each **on a new line** in a console application?
Use `WriteLine("A"); WriteLine("B"); WriteLine("C");` to print each letter on a new line, with the cursor moving to the next line after each letter.
195
How do you **format a string to display the cost** of items using C#?
You can format a string to display the cost of items using the ***Console.WriteLine ***or ***string.Format*** methods with *numbered positional arguments*, like this: `Console.WriteLine("{0} apples cost {1:C}", numberOfApples, pricePerApple * numberOfApples);`
195
What C# methods support **formatting strings using numbered positional arguments**?
The ***Write***, ***WriteLine***, and ***Format*** methods of the *Console* class support formatting strings using **numbered positional arguments.**
196
What is the **maximum number of named arguments** you can use with *Console.WriteLine* in C# and how does it change with more arguments?
With *Console.WriteLine*, you can use **up to 3 named arguments (arg0, arg1, arg2)**. If you need to pass more than three values, you cannot use *named arguments*.
197
When is it suggested to **stop using named parameters** for formatting strings in C#?
**Once you become comfortable with formatting strings**, it is suggested to stop using named parameters like `format:, arg0:, and arg1:` to streamline the code.
198
What C# feature allows you to use **variable or expression values within a string**, indicated by a dollar sign and curly braces?
**Interpolated strings.**
199
What must be true about a **string statement using *interpolated strings*** in C# versions 10 or earlier?
The statement **must be all on one line.**
200
What change in *C# 11* affects how ***interpolated strings*** are written in terms of **line breaks**?
In C# 11 or later, you **can include a line break in the middle of an expression but not in the string text** itself.
201
Why might **interpolated strings not be suitable for localizing code examples** that need to be read from *resource files*?
**Interpolated strings can't be read from resource files to be localized**, making them less versatile for *international* applications.
202
What was a **limitation of string constants** in C# versions earlier than C# 10, and how was it addressed in *C# 10*?
**Before C# 10, string constants could only be combined using concatenation** with the **+** operator. C# 10 introduced the ability to use **interpolated strings for combining string constants**, enhancing readability and simplicity.
203
What is a ***format string*** in C# and how is it used?
A *format string* in C# is used to specify **how a variable or expression should be formatted** when output. It follows the syntax **{ index [, alignment ] [ : formatString ] }**, where **index** refers to the **argument position**, **alignment** specifies how text should be **aligned** within a given width (positive for right, negative for left), and **formatString** determines the **formatting type** like number or currency.
204
How does the "**N0**" *format string* modify the output in C#?
The "N0" format string in C# formats a **number with thousand separators and no decimal places**. This helps in displaying numbers in a more **readable** form, especially when dealing with large values.
205
What does the "**C**" *format string* represent in C# and how does it behave in *different locales*?
The "C" *format string* in C# is used for **currency formatting**. The output is formatted according to the currency and thousand separator conventions of the **current thread's culture settings**. For example, it might display pounds sterling with commas as thousand separators in the UK, and euros with dots as thousand separators in Germany.
206
How can **alignment** be specified in *format strings* for table outputs in C#?
Alignment in *format strings* is specified by **including an integer after the variable index and a comma inside the curly braces.** **Positive** integers align the text to the **right**, while **negative** integers align it to the **left**. This is useful for aligning columns in *tabular* outputs.
207
What does the '**0**' format code represent in C# number formatting?
The '0' format code is a **zero placeholde**r. It **replaces the zero with the corresponding digit if present**; **otherwise, it uses zero**. For example, using 0000.00 to format the value 123.4 would result in 0123.40.
208
How does the '**#**' format code function in C# number formatting?
The '**#**' format code is a **digit placeholder**. It **replaces the hash with the corresponding digit if present; otherwise, it uses nothing.** For example, using ####.## to format the value 123.4 would result in 123.4.
209
What role does the '**.**' play in C# custom number formatting?
The '**.**' is a **decimal point that sets the location of the decimal point in the number and respects cultural formatting** differences, such as using a dot (.) in US English and a comma (,) in French.
210
How is the '**,**' used differently in C# number formatting?
The '**,**' serves as a **group separator, inserting a localized group separator between each group.** It is also used to **scale a number by dividing it by multiples of 1,000 for each comma placed after the decimal point.** For example, formatting the value 1234567 with 0,000 would result in 1,234,567.
211
Explain the '**%**' format code in C#.
The '**%**' format code **multiplies the value by 100 and adds a percentage character** to the number, effectively converting it into a percentage format.
212
What is the purpose of the '**\\**' escape character in C# number formatting?
The '**\\**' is an **escape character that makes the next character a literal instead of a format code**, which helps include actual format symbols in the output text. For example, formatting the value 1234 with \\##,###\\# would give #1,234#.
213
Describe how the '**;**' is used in C# number formatting.
The '**;**' is a **section separator that defines different format strings for positive, negative, and zero values.** For example, using the format string [0];(0);Zero, the number 13 would be formatted as [13], -13 as (13), and 0 as Zero.
214
What C# method is used to **get text input** from the user?
The ***Console.ReadLine()*** method is used to get text input from the user. It waits for the user to type text and press Enter, returning the input as a *string* value.
215
How do you handle potential **null return** values from ***Console.ReadLine()*** in C# to satisfy nullability checks?
To handle potential null return values from *Console.ReadLine(),* you can use the **nullable reference type notation string ?** for variables where null is an acceptable value, or the **null-forgiving operator !** to assert that the value will not be null.
216
What does appending a **?** after the string type in a variable declaration do in C#?
Appending a ? after the string type in a variable declaration (e.g., `string? firstName`) **tells the C# compiler that the variable may hold a null value**, which helps avoid compiler *warnings* about possible null values.
217
What is the purpose of the **null-forgiving operator !** in C#?
The **null-forgiving operator ! is used to tell the compiler that a value will not be null**, even if the method called could technically return null. This operator **suppresses compiler warnings** about null values.
218
What is the purpose of **importing a static class** in C# 6 and later?
Importing a static class in C# 6 and later allows for **simplifying the code by eliminating the need to repeatedly specify the class name when calling its static members.** For example, by importing the *System.Console* class statically, you can use its methods like *WriteLine* directly without prefixing them with 'Console.', streamlining the code and reducing verbosity.
219
How do you **statically import the *System.Console*** class in a single file in C#?
To statically import the System.Console class in a single file, you **add the statement `using static System.Console;`** at the top of the Program.cs file. This allows you to use all static methods from the *Console* class directly without the class name prefix.
220
How can you simplify your code by **removing repeated references** to 'Console.' in Visual Studio?
In Visual Studio, you can simplify your code by using the **Find and Replace feature** to remove repeated 'Console.' references. First, select 'Console.' including the dot, navigate to Edit | Find and Replace | Quick Replace, leave the Replace box empty, click on 'Replace all', and then close the replace box.
221
How do you **globally and statically import *System.Console*** for all code files in a project?
Edit your `.csproj` file to include: ``` ```
222
What is the purpose of the **string[] args** parameter in the ***Main*** method of a C# console application?
The string[] args parameter in the *Main* method of a C# console application is used to **receive command-line arguments**. These arguments are passed as an *array of strings* to the application, allowing users to influence the application's *behavior at runtime* by providing different values when executing the program.
223
How are **command-line arguments separated** and how can **spaces** be included within an argument?
Command-line arguments are separated by **spaces**. To **include spaces** within an argument value and ensure it is treated as a single argument, the value should be **enclosed in single or double quotes**.
224
In a *.NET 6 and later* top-level program, how is **access to the args array** maintained despite the absence of an explicit *Program* class and *Main* method?
In .NET 6 and later top-level programs, the ***Program* class and its *Main* method are hidden**, but the **args array still exists** implicitly. The args array is automatically available for accessing command-line arguments, maintaining functionality without explicitly defining it in the code
225
How can you **output and enumerate command-line arguments** in a console application?
To output and enumerate command-line arguments in a console application, use the following steps: **Output the number of arguments using**` WriteLine($"There are {args.Length} arguments.");`. **Iterate through the args array with a foreach loop** to display each argument, like so: ```foreach (string arg in args) { WriteLine(arg); }```
226
What is the purpose of using a **try-catch statement** in handling platform-specific features in a console application?
The try-catch statement is used to **handle exceptions** that occur when a platform-specific API is not supported by the current platform. For example, if an application tries to change the cursor size, which is not supported on macOS, wrapping this operation in a try-catch allows the program to catch the PlatformNotSupportedException and provide a user-friendly message instead of crashing.
227
How can you determine and **handle differences in operating system capabilities** in a C# application?
You can use the ***OperatingSystem* class to check for specific operating systems and their versions**, allowing code to execute only on platforms that support certain features. For instance, `OperatingSystem.IsWindows()` checks for a Windows OS, and `OperatingSystem.IsIOSVersionAtLeast(major: 14, minor: 5)` checks for at least iOS 14.5.
228
What are **conditional compilation statements** and how are they used in handling different platforms in C#?
Conditional compilation statements like **#if, #elif, #else, and #endif** **control the compilation of code based on defined symbols**, allowing developers to include or exclude code depending on the target platform. For example, `#if NET7_0_ANDROID` includes code only when compiling for Android under .NET 7. This method is used to **tailor applications to different environments without runtime overhead.**
229
What are the primary uses of the ***async*** and ***await*** keywords introduced in C# 5?
These keywords are used for **implementing multitasking in graphical user interfaces** (GUIs), **improving scalability** of web applications and services, and **preventing blocking calls** when interacting with the filesystem, databases, and remote services.
230
What feature was introduced in C# 7.1 regarding the *Main* method?
C# 7.1 introduced the **ability to mark the *Main* method as async**, allowing the use of the **await** keyword directly within it.
231
How can ***async*** and ***await*** be demonstrated in a console application?
By creating a **console app that makes an asynchronous HTTP request** using *HttpClient* to fetch a webpage (e.g., Apple’s home page) and outputs the content size.
232
# Exercise 2.1 – Test your knowledge What statement can you type in a C# file to **discover the compiler and language version**?
To discover the compiler and language version in a C# file, you can use preprocessor directives such as #if, combined with symbols like __CSCSHARP__ and __VERSION__ to check compiler-specific conditions. Additionally, the **language version can be specified in the project file** (.csproj) with tag.
233
# Exercise 2.1 – Test your knowledge What are the **two types of comments** in C#?
Types of Comments in C#: **Single-line comment:** Prefixed with //, comments the rest of the line. **Multi-line comment:** Enclosed between /* and */, comments out blocks of code.
234
# Exercise 2.1 – Test your knowledge What is the **difference between a verbatim string and an interpolated string**?
**Verbatim string:** Denoted by a **@** symbol before the string (e.g., `@"C:\Files`"), it **ignores escape sequences** and prints everything within the quotes as is. **Interpolated string:** Prefixed with **$** (e.g., `$"Name: {name}"`), it allows **embedding of expressions** inside string literals using curly braces.
235
# Exercise 2.1 – Test your knowledge Why should you **be careful** when using ***float*** and ***double*** values?
*float* and *double* types are **prone to rounding errors** because they represent floating point numbers in a binary format, which can lead to precision issues, especially when dealing with very large or very small numbers, or when exact decimal representation is required.
236
# Exercise 2.1 – Test your knowledge How can you determine **how many bytes** a type like double uses in memory?
In C#, you can use ***sizeof*** operator to determine the number of bytes a type uses in memory. For instance, `sizeof(double); `returns 8, indicating that a double uses 8 bytes.
237
# Exercise 2.1 – Test your knowledge When should you use the ***var*** keyword?
The *var* keyword should be used **when the type of a variable is obvious from the right side of the assignment**, or **when it doesn't matter to the reader what the exact type is**. It is mostly used for *local variable declaration* where the initial assignment provides sufficient detail to clearly infer the type.
238
# Exercise 2.1 – Test your knowledge What is the **newest syntax to create an instance of a class** like *XmlDocument*?
The newest syntax in C# for creating an instance of a class uses **target-typed new**, which allows you to **omit the type name if it can be inferred** by the compiler: `XmlDocument doc = new();`
239
# Exercise 2.1 – Test your knowledge Why should you **be careful** when using the **dynamic type**?
The *dynamic* type in C# **bypasses static type checking**. When using dynamic, **you lose compiler-time type checking and related *IntelliSense* support** in IDEs, which can lead to **runtime errors** if the operations being performed are not valid on the runtime type of the dynamic object.
240
# Exercise 2.1 – Test your knowledge How do you **right-align a format string**?
To right-align text in a format string, you can **specify a positive number for the alignment component** in the format item. For example, **{0,10}** aligns the first argument to the right over a width of 10 characters.
241
# Exercise 2.1 – Test your knowledge What character **separates arguments for a console app**?
In C#, arguments for a console application are **separated by spaces.** However, if an argument itself contains spaces, it should be enclosed in quotes.