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
Q

How does the latest setting differ from latestmajor in the <LangVersion> configuration?

A

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.

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

What is the effect of setting <LangVersion> to preview?

A

It uses the highest available preview version of the compiler, like 12.0 in July 2023 with .NET 8 Preview 6 installed.

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

When did Microsoft release the first preview of .NET 9 with a C# 13 compiler?

A

In 2024.

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

How can you use the C# 13 compiler in your projects after installing the .NET 9 SDK preview?

A

By editing the .csproj file to add the <LangVersion> element set to preview.

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

What does setting the <LangVersion> to preview in your project file do?

A

It allows using the preview C# 13 compiler, enabling exploration of new language features.

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

Can you use a future version of the C# compiler, like C# 13, with .NET 8 projects?

A

Yes, you can use a future version of the C# compiler with .NET 8 projects by setting the <LangVersion> appropriately in the project file.

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

What is the recommended practice for using preview versions of the C# compiler in projects?

A

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.

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

When is Microsoft expected to make the .NET 9 SDK generally available, and what does this mean for .NET 8 projects?

A

In November 2024, making it possible to use the C# 13 compiler in projects that continue to target .NET 8 by setting <LangVersion> to 13.

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

What will be the default C# language version for projects targeting .NET 9 after installing its SDK?

A

C# 13 will be the default language version for projects targeting .NET 9.

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

What is a key consideration when using new C# language features with older versions of .NET?

A

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.

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

What unique method is used to display the compiler version in the console app?

A

Add the #error version statement in the Program.cs file to trigger a compiler error that reveals the compiler and language version.

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

What information is revealed by the compiler error CS8304?

A

The error reveals the compiler version (e.g., ‘4.8.0…’) and the default language version (12.0) as part of the error message.

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

What are the components of C# grammar?

A

C# grammar includes statements and blocks.
Additionally, comments are used to document code.

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

Besides comments, what are some methods to document your code in C#?

A

Besides comments, sensible naming for variables and functions, writing unit tests, and creating actual documentation are recommended practices for documenting code.

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

How does C# indicate the end of a statement?

A

C# indicates the end of a statement with a semicolon (;).

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

How is an English sentence structure analogy used to explain C# statements?

A

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.

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

What is an example of a C# statement, and what are its components?

A

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 (+).

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

Why does the order of operands and operators matter in a C# expression?

A

The order affects the meaning and the result of the expression, similar to how word order affects meaning in natural language sentences.

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

What is the primary purpose of comments in code?

A

Comments are used to document code, increasing understanding of its functionality for others or for the original developer when revisiting the code later.

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

How do you add a single-line comment in C#?

A

Use a double slash // at the beginning of the comment.
The compiler ignores everything after // until the end of the line.

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

How can you write a multi-line comment in C#?

A

Use /* at the beginning and */ at the end of the comment block.

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

Is it possible to use multi-line comment syntax for commenting in the middle of a statement? If so, how?

A

Yes, you can use /* and */ for commenting in the middle of a statement.
For example:
decimal totalPrice = subtotal /* for this item */ + salesTax;

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

What should you consider if you find yourself adding too many comments in your code?

A

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.

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

How can you add or remove comment characters in Visual Studio 2022 and Visual Studio Code?

A

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.

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

What is the difference between commenting code and commenting out code?

A

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.

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

How does C# indicate a block of code?

A

C# uses curly brackets { } to indicate a block of code.

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

What can a block in C# define?

A

A block in C# can define the start and end of various language constructs, including namespaces, classes, methods, or statements like foreach.

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

What is a namespace in C# and why is it important?

A

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;

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

What does a class in C# contain?

A

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

What is contained within a method in C#?

A

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

How do code editors like Visual Studio and Visual Studio Code assist with blocks?

A

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.

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

What are regions in C#?

A

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

How can regions be used in code documentation and organization?

A

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.

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

How does the C# brace style compare to other languages like JavaScript?

A

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.

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

Can you use different brace styles in C#?

A

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.

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

What is the most commonly used brace style in C#, according to Microsoft’s official documentation?

A

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

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

What is advised regarding adherence to coding style conventions?

A

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.

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

What types of characters are considered white space in C#?

A

The space, tab, and newline characters are considered white space in C#.

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

How does white space affect the C# compiler?

A

Extra white space has no effect on the compiler and can be used for formatting code for better readability.

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

What is the minimal white space requirement in C# statements?

A

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";

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

What are some examples of reserved keywords in C#?

A

Examples include:
using, namespace, class, static, int, string, double, bool, if, switch, break, while, do, for, foreach, this, and true.

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

What symbol characters are commonly used in C#?

A

Common symbol characters include:
, , +, -, *, /, %, @, and $.

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

How should C# keywords be formatted, and what is the convention for user-defined type names?

A

C# keywords are all in lowercase.

User-defined type names should not be all lowercase to avoid compiler warnings and future reserved keyword conflicts.

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

How many keywords does C# have compared to the number of distinct words in the English language?

A

C# has about 100 keywords, whereas the English language has more than 250,000 distinct words.

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

Why is C# considered difficult to learn despite having far fewer words than the English language?

A

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.

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

Why do programmers worldwide need to learn English?

A

Most programming languages, including C#, use English words for their syntax and keywords, such as “if” and “break.”

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

How do Visual Studio 2022 and Visual Studio Code visually differentiate C# keywords from other code?

A

By default, these IDEs show C# keywords in blue and other code in black, though this can be customized.

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

How can you customize the color scheme in Visual Studio 2022?

A

Go to Tools | Options, navigate to the Environment section, select Fonts and Colors, and then choose the display items to customize.

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

How do you change the color theme in Visual Studio Code?

A

Navigate to File | Preferences | Theme | Color Theme on Windows and Linux, or Code | Preferences | Theme | Color Theme on macOS, and select a color theme.

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

Why are plain text editors like Notepad not helpful for writing correct C# code?

A

Plain text editors do not provide feedback on syntax errors or code correctness, unlike specialized IDEs or editors with language support.

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

How do Visual Studio 2022 and Visual Studio Code help you write correct C# code?

A

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.

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

What is a namespace in C#, and why is it used?

A

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.

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

How do you import a namespace in C#, and what is its effect?

A

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.

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

Why might importing namespaces be considered good practice in C#?

A

It simplifies the code by eliminating the need to prefix every type with its namespace, thereby making the code cleaner and more readable.

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

What problem do global using statements solve in C# 10 and .NET 6?

A

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.

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

How can you implement global using statements in a project?

A

By adding global using statements in a dedicated file, such as GlobalUsings.cs, which contains all the global using statements for the project.

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

What is the benefit of using a separate file like GlobalUsings.cs for global using statements?

A

It organizes global imports in one place, making the project cleaner and easier to maintain by avoiding repetitive namespace imports across multiple files.

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

What naming convention is recommended for the file containing global using statements?

A

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.

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

What does targeting .NET 6 or later with C# 10 or later automatically generate regarding global usings?

A

It generates a <ProjectName>.GlobalUsings.g.cs file in the obj\Debug\net<version> folder, which contains implicitly globally imported namespaces.</version></ProjectName>

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

How do implicitly imported namespaces vary?

A

The list of implicitly imported namespaces depends on the targeted SDK, with different SDKs adding specific namespaces to the implicitly imported list.

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

What namespaces are implicitly imported by the Microsoft.NET.Sdk and Microsoft.NET.Sdk.Web?

A

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 plus web-specific namespaces like Microsoft.AspNetCore.Builder and Microsoft.Extensions.Hosting.

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

How can you view the autogenerated implicit imports file in a project?

A

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 <ProjectName>.GlobalUsings.g.cs.</ProjectName>

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

What indicates that a file is autogenerated by the compiler in Visual Studio?

A

The file name includes a g for generated (e.g., <ProjectName>.GlobalUsings.g.cs), and the file itself starts with a comment indicating it is autogenerated.</ProjectName>

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

How do you use an alias for a class or statically import a class in the project file?

A

By specifying Alias or Static attributes in the <Using> element within the project file for the desired class, making it easier to reference in the code.</Using>

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

What is the effect of statically importing the Console class and aliasing the Environment class in a C# project?

A

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.

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

How can you disable the implicitly imported namespaces feature in a C# project?

A

By removing or setting the <ImplicitUsings> element to disable in the project file, allowing for manual management of global using statements.</ImplicitUsings>

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

How do methods in C# relate to verbs in English?

A

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.

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

Can you give an example of method overloading in C#?

A

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.

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

What are the equivalents of nouns in C#?

A

In C#, equivalents of nouns are types, variables, fields, and properties.

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

How does C# categorize everything related to nouns?

A

Everything can be categorized as a type in C#, which further includes classes, structs, enums, interfaces, or delegates.

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

What is the difference between a type and a class in C#?

A

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.

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

How does C# define types?

A

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

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

What programming technique is used to find out how many types and methods are available to C# in a console app?

A

Reflection is used to discover the number of types and their methods available in a C# application.

98
Q

What does the formatting specifier N0 indicate in the context of outputting numbers?

A

N0 means to format a number with zero decimal places, making the output easier to read.

99
Q

Why is learning C# considered a challenge based on the reflection output of types and methods?

A

The challenge comes from the vast number of types and methods available to learn, with each type potentially having many members, including methods.

100
Q

What is the purpose of using the System.Reflection namespace in C#?

A

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
Q

How can AI tools like ChatGPT be beneficial for programmers?

A

These tools can help programmers learn new things by explaining existing code, suggesting improvements, and even writing code, enhancing understanding and productivity.

102
Q

What is the role of variables in a program?

A

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
Q

What happens to the data in variables when a program ends?

A

When the program ends, the data stored in memory is lost unless it has been output to persistent storage like files or databases.

104
Q

What should you consider when choosing a type for a variable?

A

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
Q

How do different data types affect memory usage and processing speed?

A

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
Q

What are the two primary naming conventions used in C# and their typical applications?

A

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
Q

How do some C# programmers distinguish private fields in their code?

A

Some programmers prefix private field names with an underscore, for example, _dateOfBirth instead of dateOfBirth.

108
Q

How do you declare a named local variable and assign a value to it in C#?

A

Declare the variable with a type followed by an identifier and assign a value using the = symbol.
For example:
double heightInMetres = 1.88;.

109
Q

What C# 6 feature allows you to output the name of a variable and how is it used?

A

~~~

```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
Q

What is a notable enhancement to nameof in C# 12?

A

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
Q

What is a literal value in programming?

A

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
Q

How do you assign a single character in C#?

A

A single character, like ‘A’, is assigned to a char type using single quotes.
For example, char letter = 'A';.

113
Q

What is a surrogate pair, and why is it important in C#?

A

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
Q

How is a string assigned in C#?

A

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
Q

How do you output emojis in a console application running on Windows?

A

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
Q

What is the process to convert a Unicode value to a string for displaying an emoji?

A

Use the char.ConvertFromUtf32() method with the Unicode code point of the emoji, for example, string grinningEmoji = char.ConvertFromUtf32(0x1F600);.

117
Q

What is the purpose of using escape sequences in strings?

A

Escape sequences in strings represent special characters, such as tabs (\t) and new lines (\n), using a backslash (\).

118
Q

What issue might arise when using backslashes in file paths in C#?

A

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
Q

How can you store file paths in strings without the compiler misinterpreting backslashes as escape characters?

A

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
Q

Provide an example of a verbatim string literal used to correctly handle file paths in C#.

A

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
Q

What are raw string literals and why were they introduced in C# 11?

A

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
Q

How are raw string literals defined in C#?

A

Raw string literals are enclosed by three or more double-quote characters (“””) at both the start and end of the literal.

123
Q

Why might you need to use more than three double-quotes to enclose a raw string literal?

A

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
Q

How does C# handle indentation within raw string literals?

A

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
Q

What happens if the end triple double-quotes of a raw string literal are aligned with the left margin?

A

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
Q

How do raw interpolated string literals work in C#?

A

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
Q

What is the syntax to indicate interpolated expressions within raw interpolated string literals?

A

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
Q

Provide an example of how to write JSON using raw interpolated string literals in C#.

A
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
Q

How are different types of strings summarized in C#?

A

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
Q

How should you decide whether to store a variable as a number or a string?

A

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
Q

What are natural numbers and how are they represented in computing?

A

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
Q

What is the difference between natural numbers and integers in programming?

A

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
Q

How do you declare a float and a double in C#, and what are their uses?

A

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
Q

Why is it necessary to use specific data types like float and double for certain numbers?

A

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
Q

What is the binary number system?

A

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
Q

How do computers store the decimal number 10 in binary?

A

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
Q

What is the difference between the decimal and binary number systems?

A

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
Q

Why is the binary number system important in computing?

A

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
Q

What feature related to number formatting was introduced in C# 7?

A

C# 7 introduced the use of the underscore _ as a digit separator to enhance the legibility of numeric literals.

140
Q

How can digit separators be used in numeric literals?

A

Underscores can be inserted between any digits of a number, whether it’s in decimal, binary, or hexadecimal notation, to improve readability.

141
Q

Give an example of using digit separators in a decimal number.

A

The number one million can be written as 1_000_000 using digit separators to make it clearer.

142
Q

How do you represent a number in decimal, binary, and hexadecimal formats in C#?

A

Decimal: int decimalNotation = 2_000_000;

Binary: int binaryNotation = 0b_0001_1110_1000_0100_1000_0000;

Hexadecimal:
int hexadecimalNotation = 0x_001E_8480;

143
Q

How can you verify in C# that numbers in different notations are equal?

A

By comparing the values using the equality operator (==) and outputting the result, for example:

Console.WriteLine($"{decimalNotation == binaryNotation}");
Console.WriteLine($"{decimalNotation == hexadecimalNotation}");
144
Q

How do you output the values of different numeric notations in both decimal and hexadecimal formats?

A

Use string interpolation and formatting specifiers:

Decimal: Console.WriteLine($"{decimalNotation:N0}");

Hexadecimal: Console.WriteLine($"{decimalNotation:X}");

145
Q

What do the output results of the different formats indicate about the nature of integer representations?

A

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
Q

Why can’t computers always represent real numbers precisely?

A

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
Q

What standards do most programming languages follow for floating-point arithmetic?

A

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
Q

What does the sizeof() operator do in C#?

A

The sizeof() operator in C# returns the number of bytes that a type occupies in memory.

149
Q

How can you find the range of values a numeric type can store in C#?

A

You can find the range of values a type can store by accessing the MinValue and MaxValue members of that type.

150
Q

Why might a double store larger numbers than a decimal, despite using less memory?

A

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
Q

How does the float type compare to the double type in terms of accuracy?

A

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
Q

What is a common rule of thumb regarding the use of double for comparisons?

A

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
Q

Why does the binary representation of 0.1 lead to precision issues?

A

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
Q

How does the decimal type ensure accuracy in representing real numbers?

A

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
Q

When should you use the decimal type over float or double?

A

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
Q

What is the System.Half type and when was it introduced?

A

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
Q

What are the System.Int128 and System.UInt128 types, and what do they store?

A

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
Q

How does the sizeof operator work with new number types in C#?

A

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
Q

What are the storage capacities and range values of System.Half and System.Int128 ?

A

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
Q

Why is unsafe code needed for using the sizeof operator with certain types in C#?

A

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
Q

What values can boolean variables store in C#?

A

Boolean variables can only store one of two values: true or false.

162
Q

What are the primary uses of booleans in programming?

A

Booleans are primarily used to control the flow of programs, such as in branching (if-statements) and looping constructs.

163
Q

What is the object type used for in C#?

A

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
Q

How do you handle variables of type object when specific type operations are needed?

A

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
Q

Why should the use of the object type be limited in C#?

A

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
Q

What is the dynamic type in C#?

A

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
Q

How does the dynamic type differ from the object type?

A

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
Q

What are the implications of using the dynamic type for method and property access?

A

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
Q

Provide an example of how dynamic types can lead to runtime errors.

A
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
Q

Why can’t code editors provide IntelliSense for dynamic types?

A

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
Q

What is the scope of local variables in C#?

A

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
Q

How are local variables stored and released in C#?

A

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
Q

How do you declare local variables with specific types in C#?

A

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
Q

What does the code editor do if local variables are declared but not used?

A

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
Q

What does the var keyword do in C#?

A

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
Q

How does type inference with var affect runtime performance?

A

Using var for type inference does not affect runtime performance because type resolution happens at compile time.

177
Q

What are the suffixes used with numeric literals to infer specific numeric types with var?

A

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
Q

How does the var keyword infer types based on literal values?

A

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
Q

When is it considered good or bad practice to use var?

A

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
Q

What is target-typed new in C#?

A

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
Q

How can you instantiate an object using target-typed new?

A

You can specify the variable type and use new() without specifying the type again.
For example: XmlDocument xml3 = new();

182
Q

How does target-typed new work with objects that require initialization?

A

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
Q

What are the advantages of using target-typed new?

A

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
Q

When should you avoid using target-typed new?

A

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
Q

What is the default value of an int in C#?

A

The default value of an int is 0.

186
Q

What is the default value of a bool in C#?

A

The default value of a bool is False.

187
Q

What does default(DateTime) return in C#?

A

default(DateTime) returns 01/01/0001 00:00:00.

188
Q

What is the default value of a string in C#?

A

The default value of a string is null.

189
Q

How can you reset a variable to its default value using the default keyword in C#?

A

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
Q

What is the effect of setting a variable to its default value using the default keyword in C# and then printing it?

A

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
Q

What are console applications typically used for in programming?

A

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
Q

What is the difference between the Write and WriteLine methods in console applications?

A

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
Q

How would you output the letters “ABC” on a single line using console methods?

A

Use Write("A"); Write("B"); Write("C"); to print “ABC” continuously on one line without carriage returns.

194
Q

How do you use WriteLine to output the letters “A”, “B”, and “C” each on a new line in a console application?

A

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
Q

How do you format a string to display the cost of items using C#?

A

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
Q

What C# methods support formatting strings using numbered positional arguments?

A

The Write, WriteLine, and Format methods of the Console class support formatting strings using numbered positional arguments.

196
Q

What is the maximum number of named arguments you can use with Console.WriteLine in C# and how does it change with more arguments?

A

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
Q

When is it suggested to stop using named parameters for formatting strings in C#?

A

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
Q

What C# feature allows you to use variable or expression values within a string, indicated by a dollar sign and curly braces?

A

Interpolated strings.

199
Q

What must be true about a string statement using interpolated strings in C# versions 10 or earlier?

A

The statement must be all on one line.

200
Q

What change in C# 11 affects how interpolated strings are written in terms of line breaks?

A

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
Q

Why might interpolated strings not be suitable for localizing code examples that need to be read from resource files?

A

Interpolated strings can’t be read from resource files to be localized, making them less versatile for international applications.

202
Q

What was a limitation of string constants in C# versions earlier than C# 10, and how was it addressed in C# 10?

A

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
Q

What is a format string in C# and how is it used?

A

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
Q

How does the “N0format string modify the output in C#?

A

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
Q

What does the “Cformat string represent in C# and how does it behave in different locales?

A

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
Q

How can alignment be specified in format strings for table outputs in C#?

A

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
Q

What does the ‘0’ format code represent in C# number formatting?

A

The ‘0’ format code is a zero placeholder.
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
Q

How does the ‘#’ format code function in C# number formatting?

A

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
Q

What role does the ‘.’ play in C# custom number formatting?

A

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
Q

How is the ‘,’ used differently in C# number formatting?

A

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
Q

Explain the ‘%’ format code in C#.

A

The ‘%’ format code multiplies the value by 100 and adds a percentage character to the number, effectively converting it into a percentage format.

212
Q

What is the purpose of the ‘\’ escape character in C# number formatting?

A

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
Q

Describe how the ‘;’ is used in C# number formatting.

A

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
Q

What C# method is used to get text input from the user?

A

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
Q

How do you handle potential null return values from Console.ReadLine() in C# to satisfy nullability checks?

A

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
Q

What does appending a ? after the string type in a variable declaration do in C#?

A

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
Q

What is the purpose of the null-forgiving operator ! in C#?

A

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
Q

What is the purpose of importing a static class in C# 6 and later?

A

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
Q

How do you statically import the System.Console class in a single file in C#?

A

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
Q

How can you simplify your code by removing repeated references to ‘Console.’ in Visual Studio?

A

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
Q

How do you globally and statically import System.Console for all code files in a project?

A

Edit your .csproj file to include:

<ItemGroup>
  <Using Include="System.Console" Static="true" />
</ItemGroup>
222
Q

What is the purpose of the string[] args parameter in the Main method of a C# console application?

A

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
Q

How are command-line arguments separated and how can spaces be included within an argument?

A

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
Q

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?

A

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
Q

How can you output and enumerate command-line arguments in a console application?

A

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
Q

What is the purpose of using a try-catch statement in handling platform-specific features in a console application?

A

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
Q

How can you determine and handle differences in operating system capabilities in a C# application?

A

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
Q

What are conditional compilation statements and how are they used in handling different platforms in C#?

A

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
Q

What are the primary uses of the async and await keywords introduced in C# 5?

A

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
Q

What feature was introduced in C# 7.1 regarding the Main method?

A

C# 7.1 introduced the ability to mark the Main method as async, allowing the use of the await keyword directly within it.

231
Q

How can async and await be demonstrated in a console application?

A

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
Q

Exercise 2.1 – Test your knowledge

What statement can you type in a C# file to discover the compiler and language version?

A

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 <LangVersion> tag.</LangVersion>

233
Q

Exercise 2.1 – Test your knowledge

What are the two types of comments in C#?

A

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
Q

Exercise 2.1 – Test your knowledge

What is the difference between a verbatim string and an interpolated string?

A

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
Q

Exercise 2.1 – Test your knowledge

Why should you be careful when using float and double values?

A

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
Q

Exercise 2.1 – Test your knowledge

How can you determine how many bytes a type like double uses in memory?

A

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
Q

Exercise 2.1 – Test your knowledge

When should you use the var keyword?

A

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
Q

Exercise 2.1 – Test your knowledge

What is the newest syntax to create an instance of a class like XmlDocument?

A

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
Q

Exercise 2.1 – Test your knowledge

Why should you be careful when using the dynamic type?

A

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
Q

Exercise 2.1 – Test your knowledge

How do you right-align a format string?

A

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
Q

Exercise 2.1 – Test your knowledge

What character separates arguments for a console app?

A

In C#, arguments for a console application are separated by spaces.
However, if an argument itself contains spaces, it should be enclosed in quotes.