Share
Explore

Professor Data's Notebook on learning C# MO2033

image.png
→ C# Language overview - → Overview of Type System - → Kinds of class Members - → Access Modifiers - → Fields - → Kinds of Parameters - → Static vs Instance Methods - → Virtual, Override, Abstract Methods - → Method Overloading Principles - → Static vs Instance Constructor - → Operator Precedence Rules - → Kinds of Statements - → Reserved Word - → Conditional Attribute - → Boxing and Unboxing - → LINQ methods Cheetsheat - → List vs Linq - → Linq Repeat method - Extras: → C# 11 Features - → C# 12 Preview Features - → DOs and DON'Ts in C# -
Course Visual Learning Roadmap:

November 17 Class Notes:
VIsibility
Exceptions
Asycn keyword
Override, polymorphism
Interface
Static keyword

Future:
LINQ
Struct

Code Drills:

Warm up:

Let's create a warmup code drill focusing on: - variable declaration and comparison
using if-then statements
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"); } } } }
image.png
**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
Exception Handling in C#
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
The Static Keyword in C#
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
Appendices
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:
image.png

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.

October 6 Introducing Visual Studio Code to program C#

Step 1: Install Visual Studio Code:

Student Lab Learning Guide

Setting up Microsoft Visual Studio Code & Running a Simple C# Program
1. Installation of Microsoft Visual Studio Code (VS Code)
Get some C# programs to run:
Open a FOLDER for your work

1.1. Navigate to the .
1.2. Download the installer suitable for your operating system. Earthlings have categorized them as Windows, macOS, and Linux.
1.3. Execute the installer and follow the on-screen directives. Grant the machine permission to install, as per Earth protocols.
2. Installing C# Extension for VS Code
The Magical Lexicon for C# Codewriting
2.1. Launch VS Code.
2.2. Seek the Extensions view by clicking on the square icon on the sidebar or pressing Ctrl+Shift+X.
2.3. In the search bar, input “C#”. Choose the C# extension provided by Microsoft and click on Install.
2.4. Await the completion of this ritual, and you shall have the power of C# at your fingertips within VS Code.
3. Installing .NET SDK
The Power Core of C#
3.1. Navigate to the .
3.2. Choose the appropriate SDK (Software Development Kit) for your platform and download.
3.3. Execute the downloaded installer and follow the installation rituals.
4. Crafting Your First C# Program
Summoning Algorithms from the Ether
4.1. In VS Code, seek the File menu and choose Open Folder. Designate a directory for your C# projects.
4.2. Within this chosen sanctuary, right-click (or use the corresponding gesture in your OS), and create a new file named HelloUniverse.cs.
4.3. Inject the following code into this file:

using System;

namespace PleiadesAcademy
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello, Universe! From Earth's College!");
}
}
}

4.4. Using the terminal built into VS Code (accessible via the Terminal > New Terminal menu), navigate to your project directory. Earthlings often use commands like cd your-directory-name for this task.
4.5. Once in the correct directory, perform this incantation:
bashCopy code
dotnet new console

This creates a new C# console application.
4.6. Finally, type:
bashCopy code
dotnet run



September 29:

Today we will learn Object Oriented Programming

First usage of computers in Business:
As Electronic Calculator
— > Computers were Vacuum Tubes/ Iron Core Memory

1970s: Data Processing: Magnetic Hard Drives, Silicon CPU
Computers got small, cheap, available to business: These cmputer were electronic Filing Cabinets


1990s: / The Internet became a Things / Free Pervasive WIFI : Smart Phones became ubiquitous / Social Media became accepted

1993: Sun Microsystems released Java // based on earlier “Smalltalk”

Now that we had OO languages : And hardware strong enough to run those languages:




Day 2:

Introduction to theory and concepts
Introduction to using GITHUB

Here are three simple C# programs to help beginners get started with C#:

1. Hello World - A simple program to display "Hello, World!".


using System;

namespace HelloWorld
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello, World!");
}
}
}

2. Basic Calculator - A program to add two numbers input by the user.


using System;

namespace BasicCalculator
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter the first number: ");
double num1 = Convert.ToDouble(Console.ReadLine());

Console.WriteLine("Enter the second number: ");
double num2 = Convert.ToDouble(Console.ReadLine());

double sum = num1 + num2;

Console.WriteLine($"The sum of {num1} and {num2} is: {sum}");
}
}
}

3. Guessing Game - A program where the user needs to guess a number between 1 and 10.


using System;

namespace GuessingGame
{
class Program
{
static void Main(string[] args)
{
Random rand = new Random();
int secretNumber = rand.Next(1, 11); // Generates a number between 1 and 10

Console.WriteLine("Guess a number between 1 and 10:");

int attempts = 3;
for (int i = 0; i < attempts; i++)
{
int guess = Convert.ToInt32(Console.ReadLine());

if (guess == secretNumber)
{
Console.WriteLine("Congratulations! You guessed the right number.");
return;
}
else if (i < attempts - 1)
{
Console.WriteLine($"Wrong guess. You have {attempts - i - 1} tries left.");
}
}

Console.WriteLine($"Sorry! The correct number was {secretNumber}.");
}
}
}

These programs introduce various fundamental concepts of C#, such as:
Basic Input and Output (Console.WriteLine and Console.ReadLine)
Variables and Data Types (int, double, string, etc.)
Control Structures (for loop, if statement)
Random Number Generation (Random class)
To run these, you can copy each program into a new C# console application in Visual Studio Code and then run the program.

Below is a simple C# program that takes the user's name and age, then invites them to play a guessing game:
csharpCopy code
using System;

namespace NumberGuessingGame
{
class Program
{
static void Main(string[] args)
{
// Get user's name and age
Console.WriteLine("Hello! What's your name?");
string userName = Console.ReadLine();

Console.WriteLine($"Nice to meet you, {userName}! How old are you?");
int age;
while (!int.TryParse(Console.ReadLine(), out age))
{
Console.WriteLine("Please enter a valid age.");
}

Console.WriteLine($"{userName}, would you like to play a guessing game? (y/n)");
char choice = Console.ReadKey().KeyChar;

if (choice == 'y' || choice == 'Y')
{
PlayGuessingGame();
}
else
{
Console.WriteLine("\nAlright, maybe next time!");
}
}

static void PlayGuessingGame()
{
Console.WriteLine("\nI'm thinking of a number between 1 and 10. Try to guess it!");

// Generate a random number between 1 and 10
Random rand = new Random();
int computerGuess = rand.Next(1, 11);

int userGuess;
while (true)
{
Console.WriteLine("Enter your guess:");
if (int.TryParse(Console.ReadLine(), out userGuess) && userGuess >= 1 && userGuess <= 10)
{
if (userGuess == computerGuess)
{
Console.WriteLine("Congratulations! You guessed the right number.");
break;
}
else
{
Console.WriteLine("That's not the number I was thinking of. Try again!");
}
}
else
{
Console.WriteLine("Please enter a number between 1 and 10.");
}
}
}
}
}

This program introduces the user to:
Basic Input and Output with Console
Decision Making using if and else
Loops (while loop)
Random Number Generation with the Random class
Data Parsing using int.TryParse
You can run this code in Visual Studio or Visual Studio Code to play the game.
Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
CtrlP
) instead.