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:
// 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:
int: Whole numbers. No decimals.- Use case: Counting loops, IDs, age.
string: Text. A sequence of characters.- Use case: Names, addresses, messages.
bool: True or False.- Use case: Is the user logged in? Is the feature enabled?
decimal: High-precision fractional numbers.- Use case: MONEY. π°
Warning: Never use
floatordoublefor money. They use floating-point math, which can result in rounding errors (e.g., 9.999999). If you usedoublefor financial calculations, an accountant somewhere in the world starts crying.
Code Example
// 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.
var currentScore = 100; // Compiler knows this is an int
var message = "Loading"; // Compiler knows this is a stringBest 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 {}.
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.
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
- Integrity: Some values (like Pi or the Speed of Light) should never change. If a bug changes them, physics breaks.
- Incompatibility: You have a
double(10.5) but you need to fit it into anint(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.
// 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).
int myInt = 9;
double myDouble = myInt; // Automatic. 9 becomes 9.02. 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).
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.
string input = "500";
int number = int.Parse(input); // Converts string "500" to int 5004. 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.
&&(AND): Both sides must be true.||(OR): At least one side must be true.!(NOT): Flips true to false.
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 isFalse, 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.
// 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#):
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:
- Define a
constnamedPROCESSING_FEEof typedecimaland set its value to5.50. - Declare variables to hold the processed data using the most appropriate types (
string,int,decimal,bool). - Normalize the Customer Name: Remove all leading and trailing whitespace from
rawCustomerNameand convert the result to uppercase. Store it in anormalizedNamevariable. - Extract Product Quantity: The quantity is the number at the end of the
rawProductInfostring. Extract this part of the string and parse it into anint. Store it in aquantityvariable. - Convert Price and Priority: Parse the
rawUnitPricestring into adecimaland therawHighPrioritystring into abool. - Calculate Costs:
- Calculate the
subTotalby multiplying thequantityby theunitPrice. - Calculate the
grandTotalby adding thesubTotaland thePROCESSING_FEE.
- Calculate the
- Determine Order Status: Create a
boolvariable namedisRushOrder. An order is a rush order if thegrandTotalis greater than500.00AND thehighPriorityflag istrue. Use short-circuiting logical operators. - 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 decimalnamedPROCESSING_FEEis declared and initialized to5.50m. - A
stringvariablenormalizedNameis declared and holds the value"JOHN DOE"after usingTrim()andToUpper(). - An
intvariablequantityholds the value5, obtained by usingSubstring()andint.Parse()on therawProductInfostring. - A
decimalvariableunitPriceholds the value120.75mafter usingdecimal.Parse(). - A
boolvariablehighPriorityholds the valuetrueafter usingbool.Parse(). decimalvariablessubTotalandgrandTotalare declared and correctly calculate the values603.75and609.25respectively. Note that implicit casting of theintquantity todecimalis expected during the calculation.- A
boolvariableisRushOrderis correctly evaluated totrueusing the&&operator. - The
finalSummarystring 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".