Code Drills:
Warm up:
Let's create a warmup code drill focusing on:
- variable declaration and comparison
implementing a loop in C#. This exercise will be designed for execution in Visual Studio Code, a popular code editor for C# development. ---
**Title:** Warmup Code Drill: Variables, Comparisons, and Control Flow in C#
---
**Objective:**
To familiarize yourself with basic C# syntax including variables, comparison operations, if-then statements, and loops.
**Tools Needed:**
- Visual Studio Code
- .NET SDK installed on your computer
**Setup Instructions:**
1. **Install Visual Studio Code and .NET SDK:**
- Download Visual Studio Code from [here](https://code.visualstudio.com/).
- Install the .NET SDK from [Microsoft's official .NET download page](https://dotnet.microsoft.com/download).
2. **Configure Visual Studio Code for C#:**
- Open Visual Studio Code.
- Install the C# extension by searching for 'C#' in the Extensions view (`Ctrl+Shift+X`).
3. **Create a New C# Project:**
- Open a terminal in Visual Studio Code (`Ctrl+` `).
- Run `dotnet new console -o VariablesAndControlFlow` to create a new console application in a folder named `VariablesAndControlFlow`.
- Navigate to the project folder with `cd VariablesAndControlFlow`.
- Open this folder in Visual Studio Code with `code .`.
---
**Exercise:**
**Part 1: Variable Declaration and Comparison**
1. Declare two integer variables, `a` and `b`.
2. Assign values to these variables.
3. Write an if-then statement to compare these variables.
4. Print a message indicating whether `a` is greater than, less than, or equal to `b`.
**Part 2: Implement a Loop**
1. Create a simple for loop that iterates from 0 to 10.
2. Inside the loop, print the current loop index.
3. Add an if-then statement inside the loop to check if the loop index is even or odd.
4. Print a message for each iteration indicating whether the index is even or odd.
using System;
class Program
{
static void Main()
{
// Part 1: Variable Declaration and Comparison
int a = 5;
int b = 3;
if (a > b)
{
Console.WriteLine("a is greater than b");
}
else if (a < b)
{
Console.WriteLine("a is less than b");
}
else
{
Console.WriteLine("a is equal to b");
}
// Part 2: Implement a Loop
for (int i = 0; i <= 10; i++)
{
Console.WriteLine($"Current loop index: {i}");
if (i % 2 == 0)
{
Console.WriteLine($"{i} is even");
}
else
{
Console.WriteLine($"{i} is odd");
}
}
}
}
**Execution Instructions:**
1. Copy the provided sample code into the `Program.cs` file in your Visual Studio Code project.
2. Save the file.
3. Run the program by pressing `F5` or typing `dotnet run` in the terminal within the Visual Studio Code.
**Expected Output:**
- The program will first compare the two variables `a` and `b` and print the result.
- Then, it will iterate from 0 to 10, printing each number and stating whether it's even or odd.
---
This warmup drill will help you understand the basics of variable manipulation, conditional logic, and loop constructs in C#. Be sure to experiment with the code, changing values and logic to see different outcomes.
Table of Contents
Introduction to C# and Object-Oriented Programming Overview of C# and .NET Framework Principles of Object-Oriented Programming Working with Objects in C# Creating and Using Objects Object Properties and Methods Lab Exercise: Create a simple class and instantiate objects Visibility and Access Modifiers Understanding Public, Private, Protected, and Internal Encapsulation in Practice Lab Exercise: Implement encapsulation in a class Control Flow in C#: Loops and Conditional Statements Using if-then-else structures Iterating with for, foreach, while, and do-while loops Lab Exercise: Write a program with various control flow structures The try-catch-finally block Creating Custom Exceptions Lab Exercise: Implement exception handling in a file I/O operation Method Overriding and Polymorphism Understanding Inheritance Overriding methods in derived classes The concept of polymorphism in OOP Lab Exercise: Create a base class and derived class with overridden methods Understanding static members and methods When and why to use static Lab Exercise: Create a utility class with static methods Final Project: Building a Small Application Integrating learned concepts into a cohesive application Requirements and specifications Guided steps for development Appendix A: C# Coding Standards and Best Practices Appendix B: Additional Resources and Further Reading Example Lab Exercise (Section 2)
Objective: Focus our attention on Object Oriented Programming
Create a simple 'Book' class with properties and methods, and demonstrate object instantiation and usage.
Tasks:
Define a 'Book' class with properties such as Title, Author, and ISBN. Include methods like DisplayInfo() to print details of the book. In your main program, create OBJECT references / instances of the 'Book' class and call their methods. Sample Code for Reference:
class Book {
public string Title { get; set; }
public string Author { get; set; }
public string ISBN { get; set; }
public void DisplayInfo() {
Console.WriteLine($"Title: {Title}, Author: {Author}, ISBN: {ISBN}");
}
}
class Program {
static void Main(string[] args) {
Book myBook = new Book { Title = "C# Fundamentals", Author = "Dr. CSharp", ISBN = "123456" };
myBook.DisplayInfo();
}
}
Lecture and lab workbook: Statics and Handling Exceptions
static members
try-catch exceptions
polymorphism
**Title:** Mastering C#: Static Members, Exception Handling, and Polymorphism
---
### Chapter 1: Introduction
- **Objective:** Introduce the concepts of static members, exception handling, and polymorphism.
- **Content:**
- Overview of these concepts.
- Importance in C# programming.
### Chapter 2: Static Members in C#
- **Objective:** Understand and use static variables and methods.
- **Theory:**
- Definition of static members.
- Differences between static and instance members.
- Common use cases.
- **Lab Exercise:**
- Create a utility class with static methods.
- Use the class without instantiating it.
### Chapter 3: Exception Handling with Try-Catch
- **Objective:** Learn to write robust C# code using try-catch blocks.
- **Theory:**
- Concept of exceptions and error handling.
- The try-catch-finally construct.
- Custom exceptions.
- **Lab Exercise:**
- Write a program that deliberately causes an exception, then catch and handle it.
- Extend the program to include custom exception handling.
### Chapter 4: Polymorphism in C#
- **Objective:** Master polymorphism to write flexible and reusable code.
- **Theory:**
- Definition and types of polymorphism.
- Method overriding and overloading.
- Abstract classes and interfaces.
- **Lab Exercise:**
- Create a base class and derived classes.
- Implement method overriding.
- Demonstrate polymorphic behavior.
### Chapter 5: Integrated Project
- **Objective:** Combine all learned concepts in a comprehensive project.
- **Project Description:**
- Develop a small application that uses static methods, handles exceptions, and demonstrates polymorphism.
- Project requirements and specifications.
- **Guidance:**
- Step-by-step instructions to start the project.
- Tips for integrating different concepts.
### Chapter 6: Conclusion
- **Summary:**
- Recap of key learnings.
- **Further Resources:**
- Recommended books, websites, and tutorials for advanced study.
### Appendices
- **Appendix A: C# Coding Standards and Best Practices**
- **Appendix B: Solutions to Lab Exercises**
---
**Example Lab Exercise (Chapter 3):**
- **Objective:** Write a program that reads numbers from the console and calculates their sum. Use exception handling to deal with invalid input.
**Tasks:**
1. Prompt the user to enter numbers.
2. Use a loop to read numbers from the console.
3. Implement a try-catch block to handle `FormatException` when the user enters non-numeric input.
4. Display a friendly error message and continue execution.
using System;
class Program
{
static void Main()
{
int sum = 0;
while (true)
{
Console.Write("Enter a number (or 'exit' to finish): ");
string input = Console.ReadLine();
if (input.ToLower() == "exit")
break;
try
{
sum += int.Parse(input);
}
catch (FormatException)
{
Console.WriteLine("That's not a valid number. Please try again.");
}
}
Console.WriteLine($"The total sum is: {sum}");
}
}
```
---
This workbook layout provides a structured approach to teaching these key C# concepts. Each chapter combines theoretical content with practical exercises, reinforcing learning through application. The integrated project at the end ensures that students can apply their knowledge in a real-world context. The appendices provide additional resources for further study and reference.