MS Full-Stack, Front & Back-End Dev C2 Intro to Prog in C# Flashcards
What are the two main hosting models of Blazor
?
- Blazor WebAssembly
- Blazor Server
Both models enable C# to be used for interactive web applications.
What is Blazor WebAssembly
?
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.
What is the purpose of GitHub
?
A platform for version control and collaboration, allowing developers to manage and share code effectively.
It uses Git to track changes and facilitate teamwork.
What are key features of GitHub
?
- Version Control
- Collaboration
- Integration
- Open Source
These features enhance code management and teamwork.
Definition
Back-end development
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.
What is back-end development responsible for?
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.
What do back-end developers ensure?
That all the data the front-end needs is processed securely and efficiently.
What is the main focus of back-end developers?
Processing data securely and efficiently.
What is the purpose of the .NET environment?
A software development platform by Microsoft that simplifies building, deploying, and running applications across different operating systems.
Supports Windows, Linux, and macOS.
What types of applications can be developed using .NET?
- Web
- Desktop
- Mobile
- Cloud
- IoT
.NET’s versatility makes it suitable for diverse projects.
How do front-end engineers utilize programming skills?
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.
What tools do front-end developers use?
- HTML
- CSS
- JavaScript
- Frameworks like React and Angular
These tools help create responsive layouts and user interfaces.
What is the focus of back-end development?
Building and maintaining server-side logic, databases, and infrastructure that support the front-end.
Back-end developers ensure secure and scalable systems.
What is Visual Studio Code
?
A lightweight code editor that integrates seamlessly with the .NET environment to enhance developer productivity.
Supports writing, debugging, and deploying .NET applications.
What are some of the key features offered by Visual Studio Code as a cross-development environment?
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.
Visual Studio Code Workflow: Handling aspects of project development.
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.
What role does Visual Studio Code play in .NET projects?
It integrates with the .NET CLI to create, build, and manage .NET projects
It provides essential tools for writing, running, and debugging .NET projects
Which versions of the .NET SDK are currently installed in my computer?
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]
Which versions of the .NET runtime are currently installed in my computer?
Run:
dotnet –list-runtimes
You get an output similar to:
Five Best Practices for Organizing Files in a .NET Project
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.
What is the role of Program.cs in a .NET project?
It serves as the application’s entry point, where execution begins.
What information does the .csproj file contain?
Settings, dependencies, and configuration details.
What does the .csproj file tell the .NET build system?
How to build the project, which files to include, and which external libraries are needed.
What type of files does the obj folder hold?
Intermediate files generated during the build process.
These files are used temporarily during the build process and are not part of the final output.
What is the purpose of the bin directory in a .NET project?
To store compiled code necessary for the application to run.
The bin directory stores compiled code, including executable files and Dynamic Link Libraries (DLLs).
Which file should be included in a .gitignore file for a .NET project?
The bin and obj folders are often included in .gitignore to avoid committing build artifacts.
How do you clean the build output of a .NET project using CLI?
Use the dotnet clean command.
dotnet clean removes all compiled output files from the bin and obj directories.
What command-line tool is essential for creating new .NET projects?
.NET CLI for managing and creating projects.
The .NET CLI provides commands like dotnet new to create .NET projects.
Why is using pseudocode beneficial before writing actual code?
Pseudocode allows developers to focus on the logic and structure of the code before dealing with the syntax of a specific programming language.
What are the two main techniques for decomposing problems?
Top-down approach and modularization
Describe the top-down approach in problem decomposition.
Starts with a broad overview and gradually breaks it into detailed components
Define modularization in problem decomposition.
Divides a problem into self-contained units or modules, each performing a specific function
What is a benefit of modularization?
Allows for independent development and refinement of each module
When using the top-down approach to design software, what should be done after creating a broad design goal?
State goals and problems that are out of scope.
Stating what the software will not do helps refine the design goal and problem statement.
Which of the following best defines the bottom-up approach to problem-solving in software development?
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.
Top-Down Problem-Solving Approach
Definition and benefits | Implementation
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.
Bottom-Up Problem-Solving Approach
Definition and benefits | Implementation
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.
What is a strength of the top-down approach?
Best when there is a clear understanding of the problem
It allows for focused tasks and facilitates collaboration.
What is a weakness of the top-down approach?
May lack flexibility if the problem is not well-defined
This can hinder adaptability in dynamic situations.
What is a benefit of the bottom-up approach?
Allows for exploring problems without a clear initial definition
It is useful for scalability and flexibility.
What is a drawback of the bottom-up approach?
Can be unwieldy and unconstrained without clear goals
This may lead to inefficiencies in problem-solving.
When should the top-down approach be used?
For problems with a clearly defined high-level goal
This approach breaks down the goal into smaller tasks.
When is it appropriate to use the bottom-up approach?
When starting from the details to build a comprehensive solution
Especially useful when dealing with unknowns or needing to experiment.
AND operator in C#
&&
AND is represented by a double ampersand
Ex. condition_01 && condition_02, reads condition_01 AND condition_02
OR operator in C#
||
OR is represented by a double vertical bar
Ex. condition_01 || condition_02, reads condition_01 OR condition_02
NOT Equal operator in C#
!=
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
NOT operator in C#
!
NOT is represented by an exclamation sign
Ex. if !(condition_01) is true, then condition_01 must be false
Which of the following best describes the purpose of pseudocode in programming?
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.
Method definition and example in C#
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; }
Top-Down Approach
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.
Bottom-Up Approach
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.
Historical origin of the word “debugging”
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.
What is a logical error in a program?
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.
Debugger toolbar in VS Code
Visual Studio Code
The debugger toolbar in VS Code includes six commands:
- Continue
- Step Over
- Step Into
- Step Out
- Restart
- Stop
Debugging: Step Over
Visual Studio Code
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.
Debugging: Step Into
Visual Studio Code
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.
Debugging: Step Out
Visual Studio Code
Step Out completes the execution of the current function and returns to the calling function, then pauses.
Debugging: Restart
Visual Studio Code
Restart stops the current debugging session and starts it again from the beginning.
Debugging: Continue
Visual Studio Code
Continue resumes program execution until the next breakpoint is hit or the program ends.
What are Syntax errors?
Debugging
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.
What triggers Runtime errors?
Debugging
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.
Define Logical errors.
Debugging
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.
What is a Breakpoint in debugging?
Debugging
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 does Inspecting variables help in debugging?
Debugging
It involves checking the values of variables at different points in the code to determine if the program manipulates data as expected.
What does Stepping through code entail?
Debugging
Executing code one line at a time to observe its behavior closely and pinpoint the exact line where an error occurs.
What is the purpose of Printing error messages?
Debugging
To track the execution flow and identify where and why the code fails, especially useful for understanding unexpected behavior or crashes.
Which tool in Visual Studio Code is used to inspect variable values during debugging?
Debugging
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.
Basic structure of a C# program
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!"); } }
Handling user input via the Console
C#
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.
What is the purpose of the static keyword that precedes a variable or a method declaration?
The static keyword allows a variable or method to be accessible throughout the program without needing to create an instance of the class.
True or False
You can call a static method without instantiating the class containing it
C#
True
You can call a static method without instantiating the class containing it
True or False
Variables in C# hold data and are declared with specific types.
Variables in C# hold data and are declared with specific types.
Examples include:
int age = 25;
string name = “John”;
var count = 10;
What is the purpose of the var keyword when declaring a variable?
C#
The var keyword allows for type inference, where the compiler determines the variable’s type based on its assigned value.
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?
Categorical statement
Categorical statements are ideal for organizing data into groups based on criteria, such as age ranges.
What is the main purpose of flowcharts?
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.
What shape represents processes or actions in a flowchart?
Rectangles.
What do diamonds represent in flowcharts?
Decision points.
What do arrows indicate in a flowchart?
The direction of the flow.
What is the purpose of ovals in flowcharts?
To mark the start and end points.
Steps in creating an effective flowchart
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.
.GetType()
C#
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 } }
.Parse()
int number = int.Parse(numberString);
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 } }
.TryParse()
if (int.TryParse(input, out int result))
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."); } } }
Name the four data type conversion methods in C#
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).
What is mutability in reference to variables?
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;
.
What is the difference in C# between using const to declare a constant instead of using the readonly keyword?
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.
const
Variable declarations in C#
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.
readonly
Variable declarations in C#
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.
Which keyowrd is used to declare an immutable variable in C#?
static - const - readonly
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.
Key Types of Variables in C#
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};.
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.
True
What is the assignment operator in C#?
=
is the assignment operator.
Problems in C
Calculate the sum of the elements of an array
// 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);
Problems in C
Counting the number of vowels in a string
// 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);
Is this statement valid in C#?
float temperature = 22.5f;
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
Provide a simple code example
if
syntax
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."); }
Provide a simple code example
switch
syntax
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; }
Give an example of the switch
statement in C# with pattern matching for evaluation of a n object.
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; } } }
When to use a do-while
loop instead of a while
loop
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); } }
for loop
in C# syntax
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); }
while
loop in C# syntax
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++; }
do while
loop in C# syntax
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);
Why is important to optimize loops and what are some basic key loop optimization techniques?
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.
What is the benefit of using a switch statement with a loop?
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.
Write a simple code example
Integrating If-Else
with Loops
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); } }
True or False
Functions make code easier to mantain and update.
True
By using functions, developers can update code in one place rather than in multiple instances, making maintenance more efficient.
Structure of a function in C#
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; }
Key Benefits of Functions
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.
What are functions?
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.
True or false
A method is a function associated with an object in OOP, whereas a function is a general block of reusable code.
True
A method operates on data within an object, while a function can be used independently without being tied to a specific object.
What is an access modifier in C#?
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.
What does the ‘public’ access modifier signify?
Accessible from anywhere in the program.
Example: public int MyProperty { get; set; }
What does the ‘private’ access modifier signify?
Accessible only within the same class.
private int myField;
What does the ‘protected’ access modifier signify?
Accessible within the same class and by derived classes.
protected void MyMethod() { }
What does the ‘internal’ access modifier signify?
Accessible only within the same assembly (project).
internal string MyInternalProperty { get; set; }
What does the ‘protected internal’ access modifier signify?
Accessible within the same assembly or by derived classes in other assemblies.
protected internal int MyValue;
What does the ‘private protected’ access modifier signify?
Accessible only within the same class or derived classes in the same assembly.
private protected void MyPrivateProtectedMethod() { }
What does the ‘file’ access modifier signify?
Accessible only within the same file.
The ‘file’ access modifier was introduced in C# 11
file class MyFileClass { }
True or False
Do the following statement correctly represents the structure of a method declaration in C#?
accessModifier returnType methodName(parameters{code block}
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.
method
in C#
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 } }
What are the Key Characteristics of Methods in OOP?
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.
What is the difference between a method
and a function
in C#?
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; }
Handling events with methods
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"); }
Manipulating data with methods
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; }
Code Problem in C
A method for Circle Area Calculation
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; } }
Code Problem in C
A method for Trapezoid Area Calculation
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; } }
True or False
The following code snippet throws an error.
int sum = calcSum(5,7); Console.WriteLine("The sum is:" + sum);
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.
Pass by Value
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)
Pass by Reference
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)
Whether to use value parameters or reference parameters
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.
What is the role of a parameter in a method?
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.
Explain the Single Responsibility Principle
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.
Modularity
Modularity is the practice of dividing a program into separate, self contained units or modules, each responsible for a specific piece of functionality.
let
keyword
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."); } } }
What are control structures?
Control structures are constructs that allow a program to execute different code based on conditions.
Name two types of control structures.
- if statements
- switch statements
Which debugging tool would you use to track the value of specific variables while your code is running?
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.
What is the purpose of watches in debugging?
Tracks the value of specific variables while the code is running
Helps to spot anomalies like sudden changes in a variable’s value.
How do logging statements assist developers?
Record real-time data during program execution
Useful for tracing behavior over time, especially in complex systems.
What is the function of print statements in debugging?
Output variable values or execution flow directly to the console
Provides quick insights into the logic and helps trace the code’s path.
What do breakpoints do in a debugging context?
Pause the code at a specific line for detailed inspection
Allows stepping through the code line by line to identify where issues occur.
Fill in the blank: _____ are used to track the value of specific variables during code execution.
Watches
What is the primary benefit of using breakpoints?
Isolate complex bugs by inspecting code execution line by line
True or False
Microsoft Copilot helps developers by generating code, providing real-time suggestions, detecting errors, and optimizing code.
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.
What is a class in object-oriented programming?
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.
What does an object represent in OOP?
An object represents an instance of a class, having unique properties and behaviors defined by that class.
What is encapsulation in OOP?
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.
What are access modifiers used for in encapsulation?
Access modifiers control access levels to class components.
Define the ‘private’ access modifier.
Private restricts access to the class, ensuring that data cannot be altered directly from outside the class.
Define the ‘protected’ access modifier.
Protected allows access to the class and its subclasses, enabling inherited classes to use and extend the data and methods.
Define the ‘public’ access modifier.
Public exposes data and methods to any application part, allowing wider access.
What is abstraction in OOP?
Abstraction is defining what an object does without specifying how it does it.
What are abstract classes?
Abstract classes define a common code base with some standard methods and some abstract methods without implementation.
What is the purpose of interfaces in OOP?
Interfaces define a contract specifying what methods a class must implement without providing details.
In OOP, what is a derived class in the context of inheritance?
A derived class is a class that inherits properties from a base class, enabling code reuse and extension.
How does a derived class use polymorphism to provide different behavior for a method?
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.
Fundamental concepts in Object-Oriented Programming (OOP)
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.
What is a derived class in the context of inheritance?
A new class based on an existing class called the base class
What does a derived class inherit from the base class?
All the properties and methods of the base class
What is one of the key benefits of inheritance?
Code reusability
How does inheritance help in code management?
Establishes hierarchical relationships and reduces redundancy
What does polymorphism allow in OOP?
A single method to perform different tasks depending on the object
What is method overriding in the context of polymorphism?
When a derived class implements a method already defined in the base class
What can developers do by using polymorphism?
Extend the base class, override methods, promote code reuse
What is the relationship between a base class and derived classes in terms of attributes?
Derived classes inherit common attributes from the base class
How do derived classes introduce their unique methods?
By adding new methods or modifying existing ones
In the context of inheritance, what is a base class?
A base class defines common properties and methods that can be inherited and used by derived classes.
What is the purpose of using interfaces in C#?
Interfaces in C# define a set of methods that an implementing class must include without providing the implementation details.
Steps to define a base class
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}"); } }
Steps to create a derived class
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}"); } }
Steps for Method Overriding
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"); } }
Steps to using Interfaces
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"); } }
When to use inheritance? When to use polymorphism?
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.