Practice library / More programming languages
Workbook · Easy · 3 hours
Introduction to C#
.NET, C# basics, and Windows development context for security work.
On this page 6 sections
C# is a major language of the Windows stack. It powers business tooling, internal web services, and many offensive payloads that must sign, blend in, or load through a .NET loader. A security engineer who reads C# can audit an internal app, tune an EDR rule, and understand how a red team builds a stager. This workbook introduces the language from zero: types, control flow, classes, interfaces, collections, LINQ, and exceptions. It also shows how to build and run a .NET project from the command line. The paired lab walks through an AppLocker bypass so the reader can see where this code lives in a real attack.
What You'll Learn
- Write C# programs with types, variables, control flow and methods
- Build classes, use inheritance and interfaces
- Store data in lists and dictionaries and query it with LINQ
- Handle errors with exceptions
- Create, build and run a .NET project from the command line
About This Workbook
C# is a major language of the Windows platform. Many administration tools, security products and the tools that defenders read when they analyse a program are written in C# and run on .NET. A security analyst who can read C# can also read a .NET sample in a decompiler and write small tools for log analysis.
This workbook teaches the language with small programs that process log lines. Every program is short enough to type. Every program in this workbook was compiled and run with .NET 8, and the output shown is the real output. All programs read text and print results. None of them touches a network or another system.
Set up
Install the .NET SDK, version 8 or newer, from the .NET download page of Microsoft. Then create a project.
dotnet --version
dotnet new console -o hello
cd hello
dotnet runExample output:
8.0.428
Hello, World!dotnet new console makes a folder with two files: hello.csproj (the project settings) and Program.cs (the code). dotnet run compiles and starts the program. In each worked example below, replace the content of Program.cs with the code shown and run dotnet run again.
Chapter 1 — Language Basics
Objectives
- Declare variables with the common types
- Explain integer division
- Use
if,switch,forandforeach - Write a method that returns a value
Explanation
C# is statically typed: every variable has a type, and the compiler checks it before the program runs. These types appear in almost every program.
| Type | Holds | Example |
|---|---|---|
int | Whole number, about plus or minus 2 billion | int port = 443; |
long | Larger whole number | long bytes = 5_000_000_000; |
double | Number with a fraction | double ratio = 3.5; |
bool | true or false | bool open = true; |
string | Text | string host = "web01"; |
int[] | Fixed-size array | int[] ports = { 22, 80, 443 }; |
var lets the compiler find the type from the value: var host = "web01"; is a string. The type is still fixed.
A string interpolation puts values in text: $"{host}:{port}" makes web01:443. Inside the braces, {port,5} pads the value to 5 characters.
Integer division drops the fraction. If both numbers are int, the result is int. 7 / 2 is 3, and double r = 7 / 2; still stores 3, because the division happens first. Write 7 / 2.0 to get 3.5.
Control flow decides which code runs:
if (condition) { ... } else { ... }runs one of two blocks.- A switch expression picks a value:
port switch { 22 => "ssh", _ => "other" }. The_arm matches everything else. for (int i = 0; i < 3; i++)repeats a block a set number of times.foreach (string line in lines)visits every item of a collection.
A method is a named block of code. It has a return type, a name and parameters. A method that uses static belongs to the program, not to an object.
Worked example
This program reads four scan results, splits each one, and prints a table. Put it in Program.cs.
string[] lines = { "22 open", "80 open", "3389 closed", "8080 open" };
foreach (string line in lines)
{
string[] parts = line.Split(' ');
int port = int.Parse(parts[0]);
bool open = parts[1] == "open";
Console.WriteLine($"{port,5} {Describe(port)} {(open ? "OPEN" : "closed")}");
}
static string Describe(int port) => port switch
{
22 => "ssh ",
80 => "http ",
443 => "https",
3389 => "rdp ",
_ => "other"
};Example output:
22 ssh OPEN
80 http OPEN
3389 rdp closed
8080 other OPENFollow the code line by line. line.Split(' ') cuts "22 open" into {"22", "open"}. int.Parse turns the text "22" into the number 22. The expression open ? "OPEN" : "closed" is a short if: it gives the first text when open is true. Describe is a method with one parameter, written with =>, which means "returns this value". Its body is a switch expression.
Practice questions
- Which type is a good fit for a TCP port number, and why?
- What does
double r = 7 / 2;store inr? How do you store 3.5? - Make
Describe(8443)return"alt"instead of"other". What do you change? - When do you choose
foreachand whenfor?
Answers
intis a good fit, because the numbers 0 to 65535 fit in it. Aushortalso fits, butintis the usual choice.- It stores
3. Both operands areint, so the division drops the fraction before the assignment. Write7 / 2.0or7.0 / 2to get3.5. - Add the line
8443 => "alt",before the_arm. Keep the text five characters wide,"alt ", if you want the table to stay aligned. - Use
foreachwhen you need every item and not its position. Useforwhen you need the index, or a fixed number of repeats.
Chapter 2 — Object-Oriented C#
Objectives
- Write a class with properties and a constructor
- Use an abstract class and inheritance
- Define and implement an interface
- Use a
recordfor plain data
Explanation
A class is a template for objects. It groups data (properties) and behaviour (methods). new ContainsRule("Failed login", "Failed password") makes one object, called an instance, and runs the constructor, the special method that sets it up.
A property is a field with access control. public string Name { get; } can be read from outside the class, and the class sets it only in its constructor. Access modifiers are public (any code), private (this class only) and protected (this class and its children).
Inheritance lets one class build on another. class ContainsRule : RuleBase means that ContainsRule has everything of RuleBase and can add or change behaviour. An abstract class cannot be created alone, and an abstract method has no body. Each child must provide one with the keyword override.
An interface lists what a type can do, with no code. A class that says : IRule promises to provide every member of the interface. Code that works with IRule does not need to know the exact class. A class can have one parent class and many interfaces.
A record is a short way to write a class that holds data. record Finding(string Rule, string Line); makes a type with two read-only properties. Two records with the same values are equal, and a class would need extra code for that.
Worked example
This program holds two kinds of detection rule behind one interface. It checks three log lines against both rules. Type declarations go after the top-level code.
var rules = new List<IRule>
{
new ContainsRule("Failed login", "Failed password"),
new StartsWithRule("Root login", "Accepted password for root"),
};
string[] log =
{
"Accepted password for root from 10.0.0.50",
"Failed password for deploy from 10.0.0.50",
"session closed for user deploy",
};
foreach (string line in log)
{
foreach (IRule rule in rules)
{
if (rule.Matches(line))
{
var finding = new Finding(rule.Name, line);
Console.WriteLine($"[{finding.Rule}] {finding.Line}");
}
}
}
interface IRule
{
string Name { get; }
bool Matches(string line);
}
abstract class RuleBase : IRule
{
public string Name { get; }
protected string Text { get; }
protected RuleBase(string name, string text)
{
Name = name;
Text = text;
}
public abstract bool Matches(string line);
}
class ContainsRule : RuleBase
{
public ContainsRule(string name, string text) : base(name, text) { }
public override bool Matches(string line) => line.Contains(Text);
}
class StartsWithRule : RuleBase
{
public StartsWithRule(string name, string text) : base(name, text) { }
public override bool Matches(string line) => line.StartsWith(Text);
}
record Finding(string Rule, string Line);Example output:
[Root login] Accepted password for root from 10.0.0.50
[Failed login] Failed password for deploy from 10.0.0.50Read the output first. The third line matches no rule, so it prints nothing. The loop calls rule.Matches(line) and does not care which class the rule is. This is polymorphism: one call, different behaviour. To add a new kind of rule, you write one new class. The loop does not change.
Practice questions
- Why does
RuleBasedeclareNamewith{ get; }and no setter? - What happens if
ContainsRulehas noMatchesmethod? - Write an
EndsWithRuleand add it to the list. - What does
new Finding("a", "b") == new Finding("a", "b")give? What would it give for a plain class?
Answers
A rule must not change its name after creation. With
{ get; }only the constructor sets the value, and no other code can change it by mistake.The program does not compile.
RuleBasedeclaresMatchesas abstract, so every non-abstract child must override it.Write this class and add
new EndsWithRule("Deploy user", "user deploy")to the list.class EndsWithRule : RuleBase { public EndsWithRule(string name, string text) : base(name, text) { } public override bool Matches(string line) => line.EndsWith(Text); }For the record it gives
true, because records compare their values. For a plain class it givesfalse, because==compares whether both names point to the same object, unless the class defines its own equality.
Chapter 3 — Practical C#
Objectives
- Use
List<T>andDictionary<TKey, TValue> - Filter and sort data with LINQ
- Catch an exception and return an exit code
- Explain what
dotnet buildanddotnet rundo
Explanation
A list (List<int>) is an array that grows. A dictionary (Dictionary<string, int>) maps a key to a value, for example an address to a count. Reading a missing key with counts["x"] throws an exception. counts.GetValueOrDefault("x") returns 0 instead.
LINQ is a set of methods to query collections: Where keeps items that pass a test, OrderBy sorts, Select changes each item. The test is a lambda: n => n > 4 means "for each n, is it bigger than 4?"
var nums = new List<int> { 5, 3, 9, 1 };
nums.Add(7);
Console.WriteLine(string.Join(",", nums.Where(n => n > 4).OrderBy(n => n)));Example output:
5,7,9An exception is an error that stops normal flow. try holds the code that can fail. catch (SomeException) handles one kind of error. finally always runs. Catch the specific exception that you can handle, and let the others stop the program. Prefer int.TryParse("abc", out int v) to int.Parse for input that can be wrong: it returns false and does not throw.
The .NET runtime runs your program. dotnet build compiles the code into an assembly, a .dll file in the bin folder that holds intermediate code. The runtime compiles that code to machine code when the program starts. dotnet run builds first, then starts the program. A namespace groups types, and a using line imports one. The console template turns on common namespaces such as System, System.IO and System.Linq, so the examples need no using lines. NuGet is the package source: dotnet add package <name> adds a library to the project.
A program returns an exit code to the operating system. 0 means success. A shell script reads it with $?.
Worked example
This program counts failed SSH logins by source address, like the first step of an investigation. First create the input file auth.txt in the project folder.
cat > auth.txt <<'EOF'
Failed password for root from 10.0.0.50 port 40144 ssh2
Failed password for deploy from 10.0.0.50 port 40152 ssh2
Accepted password for deploy from 10.0.0.50 port 40168 ssh2
Failed password for admin from 10.0.0.9 port 51000 ssh2
Failed password for root from 10.0.0.50 port 40170 ssh2
EOFPut this code in Program.cs.
string path = args.Length > 0 ? args[0] : "auth.txt";
var counts = new Dictionary<string, int>();
try
{
foreach (string line in File.ReadLines(path))
{
if (!line.Contains("Failed password")) continue;
string[] parts = line.Split(' ');
int i = Array.IndexOf(parts, "from");
string ip = parts[i + 1];
counts[ip] = counts.GetValueOrDefault(ip) + 1;
}
}
catch (FileNotFoundException)
{
Console.WriteLine($"File not found: {path}");
return 1;
}
foreach (var (ip, n) in counts.OrderByDescending(kv => kv.Value))
{
Console.WriteLine($"{n,3} {ip}");
}
return 0;Run it twice. The second run gives a file name that does not exist.
dotnet run
dotnet run -- missing.txt
echo $?Example output:
3 10.0.0.50
1 10.0.0.9
File not found: missing.txt
1Read the code in order. args holds the words after -- on the command line. continue skips lines that are not failures. Array.IndexOf(parts, "from") finds the position of the word from, and the next word is the address. The counts[ip] = ... + 1 line adds one to the count of that address, and starts at zero for a new address. OrderByDescending sorts the biggest count first. The (ip, n) in foreach splits each dictionary entry into its key and value. The accepted login is not counted, because it does not contain Failed password.
The program prints the message and returns exit code 1 when the file is missing. A script that calls this tool can then see the failure.
Practice questions
- Why does the worked example use
GetValueOrDefaultand notcounts[ip] + 1? - Which exception does
int.Parse("abc")throw, and how do you avoid it? - Show a LINQ expression that keeps only the addresses with 3 or more failures.
- What is the difference between
dotnet buildanddotnet run?
Answers
- The first time an address appears, it is not a key in the dictionary.
counts[ip]would throw aKeyNotFoundException.GetValueOrDefaultreturns0for a missing key. - It throws
FormatException. Useint.TryParse("abc", out int v). It returnsfalseand does not throw. In the example,vis0when the result isfalse. counts.Where(kv => kv.Value >= 3). With the sample file, this keeps10.0.0.50.dotnet buildcompiles the project and writes the assembly inbin.dotnet runbuilds when needed and then starts the program.
Next steps
You can now read and write short C# programs. Use these skills in two places:
- Read a .NET assembly in a decompiler and recognise classes, methods and exceptions, as in malware analysis.
- Write a small tool for your own lab logs, such as the counter in Chapter 3.
For the Windows command line that you use next to C#, continue with the Windows Command Line & PowerShell workbook.
Workbook complete. Write the failed-login counter again from memory, and add one new feature, such as a list of the accounts that each address tried.
Sign in to track progress and send feedback.