MS Full-Stack, Front & Back-End Dev C2 Intro to Prog in C# Flashcards

1
Q

What are the two main hosting models of Blazor?

A
  • Blazor WebAssembly
  • Blazor Server

Both models enable C# to be used for interactive web applications.

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

What is Blazor WebAssembly?

A

A hosting model that runs C# client-side in the browser through WebAssembly, eliminating the need for JavaScript.

This allows for rich client-side applications.

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

What is the purpose of GitHub?

A

A platform for version control and collaboration, allowing developers to manage and share code effectively.

It uses Git to track changes and facilitate teamwork.

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

What are key features of GitHub?

A
  • Version Control
  • Collaboration
  • Integration
  • Open Source

These features enhance code management and teamwork.

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

Definition

Back-end development

A

Back-end development is the practice of building and managing the systems that power apps and websites, such as data processing, storage, and application logic.

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

What is back-end development responsible for?

A

Back-end development is responsible for the servers, database, and logic that make a website function. Back-end developers ensure that all the data the front-end needs is processed securely and efficiently.

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

What do back-end developers ensure?

A

That all the data the front-end needs is processed securely and efficiently.

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

What is the main focus of back-end developers?

A

Processing data securely and efficiently.

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

What is the purpose of the .NET environment?

A

A software development platform by Microsoft that simplifies building, deploying, and running applications across different operating systems.

Supports Windows, Linux, and macOS.

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

What types of applications can be developed using .NET?

A
  • Web
  • Desktop
  • Mobile
  • Cloud
  • IoT

.NET’s versatility makes it suitable for diverse projects.

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

How do front-end engineers utilize programming skills?

A

They develop user-facing elements of web applications through building interfaces, collaborating with teams, and debugging and optimizing.

Key tasks include using HTML, CSS, and JavaScript.

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

What tools do front-end developers use?

A
  • HTML
  • CSS
  • JavaScript
  • Frameworks like React and Angular

These tools help create responsive layouts and user interfaces.

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

What is the focus of back-end development?

A

Building and maintaining server-side logic, databases, and infrastructure that support the front-end.

Back-end developers ensure secure and scalable systems.

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

What is Visual Studio Code?

A

A lightweight code editor that integrates seamlessly with the .NET environment to enhance developer productivity.

Supports writing, debugging, and deploying .NET applications.

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

What are some of the key features offered by Visual Studio Code as a cross-development environment?

A

IntelliSense: Provides smart code completions and suggestions, helping developers write code faster and with fewer errors.

Debugging tools: Allows developers to step through code line-by-line, setting breakpoints to identify and fix errors quickly.

GitHub integration: Facilitates source control management by tracking code changes and supporting collaboration among team members.

Extension marketplace: Offers a wide range of extensions that can be added to customize the editor for specific languages and workflows.

Azure integration: Supports cloud-based services, allowing for seamless integration with Microsoft Azure.

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

Visual Studio Code Workflow: Handling aspects of project development.

A

Project setup and management: VS Code simplifies the creation and management of .NET projects with its intuitive interface and commands that automate repetitive tasks.

Coding and debugging: Developers can easily write, refine, and debug their code, ensuring high-quality outputs and faster iteration cycles.

Version control: With built-in GitHub integration, Visual Studio Code helps developers manage code changes and maintain a history of modifications.

Testing and deployment: VS Code includes tools for writing and running tests directly within the editor, which ensures code reliability. Additionally, it offers streamlined deployment options that allow developers to package and deploy applications to production servers quickly and efficiently.

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

What role does Visual Studio Code play in .NET projects?

A

It integrates with the .NET CLI to create, build, and manage .NET projects

It provides essential tools for writing, running, and debugging .NET projects

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

Which versions of the .NET SDK are currently installed in my computer?

A

You can see which versions of the .NET SDK are currently installed with a terminal. Open a terminal and run the following command.

dotnet –list-sdks

You get an output similar to:

3.1.424 [C:\program files\dotnet\sdk]
5.0.100 [C:\program files\dotnet\sdk]
6.0.402 [C:\program files\dotnet\sdk]
7.0.100 [C:\program files\dotnet\sdk]

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

Which versions of the .NET runtime are currently installed in my computer?

A

Run:
dotnet –list-runtimes

You get an output similar to:

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

Five Best Practices for Organizing Files in a .NET Project

A

Modularization: Divide your code into logical modules or categories, such as features (e.g., user management, data processing) or layers (e.g., data access, business logic, presentation).

Separation of concerns: Structure your project by separating different functionalities. This could mean organizing code by features or by layers.

Naming conventions: Follow consistent naming conventions to improve code clarity.

Refactoring: Regularly review and refactor your code to maintain its structure and readability.

Documentation: Provide external documentation (such as a README file that gives an overview of the project) and internal comments within the code.

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

What is the role of Program.cs in a .NET project?

A

It serves as the application’s entry point, where execution begins.

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

What information does the .csproj file contain?

A

Settings, dependencies, and configuration details.

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

What does the .csproj file tell the .NET build system?

A

How to build the project, which files to include, and which external libraries are needed.

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

What type of files does the obj folder hold?

A

Intermediate files generated during the build process.

These files are used temporarily during the build process and are not part of the final output.

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

What is the purpose of the bin directory in a .NET project?

A

To store compiled code necessary for the application to run.

The bin directory stores compiled code, including executable files and Dynamic Link Libraries (DLLs).

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

Which file should be included in a .gitignore file for a .NET project?

A

The bin and obj folders are often included in .gitignore to avoid committing build artifacts.

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

How do you clean the build output of a .NET project using CLI?

A

Use the dotnet clean command.

dotnet clean removes all compiled output files from the bin and obj directories.

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

What command-line tool is essential for creating new .NET projects?

A

.NET CLI for managing and creating projects.

The .NET CLI provides commands like dotnet new to create .NET projects.

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

Why is using pseudocode beneficial before writing actual code?

A

Pseudocode allows developers to focus on the logic and structure of the code before dealing with the syntax of a specific programming language.

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

What are the two main techniques for decomposing problems?

A

Top-down approach and modularization

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

Describe the top-down approach in problem decomposition.

A

Starts with a broad overview and gradually breaks it into detailed components

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

Define modularization in problem decomposition.

A

Divides a problem into self-contained units or modules, each performing a specific function

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

What is a benefit of modularization?

A

Allows for independent development and refinement of each module

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

When using the top-down approach to design software, what should be done after creating a broad design goal?

A

State goals and problems that are out of scope.

Stating what the software will not do helps refine the design goal and problem statement.

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

Which of the following best defines the bottom-up approach to problem-solving in software development?

A

A method that begins with developing individual components and integrates into a complete system.

The bottom-up approach involves developing small, manageable parts first and then integrating them to form a comprehensive solution.

The bottom-up approach is beneficial when the problem is not clearly defined, allowing for exploration and flexibility.

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

Top-Down Problem-Solving Approach

Definition and benefits | Implementation

A

Definition and benefits: the top-down approach starts with a broad overview of a problem and breaks it down into smaller, more manageable parts. It is particularly useful for software development tasks like code debugging and feature development.

Implementation: developers begin by examining the system to identify specific areas of concern. The process involves progressively refining these areas into finer details to solve the problem.

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

Bottom-Up Problem-Solving Approach

Definition and benefits | Implementation

A

Definition and benefits: the bottom-up approach starts with small, manageable parts and integrates them to create a comprehensive solution. This method supports flexibility and experimentation in software development, allowing developers to build individual components that are later combined into a complete system.

Implementation: developers focus on creating specific parts of an application, like user authentication or profile management, and then integrate these parts into a single, functional application. This approach is useful for developing complex systems where components can be developed and tested individually before integration.

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

What is a strength of the top-down approach?

A

Best when there is a clear understanding of the problem

It allows for focused tasks and facilitates collaboration.

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

What is a weakness of the top-down approach?

A

May lack flexibility if the problem is not well-defined

This can hinder adaptability in dynamic situations.

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

What is a benefit of the bottom-up approach?

A

Allows for exploring problems without a clear initial definition

It is useful for scalability and flexibility.

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

What is a drawback of the bottom-up approach?

A

Can be unwieldy and unconstrained without clear goals

This may lead to inefficiencies in problem-solving.

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

When should the top-down approach be used?

A

For problems with a clearly defined high-level goal

This approach breaks down the goal into smaller tasks.

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

When is it appropriate to use the bottom-up approach?

A

When starting from the details to build a comprehensive solution

Especially useful when dealing with unknowns or needing to experiment.

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

AND operator in C#

A

&&
AND is represented by a double ampersand

Ex. condition_01 && condition_02, reads condition_01 AND condition_02

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

OR operator in C#

A

||
OR is represented by a double vertical bar

Ex. condition_01 || condition_02, reads condition_01 OR condition_02

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

NOT Equal operator in C#

A

!=
NOT is represented by an equal sign preceded by and exclamation sign

Ex. condition_01 != condition_02, reads cond_01 is not equal cond_02

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

NOT operator in C#

A

!
NOT is represented by an exclamation sign

Ex. if !(condition_01) is true, then condition_01 must be false

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

Which of the following best describes the purpose of pseudocode in programming?

A

It helps outline the logic of the program in plain language before coding.

Pseudocode is used to describe the steps of an algorithm or program logic in plain language, helping programmers plan their code.

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

Method definition and example in C#

A

Methods are reusable blocks of code designed to perform specific tasks, which helps organize and manage complex programs.

A method comprises a name, parameters (inputs), a return type (output), and the code to execute.

public static int Accelerate(int gas) {
    // Code to increase car velocity
    return velocity;
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
50
Q

Top-Down Approach

A

Top-Down Approach
Start with a high-level overview and break it into smaller components or tasks.

It is ideal for situations where the overall structure is known, such as developing a feature that follows established patterns.

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

Bottom-Up Approach

A

Bottom-Up Approach
Begin with basic elements or functions and combine them to build a complete system.

This method is suitable when the details are unclear or the development requires flexibility, such as building a new feature from scratch.

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

Historical origin of the word “debugging”

A

In 1947, while working on the Harvard Mark two Computer, Grace Hopper and her team discovered a moth trapped in a relay causing the system to malfunction, a discovery that led to the coining of the term debugging.

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

What is a logical error in a program?

A

A logical error is a mistake in programming logic that produces incorrect results without crashing the program.

Logical errors occur when the logic of the code is flawed, leading to incorrect results without causing the program to crash.

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

Debugger toolbar in VS Code

Visual Studio Code

A

The debugger toolbar in VS Code includes six commands:

  • Continue
  • Step Over
  • Step Into
  • Step Out
  • Restart
  • Stop
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
55
Q

Debugging: Step Over

Visual Studio Code

A

Step Over executes the current line of code and moves to the next line, but does not enter into functions or method called by that line.

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

Debugging: Step Into

Visual Studio Code

A

Step Into executes the current line of code, and if the line contains a function or method, enters into that function to allow line by line debugging inside it.

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

Debugging: Step Out

Visual Studio Code

A

Step Out completes the execution of the current function and returns to the calling function, then pauses.

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

Debugging: Restart

Visual Studio Code

A

Restart stops the current debugging session and starts it again from the beginning.

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

Debugging: Continue

Visual Studio Code

A

Continue resumes program execution until the next breakpoint is hit or the program ends.

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

What are Syntax errors?

Debugging

A

Errors that occur when the code violates the programming language’s rules, such as missing semicolons or unmatched brackets.

The compiler usually catches Syntax errors, making them easier to detect and correct.

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

What triggers Runtime errors?

Debugging

A

Errors that happen while the program is running, often causing the program to crash or behave unexpectedly.

An example is a division by zero error, which is encountered only during execution.

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

Define Logical errors.

Debugging

A

Mistakes in the code’s logic that produce incorrect results without causing a crash.

They are often the hardest to detect because the program appears to function correctly.

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

What is a Breakpoint in debugging?

Debugging

A

A tool that allows developers to pause the execution of code at specific points to inspect the program’s state.

This helps understand what is happening at that moment.

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

How does Inspecting variables help in debugging?

Debugging

A

It involves checking the values of variables at different points in the code to determine if the program manipulates data as expected.

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

What does Stepping through code entail?

Debugging

A

Executing code one line at a time to observe its behavior closely and pinpoint the exact line where an error occurs.

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

What is the purpose of Printing error messages?

Debugging

A

To track the execution flow and identify where and why the code fails, especially useful for understanding unexpected behavior or crashes.

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

Which tool in Visual Studio Code is used to inspect variable values during debugging?

Debugging

A

The Debugging Inspector

The Debugger Inspector in Visual Studio Code allows you to check the values of variables at different points in your code during debugging.

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

Basic structure of a C# program

A

A C# program starts with a class definition and a Main method that serves as the program’s entry point.

For example:

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Hello, World!");
    }
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
69
Q

Handling user input via the Console

C#

A

C# can also handle user input via the Console.ReadLine() method.

For example:

Console.WriteLine("Enter your name:");
string name = Console.ReadLine();
Console.WriteLine("Hello, " + name + "!");

This allows programs to interact with users dynamically.

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

What is the purpose of the static keyword that precedes a variable or a method declaration?

A

The static keyword allows a variable or method to be accessible throughout the program without needing to create an instance of the class.

71
Q

True or False

You can call a static method without instantiating the class containing it

C#

A

True

You can call a static method without instantiating the class containing it

72
Q

True or False
Variables in C# hold data and are declared with specific types.

A

Variables in C# hold data and are declared with specific types.

Examples include:

int age = 25;
string name = “John”;
var count = 10;

73
Q

What is the purpose of the var keyword when declaring a variable?

C#

A

The var keyword allows for type inference, where the compiler determines the variable’s type based on its assigned value.

74
Q

You are developing a program that categorizes event attendees into children, teens, and adults based on their ages. Which algorithm structure would best suit this task?

A

Categorical statement

Categorical statements are ideal for organizing data into groups based on criteria, such as age ranges.

75
Q

What is the main purpose of flowcharts?

A

To visualize the logical steps involved in various scenarios.

Mastering the creation and analysis of flowcharts is crucial for developers to visualize processes accurately, avoid common mistakes, and communicate logic effectively.

76
Q

What shape represents processes or actions in a flowchart?

A

Rectangles.

77
Q

What do diamonds represent in flowcharts?

A

Decision points.

78
Q

What do arrows indicate in a flowchart?

A

The direction of the flow.

79
Q

What is the purpose of ovals in flowcharts?

A

To mark the start and end points.

80
Q

Steps in creating an effective flowchart

A

1 Define the process.
2 Identify key steps.
3 Draw the flowchart.
4 Validate the flowchart.

Analyze each step, check decision points, validate the flow of control, confirm start and end points.
Review for missing steps, incorrect sequences, or unclear decision points.

81
Q

.GetType()

C#

A

GetType() returns a Type object that represents the runtime type of the instance.

It is a method of the System.Object class, so it can be called on any object.

Use it to inspect or compare the type of an object at runtime

using System;

class Program
{
    static void Main()
    {
        string example = "Hello, World!";
        Type type = example.GetType();
        Console.WriteLine(type); // Output: System.String
    }
}
82
Q

.Parse()

int number = int.Parse(numberString);
A

In C#, the Parse() method is used to convert a string representation of a value into its corresponding data type. It is commonly used with numeric types like int, double, or DateTime

Parse() throws an exception if the string is not in a valid format for the target type.

If you’re unsure about the input’s validity, use TryParse() instead.

using System;

class Program
{
    static void Main()
    {
        string numberString = "123";
        int number = int.Parse(numberString); // Converts the string to an integer
        Console.WriteLine(number); // Output: 123
    }
}
83
Q

.TryParse()

if (int.TryParse(input, out int result))
A

TryParse() method is used to safely convert a string to a specific data type without throwing an exception if the conversion fails.

Returns true if the conversion is successful, and the out parameter contains the converted value.

Returns false if the conversion fails, and the out parameter is set to the default value of the target type.

Commonly used for types like int, double, DateTime, etc.

using System;

class Program
{
    static void Main()
    {
        string input = "123";
        if (int.TryParse(input, out int result))
        {
            Console.WriteLine($"Conversion successful: {result}");
        }
        else
        {
            Console.WriteLine("Conversion failed.");
        }
    }
}
84
Q

Name the four data type conversion methods in C#

A

Conversion methods include casting (explicitly converting a type), parsing (interpreting strings as other data types), implicit conversion (automatic conversion by the language), and explicit conversion (requiring a function or method).

85
Q

What is mutability in reference to variables?

A

Mutability refers to whether a variable can be changed after its creation:

Mutable Variables: Variables that can change their values after being declared.
For example, declaring int counter = 1; allows you to change counter later in the code, such as counter = 2;.

Immutable Variables:
Immutable variables cannot be changed after initialization.
Declared using the const keyword (for compile-time constants) or readonly (for values assigned at runtime).

const double PI = 3.14159;readonly int maxAttempts;.

86
Q

What is the difference in C# between using const to declare a constant instead of using the readonly keyword?

A

In C#, both const and readonly are used to define constants, but they differ in their behavior and usage:

Use const for values that are truly immutable and known at compile time (e.g., mathematical constants).
const int Pi = 3.141516;

Use readonly for values that may depend on runtime logic or need to be initialized dynamically.

readonly variables can be assigned either at the time of declaration or in a class constructor, while const variables are assigned during declaration and remain fixed.

87
Q

const

Variable declarations in C#

A

Use const to define a constant

Compile-Time Constant: The value must be assigned at the time of declaration and cannot be changed later.

Implicitly Static: const values are shared across all instances of a class and accessed using the class name.

Fixed Value: The value is “baked” into the code at compile time, meaning changes require recompilation of dependent code.

public const int DaysInWeek = 7;

Use const for values that are truly immutable and known at compile time (e.g., mathematical constants).

Use readonly for values that may depend on runtime logic or need to be initialized dynamically.

88
Q

readonly

Variable declarations in C#

A

Runtime Constant: The value can be assigned either at the time of declaration or within the constructor, allowing for dynamic initialization.

Instance-Specific: readonly fields are tied to the instance unless declared as static.

Flexible: The value is resolved at runtime, so changes in the source code don’t require recompilation of dependent code.

public readonly int MaxUsers;

public MyClass()
{
    MaxUsers = 100; // Assigned in the constructor
}

the readonly keyword allows for dynamic initialization

Use const for values that are truly immutable and known at compile time (e.g., mathematical constants).

Use readonly for values that may depend on runtime logic or need to be initialized dynamically.

89
Q

Which keyowrd is used to declare an immutable variable in C#?
static - const - readonly

A

The const keyword is used to declare immutable variables, which cannot be reassigned after initialization.

static relates to the scope of a variable within a class, not its mutability

readonly allows for dynamic initialization, that is, initialization at runtime: you don’t know the variable’s value at declare time.

90
Q

Key Types of Variables in C#

A

Integer (int): stores whole numbers, e.g., int count = 10;.

Double (double): holds numeric values with decimals, e.g., double price = 19.99;.

String (string): used for text data, e.g., string name = “Alice”;.

Boolean (bool): represents true or false values, e.g., bool isValid = true;.

Array: stores a collection of values of the same type, e.g., int[] scores = {10, 20, 30};.

91
Q

True or False

C# is a type-safe language, meaning that each variable must be declared with a specific data type, which helps prevent errors and improves code readability.

92
Q

What is the assignment operator in C#?

A

= is the assignment operator.

93
Q

Problems in C

Calculate the sum of the elements of an array

A
// Initialize an array of integers
int[] numbers = { 1, 2, 3, 4, 5 };
int sum = 0;

// Loop through each number in the array
foreach (int number in numbers)
{
    // Add each number to the sum
    sum += number;
}

// Output the sum
Console.WriteLine("The sum of the array is: " + sum);
94
Q

Problems in C

Counting the number of vowels in a string

A
// Initialize a string
string text = "Hello World";
int vowelCount = 0;

// Loop through each character in the string
foreach (char c in text.ToLower())
{
    // Use switch to check if the character is a vowel
    switch (c)
    {
        case 'a':
        case 'e':
        case 'i':
        case 'o':
        case 'u':
            vowelCount++;
            break;
    }
}

// Output the number of vowels
Console.WriteLine("The number of vowels is: " + vowelCount);
95
Q

Is this statement valid in C#?

float temperature = 22.5f;
A

Yes, the statement is valid in C#.

The f suffix explicitly indicates that the number 22.5 is a float. Without the f, the number would be treated as a double by default, resulting in a type mismatch.

Use the float data type to store single-precision floating-point numbers

96
Q

Provide a simple code example

if syntax

A
if (condition) {
    // Code to execute if the condition is true
} else {
    // Code to execute if the condition is false
}

Use If-Else Statements for Binary Decisions

int age = 18;
if (age >= 18) {
    Console.WriteLine("Access granted.");
} else {
    Console.WriteLine("Access denied.");
}
97
Q

Provide a simple code example

switch syntax

A
switch (variable) {
    case value1:
        // Code to execute if variable == value1
        break;
    case value2:
        // Code to execute if variable == value2
        break;
    default:
        // Code to execute if variable matches none of the cases
        break;
}

switch evaluates a variable then executes different actions accordingly

string button = "Water";
switch (button) {
    case "Water":
        Console.WriteLine("Dispensing water");
        break;
    case "Soda":
        Console.WriteLine("Dispensing soda");
        break;
    default:
        Console.WriteLine("Invalid option");
        break;
}
98
Q

Give an example of the switch statement in C# with pattern matching for evaluation of a n object.

A

Pattern Matching: The switch statement evaluates the type and value of value using patterns like int i and string s.

Case Guards: The when keyword adds additional conditions, such as i > 0 or i < 0.

Default Case: Handles any value that doesn’t match the specified patterns.

using System;

class Program
{
    static void Main()
    {
        object value = 42;

        switch (value)
        {
            case int i when i > 0:
                Console.WriteLine($"Positive integer: {i}");
                break;
            case int i when i < 0:
                Console.WriteLine($"Negative integer: {i}");
                break;
            case string s:
                Console.WriteLine($"String: {s}");
                break;
            case null:
                Console.WriteLine("Null value");
                break;
            default:
                Console.WriteLine("Unknown type");
                break;
        }
    }
}
99
Q

When to use a do-while loop instead of a while loop

A

The key difference between do-while and while loops is that do-while loops always execute the code block at least once before evaluating the condition, while “while” loops may skip execution if the condition is false initially.

Use a do-while loop to execute the code block at least once before checking if the condition is true.

Use a while loop to execute a code block only if the condition is true from the start, like when validating input before processing.

using System;

class Program
{
    static void Main()
    {
        int counter = 0;

        do
        {
            Console.WriteLine($"Counter: {counter}");
            counter++;
        } while (counter < 5);
    }
}
100
Q

for loop in C# syntax

A

The syntax of a for loop includes four parts:

Initialization: this part initializes the loop counter, typically by setting it to a starting value.

Condition: before each iteration, the loop checks a condition. If the condition is true, the loop continues; if false, the loop stops.

Increment/decrement: after each iteration, the loop counter is modified, usually by incrementing or decrementing.

Code block: This section contains the code to be executed on each iteration.

Use for loop when you know the exact number of times to iterate.

for (int i = 0; i < 5; i++)
{
    Console.WriteLine(i);
}
101
Q

while loop in C# syntax

A

The syntax of a while loop is straightforward:

It starts with the keyword while followed by a condition in parentheses.

As long as the condition is true, the code block inside the loop is executed.

Use while loop when you don’t know the exact number of times to iterate

int counter = 0;
while (counter < 10)
{
    Console.WriteLine(counter);
    counter++;
}
102
Q

do while loop in C# syntax

A

The syntax of a do-while loop involves two parts:

The loop begins with the keyword do, followed by a code block enclosed in curly braces {}.

After the code block, the keyword while and the condition are specified.

Use do-while to execute code at least once reagrdless of the condition.

int counter = 10;
do
{
    Console.WriteLine(counter);
    counter++;
} while (counter < 10);
103
Q

Why is important to optimize loops and what are some basic key loop optimization techniques?

A

Optimizing loops is crucial to preventing slowdowns caused by unnecessary iterations or redundant calculations.

Minimize iterations. Terminate loops early to reduce the number of iterations. When a condition is met, you can break out of the loop early with a break statement.

Avoid nested loops. Nested loops can be inefficient, especially if both loops iterate many times without needing to. Avoiding nested loops or minimizing their usage can improve performance. When possible, it’s a good practice to break down loops into smaller independent loops rather than nesting them.

Efficient loops ensure faster execution, conserve resources, and improve application scalability.

104
Q

What is the benefit of using a switch statement with a loop?

A

Simplifies managing complex conditions by separating the iteration process from the decision-making process.

Combining a switch statement with a loop allows you to systematically evaluate each item in a collection and handle specific conditions or cases based on its value.

105
Q

Write a simple code example

Integrating If-Else with Loops

A
using System;
					
public class Program
{
    public static void Main()
    {
        int input;
		do {
			Console.WriteLine("Enter an even number between 1 and 10:");
			input = int.Parse(Console.ReadLine());
			if (input >= 1 && input <= 10 && input % 2 == 0) {
				Console.WriteLine("Valid input: " + input);
				break;
			} else {
				Console.WriteLine("Invalid input. Please try again.");
			}
		} while (true);
    }
}
106
Q

True or False

Functions make code easier to mantain and update.

A

True

By using functions, developers can update code in one place rather than in multiple instances, making maintenance more efficient.

107
Q

Structure of a function in C#

A

Function declaration: This is the function’s name and defines what the function will do.

Parameters: Functions often take input values, known as parameters.

Function body: This contains the actual code that processes the input.

Return value: A function typically returns a result after completing its task. The return value could be stored in a variable or used immediately in the program.

double CalculateRectangleArea(double length, double width)
{
    return length * width;
}
108
Q

Key Benefits of Functions

A

Reusability: The same function can be called multiple times across the program without duplicating code.

Modularity: By breaking down large tasks into smaller, manageable functions, developers make the code more readable and easier to debug.

Maintainability: If a function’s logic needs to change, it can be updated in one place, and those changes are automatically reflected wherever the function is used.

109
Q

What are functions?

A

A function is a block of code that takes input, processes it, and returns a result.

By using functions, developers can write more efficient code, avoiding repetition.

Example:

double CalculateTriangleArea(double baseLength, double height)
{
    return 0.5 * baseLength * height;
}

Functions allow you to perform common tasks, like calculations or data transformations, without having to rewrite the same code multiple times. This enables faster development and fewer errors.

110
Q

True or false

A method is a function associated with an object in OOP, whereas a function is a general block of reusable code.

A

True

A method operates on data within an object, while a function can be used independently without being tied to a specific object.

111
Q

What is an access modifier in C#?

A

In C#, an access modifier is a keyword used to define the visibility or accessibility of classes, methods, fields, and other members of a program. It determines which parts of the code can access a particular member.

Types of Access Modifiers:

public
private
protected
internal
protected internal
private protected
file (introduced in C# 11):

These modifiers help enforce encapsulation and control how data and functionality are exposed in your program.

112
Q

What does the ‘public’ access modifier signify?

A

Accessible from anywhere in the program.

Example: public int MyProperty { get; set; }

113
Q

What does the ‘private’ access modifier signify?

A

Accessible only within the same class.

private int myField;

114
Q

What does the ‘protected’ access modifier signify?

A

Accessible within the same class and by derived classes.

protected void MyMethod() { }

115
Q

What does the ‘internal’ access modifier signify?

A

Accessible only within the same assembly (project).

internal string MyInternalProperty { get; set; }

116
Q

What does the ‘protected internal’ access modifier signify?

A

Accessible within the same assembly or by derived classes in other assemblies.

protected internal int MyValue;

117
Q

What does the ‘private protected’ access modifier signify?

A

Accessible only within the same class or derived classes in the same assembly.

private protected void MyPrivateProtectedMethod() { }

118
Q

What does the ‘file’ access modifier signify?

A

Accessible only within the same file.

The ‘file’ access modifier was introduced in C# 11

file class MyFileClass { }

119
Q

True or False

Do the following statement correctly represents the structure of a method declaration in C#?

accessModifier returnType methodName(parameters{code block}

A

True

The structure of a method declaration in C# includes an access modifier, return type, method name, and parameters.

Methods provide a way to encapsulate and simplify repetitive tasks in C# programming.

120
Q

method in C#

A

In object-oriented programming (OOP), a method is a function that is associated with a class or an object. It defines the behavior or actions that an object of the class can perform. Methods operate on the data (fields or properties) of the class and are used to implement the functionality of an object.

Methods provide a structured way to process & modify data efficiently.

class Car
{
    public string Make { get; set; }
    public string Model { get; set; }

    // Method associated with the Car class
    public void Drive()
    {
        Console.WriteLine($"The {Make} {Model} is driving.");
    }
}
class Program
{
    static void Main()
    {
        Car myCar = new Car { Make = "Toyota", Model = "Corolla" };
        myCar.Drive(); // Calls the Drive method
    }
}
121
Q

What are the Key Characteristics of Methods in OOP?

A

Encapsulation: Methods allow you to encapsulate behavior within a class, keeping the implementation details hidden from the outside world.

Association with Objects: Unlike standalone functions, methods are tied to a specific class or object.

Polymorphism: Methods can be overridden in derived classes to provide specific behavior, enabling polymorphism.

Access Modifiers: Methods can have access modifiers (e.g., public, private) to control their visibility.

Methods in C# are fundamental to organizing and structuring code in a reusable and maintainable way. Their role in OOP ties them to classes, giving them access to data within objects.

122
Q

What is the difference between a method and a function in C#?

A

A function is a general term for a block of code that performs a task and can exist independently.

A method, in the context of OOP, is a function that is specifically tied to a class or object.

public int AddNumbers(int a, int b) {
   return a + b;
}
123
Q

Handling events with methods

A

Methods are crucial for building interactive applications. They can respond to user actions, such as mouse clicks or key presses, making your application responsive.

Typical Event-Handler signature (object sender, EventArgs e)

private void Button_Click(object sender, EventArgs e) {
   Console.WriteLine("Button clicked");
}
124
Q

Manipulating data with methods

A

Developers frequently use data-processing methods, like sorting arrays or modifying collections. Methods help ensure that these operations are executed consistently and efficiently.

A typical method can take and return a List object!

public List<int> SortList(List<int> numbers) {
   numbers.Sort();
   return numbers;
}
125
Q

Code Problem in C

A method for Circle Area Calculation

A
using System;
class Program {
    static void Main() {
        // Prompt the user for the radius of the circle
        Console.WriteLine("Enter the radius of the circle:");
        double radius = Convert.ToDouble(Console.ReadLine());

        // Call the function to calculate the area and store the result in 'area'
        double area = CalculateCircleArea(radius);

        // Output the result
        Console.WriteLine("The area of the circle is: " + area);
    }

    // Define the method to calculate the circle's area
    static double CalculateCircleArea(double radius) {
        return Math.PI * radius * radius;
    }
}
126
Q

Code Problem in C

A method for Trapezoid Area Calculation

A
using System;

public class Program {
    public static void Main() {
        // Prompt the user for the lengths of the two parallel sides and the height
        Console.WriteLine("Enter the length of the first parallel side (a):");
        decimal a = Convert.ToDecimal(Console.ReadLine());

        Console.WriteLine("Enter the length of the second parallel side (b):");
        decimal b = Convert.ToDecimal(Console.ReadLine());

        Console.WriteLine("Enter the height of the trapezoid:");
        decimal height = Convert.ToDecimal(Console.ReadLine());

        // Call the function to calculate the area and store the result in 'area'
        decimal area = CalculateTrapezoidArea(a, b, height);

        // Output the result
        Console.WriteLine("The area of the trapezoid is: " + area);
    }

    // Define the method to calculate the trapezoid's area
    static decimal CalculateTrapezoidArea(decimal a, decimal b, decimal height) {
        return (a + b) / 2 * height;
    }
}
127
Q

True or False

The following code snippet throws an error.

int sum = calcSum(5,7);
		Console.WriteLine("The sum is:" + sum);
A

False

The reason this code does not throw an error is because of implicit type conversion in C#.

The + operator in C# has overloaded behavior. When used with two numbers, it performs arithmetic addition. However, when one operand is a string, it performs string concatenation.

Console.WriteLine(“The sum is: “ + sum.ToString());

Since one operand is a string, C# automatically converts sum to a string using its .ToString() method.

128
Q

Pass by Value

A

Value Parameters (Pass by Value)
When a method receives a value parameter, it gets a copy of the original data.

Any modifications inside the method do not affect the original variable.

Used when you want to preserve the original value and avoid unintended changes.

void ModifyValue(int number)
{
    number = 10; // Changes only the local copy
}

int myNumber = 5;
ModifyValue(myNumber);
Console.WriteLine(myNumber); // Output: 5 (unchanged)
129
Q

Pass by Reference

A

Reference Parameters (Pass by Reference)
When a method receives a reference parameter, it gets a reference to the original variable.

Any modifications inside the method affect the original variable.

Used when you want to modify the original value or avoid unnecessary copying of large objects.

void ModifyReference(ref int number)
{
    number = 10; // Changes the original variable
}

int myNumber = 5;
ModifyReference(ref myNumber);
Console.WriteLine(myNumber); // Output: 10 (modified)
130
Q

Whether to use value parameters or reference parameters

A

Use value parameters when you want to protect the original data from modification.

Use reference parameters when you need to modify the original variable or optimize performance for large objects.

131
Q

What is the role of a parameter in a method?

A

Parameters are variables defined within a method’s signature that specify what input the method can accept.

A parameter is indeed a variable listed in the method’s definition that acts as a placeholder for the value to be passed during method execution.

132
Q

Explain the Single Responsibility Principle

A

The Single Responsibility Principle states that a class function or module should have only one reason to change, which means it should only be responsible for one specific functionality or task.

133
Q

Modularity

A

Modularity is the practice of dividing a program into separate, self contained units or modules, each responsible for a specific piece of functionality.

134
Q

let keyword

A

In C#, the let keyword is used in LINQ query expressions to introduce a new range variable and store the result of a subexpression. This allows you to reuse computed values within the query without recalculating them multiple times.

Enables complex queries

Improves readability | Optimizes performance | Enables complex queries

using System;
using System.Linq;

class Program
{
    static void Main()
    {
        string[] words = { "apple", "banana", "cherry", "date", "elderberry" };

        var query = from word in words
                    let length = word.Length // Store the length of each word
                    where length > 5
                    select new { word, length };

        foreach (var item in query)
        {
            Console.WriteLine($"{item.word} has {item.length} letters.");
        }
    }
}
135
Q

What are control structures?

A

Control structures are constructs that allow a program to execute different code based on conditions.

136
Q

Name two types of control structures.

A
  • if statements
  • switch statements
137
Q

Which debugging tool would you use to track the value of specific variables while your code is running?

A

A watch allows you to monitor the value of specific variables in real-time as the program runs, helping you detect changes step-by-step.

138
Q

What is the purpose of watches in debugging?

A

Tracks the value of specific variables while the code is running

Helps to spot anomalies like sudden changes in a variable’s value.

139
Q

How do logging statements assist developers?

A

Record real-time data during program execution

Useful for tracing behavior over time, especially in complex systems.

140
Q

What is the function of print statements in debugging?

A

Output variable values or execution flow directly to the console

Provides quick insights into the logic and helps trace the code’s path.

141
Q

What do breakpoints do in a debugging context?

A

Pause the code at a specific line for detailed inspection

Allows stepping through the code line by line to identify where issues occur.

142
Q

Fill in the blank: _____ are used to track the value of specific variables during code execution.

143
Q

What is the primary benefit of using breakpoints?

A

Isolate complex bugs by inspecting code execution line by line

144
Q

True or False

Microsoft Copilot helps developers by generating code, providing real-time suggestions, detecting errors, and optimizing code.

A

Microsoft Copilot assists developers in various ways, including code generation, real-time suggestions, error detection, and code optimization to streamline the coding process.

/explain - describe the issue /fix - write the code

Microsoft Copilot offers suggestions on how to resolve identified errors, saving time and effort during debugging.

145
Q

What is a class in object-oriented programming?

A

A class is a blueprint or template that defines a set of shared characteristics and behaviors for a group of entities.

A class in OOP is defined by its properties and method.

146
Q

What does an object represent in OOP?

A

An object represents an instance of a class, having unique properties and behaviors defined by that class.

147
Q

What is encapsulation in OOP?

A

Encapsulation is the principle of bundling data and methods within a class and restricting access to some of its components.

Encapsulation protects an object’s internal state by managing how data and methods are accessed and modified within a class.

148
Q

What are access modifiers used for in encapsulation?

A

Access modifiers control access levels to class components.

149
Q

Define the ‘private’ access modifier.

A

Private restricts access to the class, ensuring that data cannot be altered directly from outside the class.

150
Q

Define the ‘protected’ access modifier.

A

Protected allows access to the class and its subclasses, enabling inherited classes to use and extend the data and methods.

151
Q

Define the ‘public’ access modifier.

A

Public exposes data and methods to any application part, allowing wider access.

152
Q

What is abstraction in OOP?

A

Abstraction is defining what an object does without specifying how it does it.

153
Q

What are abstract classes?

A

Abstract classes define a common code base with some standard methods and some abstract methods without implementation.

154
Q

What is the purpose of interfaces in OOP?

A

Interfaces define a contract specifying what methods a class must implement without providing details.

155
Q

In OOP, what is a derived class in the context of inheritance?

A

A derived class is a class that inherits properties from a base class, enabling code reuse and extension.

156
Q

How does a derived class use polymorphism to provide different behavior for a method?

A

A derived class can use polymorphism by overriding a method, allowing it to define its own specific behavior different from the parent class’s method.

157
Q

Fundamental concepts in Object-Oriented Programming (OOP)

A

Encapsulation
Encapsulation protects the integrity of an object’s data.

Abstraction
Abstraction allows developers to create simplified interfaces.

Inheritance
Inheritance enables a new class to inherit properties and methods from an existing class, promoting code reuse and extension.

Polymorphism
Polymorphism allows a single method to perform different actions depending on the object, increasing code flexibility.

Inheritance establishes a hierarchical relationship between classes, and polymorphism allows them to modify or extend behaviors.

158
Q

What is a derived class in the context of inheritance?

A

A new class based on an existing class called the base class

159
Q

What does a derived class inherit from the base class?

A

All the properties and methods of the base class

160
Q

What is one of the key benefits of inheritance?

A

Code reusability

161
Q

How does inheritance help in code management?

A

Establishes hierarchical relationships and reduces redundancy

162
Q

What does polymorphism allow in OOP?

A

A single method to perform different tasks depending on the object

163
Q

What is method overriding in the context of polymorphism?

A

When a derived class implements a method already defined in the base class

164
Q

What can developers do by using polymorphism?

A

Extend the base class, override methods, promote code reuse

165
Q

What is the relationship between a base class and derived classes in terms of attributes?

A

Derived classes inherit common attributes from the base class

166
Q

How do derived classes introduce their unique methods?

A

By adding new methods or modifying existing ones

167
Q

In the context of inheritance, what is a base class?

A

A base class defines common properties and methods that can be inherited and used by derived classes.

168
Q

What is the purpose of using interfaces in C#?

A

Interfaces in C# define a set of methods that an implementing class must include without providing the implementation details.

169
Q

Steps to define a base class

A

Use an access modifier (public, private, protected).

Use the class keyword followed by the class name.

Define properties to hold data and methods to define actions.

public class Pool
{
    public int chlorineLevel;
    public int waterLevel;
    public Pool(int chlorine, int water)
    {
        chlorineLevel = chlorine;
        waterLevel = water;
    }
    public void PoolInfo()
    {
        Console.WriteLine($"Pool: {chlorineLevel}, {waterLevel}");
    }
}
170
Q

Steps to create a derived class

A

Declare like a base class but add a colon (:) followed by the base class name.

The derived class inherits properties and methods from the base class.

To create a derived class in C#, you use an access modifier (like public), followed by the derived class name, a colon, and the base class name.

public class Spa : Pool

{
    public int heatLevel;
    public Spa(int chlorine, int water, int heat)
        : base(chlorine, water)
    {
        heatLevel = heat;
    }
    public void SpaInfo()
    {
        Console.WriteLine($"Spa: {chlorineLevel}, {waterLevel}, {heatLevel}");
    }
}
171
Q

Steps for Method Overriding

A

Use the virtual keyword in the base class to declare methods that can be overridden.

In the derived class, use the override keyword to provide a specific implementation.

Developers use polymorphism by creating a virtual method in the base class, which can be overridden in any derived class to provide specific behavior.

public class Instrument
{
    public virtual void Play()
    {
        Console.WriteLine("Playing an instrument");
    }
}

public class Piano : Instrument
{
    public override void Play()
    {
        Console.WriteLine("The piano is playing");
    }
}
172
Q

Steps to using Interfaces

A

Define an interface with method signatures that derived classes must implement.

Implement the interface in derived classes.

public interface IPlayable

{
    void Play();
}

public class Guitar : IPlayable
{
    public void Play()
    {
        Console.WriteLine("The guitar is playing");
    }
}
173
Q

When to use inheritance? When to use polymorphism?

A

Use inheritance to create reusable base classes and extend their functionality with derived classes.

Use polymorphism through method overriding and interfaces to allow flexibility in method implementations across different classes.