Learn C# Β· 2/15

C# Fundamentals: Core Building Blocks

8 min read

πŸ‘‹ Welcome to the Matrix (of Data)

Welcome to the foundation of C#. If programming were a language, what we are about to cover are the nouns, verbs, and punctuation. Without these, your code is just a blank stare at a blinking cursor.

We are going to move away from "Hello World" and start building programs that actually remember things, do math, and make decisions.

Fun Fact: The first version of C# was originally named "Cool" (C-like Object Oriented Language). But they couldn't use it because of trademark laws. So, we got C# (which is musically a semi-tone higher than C).


πŸ› οΈ Getting Started: The Boilerplate

In modern C# (NET 6+), we use Top-Level Statements. This means you don't need a massive amount of code just to write a line of text. The compiler handles the entry point for you.

If you are running this in a standard console application Program.cs:

csharp
// Program.cs
// This is all you need to start writing code!
Console.WriteLine("System initialized...");

1. Variables and Data Types: Storing Your Information

🧐 The Problem

Imagine you are a waiter. A customer orders a "Spicy Chicken Burger." If you don't write it down (store it), you will forget it by the time you reach the kitchen. Computer memory works the same way. Without variables, a program has the memory span of a goldfish.

πŸ’‘ The Solution: Variables

A variable is a named storage location in the computer's memory that holds a value.
A data type defines what kind of value that storage location can hold (a number, a letter, a truth).

🏭 Industry Standards & Common Types

C# is a strongly typed language. You must tell the compiler what kind of data goes into the box.

The "Big 4" You Will Use 90% of the Time:

  1. int: Whole numbers. No decimals.
    • Use case: Counting loops, IDs, age.
  2. string: Text. A sequence of characters.
    • Use case: Names, addresses, messages.
  3. bool: True or False.
    • Use case: Is the user logged in? Is the feature enabled?
  4. decimal: High-precision fractional numbers.
    • Use case: MONEY. πŸ’°

Warning: Never use float or double for money. They use floating-point math, which can result in rounding errors (e.g., 10.00becoming10.00 becoming 9.999999). If you use double for financial calculations, an accountant somewhere in the world starts crying.

Code Example

csharp
// Declaration and Initialization
int playerLevel = 1; 
string playerName = "Neo";
bool isGameActive = true;

// The Financial Standard
decimal bankBalance = 1050.50m; // The 'm' suffix tells C# this is a decimal, not a double.

The var Keyword

In professional environments, you will often see var. This is Type Inference. The compiler figures out the type based on the value on the right side.

csharp
var currentScore = 100; // Compiler knows this is an int
var message = "Loading"; // Compiler knows this is a string

Best Practice: Only use var when the type is obvious from the right side of the assignment.

  • Good: var user = new User();
  • Bad: var result = GetData(); (What is result? A number? A string? A banana?)

2. Working with Strings and Text Manipulation

🧐 The Problem

Computers speak binary (010101). Humans speak text. We need efficient ways to combine words, insert data into sentences, and clean up messy input.

πŸ’‘ The Solution: String Interpolation

A string is an immutable sequence of characters. In C#, we use the string class to handle text.

Historically, developers used concatenation ("Hello " + name). This is messy and hard to read.
The industry standard is String Interpolation.

πŸ’» Hands-on Code

String Interpolation ($)

Put a $ before the quote, and you can inject variables directly using curly braces {}.

csharp
string firstName = "John";
string lastName = "Wick";
int dogsOwned = 1;

// The old, painful way (Avoid this)
// string bio = firstName + " " + lastName + " owns " + dogsOwned + " dog.";

// The Modern Way (Do this)
string bio = $"{firstName} {lastName} owns {dogsOwned} dog.";

Console.WriteLine(bio); 
// Output: John Wick owns 1 dog.

Essential String Methods

You typically need to clean data coming from users.

csharp
string messyInput = "   pAsSwOrD123   ";

// 1. Trim(): Removes whitespace from start and end
string trimmed = messyInput.Trim(); // "pAsSwOrD123"

// 2. ToUpper() / ToLower(): Normalization
string upper = trimmed.ToUpper(); // "PASSWORD123"

// 3. Contains(): Searching
bool hasPass = upper.Contains("PASS"); // true

// 4. Substring(): Extracting parts
// (Starting Index, Length)
string code = "ID-5541";
string idNumber = code.Substring(3); // "5541"

Under the Hood: Strings in C# are Immutable. This means every time you use .Replace() or .ToUpper(), C# isn't changing the original string; it is destroying the old one and creating a brand new one in memory. Be careful doing this inside massive loops!


3. Constants and Type Conversion (Casting)

🧐 The Problem

  1. Integrity: Some values (like Pi or the Speed of Light) should never change. If a bug changes them, physics breaks.
  2. Incompatibility: You have a double (10.5) but you need to fit it into an int (10). Square peg, round hole.

πŸ’‘ The Solution: const and Casting

Constants

A constant is a variable whose value is determined at compile-time and cannot be changed at runtime.

csharp
// If you try to change this later, the code won't run.
const double Pi = 3.14159; 
const int MaxRetries = 3;

Type Conversion (Casting)

Casting is the process of converting one data type into another.

1. Implicit Casting (Safe)
Converting a smaller type to a larger type. No data is lost.

  • int (small cup) ➑️ double (bucket).
csharp
int myInt = 9;
double myDouble = myInt; // Automatic. 9 becomes 9.0

2. Explicit Casting (Unsafe)
Converting a larger type to a smaller type. You must manually tell C#: "I know what I'm doing, lose the data if you have to."

  • double (bucket) ➑️ int (small cup). The water will spill (decimals get chopped off).
csharp
double myTemperature = 98.6;
int reportTemp = (int)myTemperature; // Manual casting

Console.WriteLine(reportTemp); 
// Output: 98 (The .6 is lost forever, not rounded, just truncated)

3. Parsing (String to Number)
This is the most frequent real-world scenario. You get text from a text box ("500") and need to do math with it.

csharp
string input = "500";
int number = int.Parse(input); // Converts string "500" to int 500

4. Operators: Math, Logic, and Comparisons

🧐 The Problem

Data is useless if it sits there. We need to manipulate it (Math), compare it (Relational), and make complex decisions based on it (Logical).

πŸ’‘ The Solution: Operators

Operators are symbols that perform operations on operands (variables/values).

Arithmetic (The Usual Suspects)

+, -, *, / (Division), % (Modulus).

Spotlight on Modulus (%):
Modulus gives you the remainder of a division.
It is extremely useful in programming for checking even/odd numbers or cycling through arrays.
10 % 3 = 1 (Because 3 goes into 10 three times, with 1 left over).

Comparison (Asking Questions)

These always return a bool (True/False).

  • == (Equal to) - Note: distinct from = which is assignment.
  • != (Not equal to)
  • > (Greater than)
  • < (Less than)

Logical (Making Decisions)

Used to combine multiple comparisons.

  1. && (AND): Both sides must be true.
  2. || (OR): At least one side must be true.
  3. ! (NOT): Flips true to false.
csharp
int battery = 15;
bool hasCharger = true;

// Logic: If battery is low AND I don't have a charger -> Panic.
bool shouldPanic = (battery < 20) && (!hasCharger); 
// Result: False (Because hasCharger is true)

Under the Hood: Short-Circuit Evaluation
C# is lazy (efficient).
In an && operation, if the first condition is False, C# won't even look at the second condition. Why bother? The result is already False. This saves processing power.


πŸš€ Real-Life Simulation: The Vending Machine

Let's combine everything into a logic check for a vending machine.

csharp
// 1. Variables (Data)
decimal itemPrice = 1.50m; // Decimal for money!
decimal moneyInserted = 2.00m;
bool isMachineOn = true;

// 2. Constants
const string CurrencySymbol = "$";

// 3. Logic & Operators
if (isMachineOn && moneyInserted >= itemPrice)
{
    // Arithmetic
    decimal change = moneyInserted - itemPrice;
    
    // Casting (Displaying logic often needs strings)
    // String Interpolation
    Console.WriteLine($"Dispensing item. Your change is {CurrencySymbol}{change}");
}
else
{
    Console.WriteLine("Error: Insufficient funds or Power outage.");
}

πŸ“š Further Reading & References

Never trust a guide that doesn't link to the source. Here is the official Microsoft Documentation (The Bible of C#):

  1. C# Built-in Types (Microsoft Learn)
  2. String Interpolation
  3. Casting and Type Conversions
  4. C# Operators

Next Steps: Now that you can store data and do math, the next logic step is controlling the flow of the program with if/else and switch statements! Keep coding. β˜•

Challenge

C# Invoice Processing Challenge

You are tasked with writing a C# script to process raw invoice data. Your script must clean and convert the data, perform calculations, and generate a final summary string.

Raw Data Provided:

  • Customer Name: " John Doe "
  • Product Information: "SKU-789-5"
  • Unit Price (as string): "120.75"
  • High Priority Flag (as string): "true"

Your Tasks:

  1. Define a const named PROCESSING_FEE of type decimal and set its value to 5.50.
  2. Declare variables to hold the processed data using the most appropriate types (string, int, decimal, bool).
  3. Normalize the Customer Name: Remove all leading and trailing whitespace from rawCustomerName and convert the result to uppercase. Store it in a normalizedName variable.
  4. Extract Product Quantity: The quantity is the number at the end of the rawProductInfo string. Extract this part of the string and parse it into an int. Store it in a quantity variable.
  5. Convert Price and Priority: Parse the rawUnitPrice string into a decimal and the rawHighPriority string into a bool.
  6. Calculate Costs:
    • Calculate the subTotal by multiplying the quantity by the unitPrice.
    • Calculate the grandTotal by adding the subTotal and the PROCESSING_FEE.
  7. Determine Order Status: Create a bool variable named isRushOrder. An order is a rush order if the grandTotal is greater than 500.00 AND the highPriority flag is true. Use short-circuiting logical operators.
  8. Generate Summary: Using string interpolation, create a final summary string assigned to the variable finalSummary. The format must be exactly: CUSTOMER: [NORMALIZED NAME] | TOTAL: $[GRAND TOTAL] | RUSH ORDER: [IS RUSH ORDER].

Expected result

Your code should correctly implement the following logic:

  • A const decimal named PROCESSING_FEE is declared and initialized to 5.50m.
  • A string variable normalizedName is declared and holds the value "JOHN DOE" after using Trim() and ToUpper().
  • An int variable quantity holds the value 5, obtained by using Substring() and int.Parse() on the rawProductInfo string.
  • A decimal variable unitPrice holds the value 120.75m after using decimal.Parse().
  • A bool variable highPriority holds the value true after using bool.Parse().
  • decimal variables subTotal and grandTotal are declared and correctly calculate the values 603.75 and 609.25 respectively. Note that implicit casting of the int quantity to decimal is expected during the calculation.
  • A bool variable isRushOrder is correctly evaluated to true using the && operator.
  • The finalSummary string variable is created using string interpolation ($"...") and matches the required format, containing the calculated values. For example: "CUSTOMER: JOHN DOE | TOTAL: $609.25 | RUSH ORDER: True".
csharp

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.