Continue learning on DevStudyHub

Want a longer, ordered course alongside these examples? Follow the C# tutorial on DevStudyHub to study types, methods, classes, collections, LINQ and asynchronous programming.

For other subjects, browse DevStudyHub programming tutorials and practice. Use the explanations here together with small programs you can run and change yourself.

More C# lessons and practice

Choose a topic below to open its full lesson on DevStudyHub. Read the explanation, try the example in the stated environment, and compare your result before continuing.

Module 1: .NET Architecture & C# Foundations

  1. .NET Unified Architecture: CLR, JIT & .NET 8 SDK
  2. Program Structure, Top-Level Statements & Program.cs
  3. Console I/O: Console.WriteLine, ReadLine & Formatting
  4. Namespaces, File-Scoped Namespaces & Global Usings

Module 2: Variables, CTS Types & Nullable Safety

  1. Common Type System (CTS), Primitives & The decimal Type
  2. Implicit Typing with var & Safe Conversions (TryParse)
  3. Value Types vs Reference Types: Stack, Heap & Boxing
  4. Nullable Reference Types & Null-Coalescing Operators

Module 3: Operators & Modern Pattern Matching

  1. Arithmetic, Logical & Compound Assignment Operators
  2. Modern Pattern Matching: Type Testing & Negated Patterns
  3. Switch Expressions, Relational & Property Patterns

Module 4: Control Flow & Selection Statements

  1. Control Flow: Selection Statements & Guard Clauses
  2. Ternary Operator (?:) & Target-Typed New Expressions
  3. Short-Circuit Logic & Bitwise Operations

Module 5: Loops & Collection Iteration

  1. While & Do-While Loops: Indefinite Iteration
  2. For Loops, Iteration Strides & Loop Scope
  3. Foreach Loops, IEnumerable & Collection Iteration

Module 6: Methods, Parameters & Local Functions

  1. Method Declarations, Signatures & Expression-Bodied Members
  2. Parameter Modifiers: ref, out & in (Pass by Reference)
  3. Params Keyword, Optional Parameters & Named Arguments
  4. Local Functions, Closures & Static Local Functions

Module 7: Strings, Interpolation & Text Formatting

  1. String Immutability, String Interning & Memory Allocation
  2. String Interpolation ($), Verbatim (@) & Raw Strings (C# 11)
  3. High-Performance Text Building: StringBuilder Architecture

Module 8: Arrays, Indices, Ranges & Span<T>

  1. Arrays: Multidimensional [,] vs Jagged [][] Arrays
  2. Indices and Ranges: Slice Syntax in C# 8
  3. High-Performance Zero-Allocation Slices: Span<T> & ReadOnlySpan<T>

Module 9: Classes, Encapsulation & Properties

  1. Classes, Object Instantiation & The this Keyword
  2. Constructors, Static Constructors & C# 12 Primary Constructors
  3. Properties: Auto-Properties, Backing Fields & init-Only Setters
  4. Access Modifiers & Enterprise Encapsulation

Module 10: Structs, Records & Immutability

  1. Structs: Value-Type Memory Semantics & readonly struct
  2. Records (C# 9+): Positional Syntax & Value-Based Equality
  3. Non-Destructive Mutation: with Expressions & record struct
  4. Tuple Deconstruction & Custom Deconstruct Methods

Module 11: Inheritance, Polymorphism & Interfaces

  1. Inheritance, The base Keyword & Protected Scope
  2. Polymorphism: virtual, override, new Shadowing & sealed
  3. Abstract Classes vs Interfaces & Interface Segregation
  4. Default Interface Methods & Multiple Implementation

Module 12: Generics & Generic Collections

  1. Generics: Generic Classes, Methods & Type Parameters <T>
  2. Generic Constraints: The where Clause
  3. Generic Collections: List, Dictionary, HashSet & Queues

Module 13: Delegates, Events & Lambda Expressions

  1. Delegates: Custom Delegates, Action & Func Types
  2. Events & The Publisher-Subscriber Architecture
  3. Lambda Expressions, Closures & Variable Capture

Module 14: LINQ (Language Integrated Query)

  1. LINQ Foundations: Method Syntax vs Query Syntax & Deferred Execution
  2. LINQ Operations: Filtering, Projection & Sorting
  3. LINQ Aggregations, Grouping & Quantifiers

Module 15: Asynchronous Tasks, File I/O & Exceptions

  1. Asynchronous Programming: async, await & Task Concurrency
  2. Structured Exception Handling & Modern File I/O

Module 16: C# Practical Examples

  1. Literals: writing values directly in C#
  2. Cancel an asynchronous operation safely
  3. Number to words: international grouping
  4. Number to words: Indian grouping
  5. Create an Excel workbook with C#
  6. Connect C# to Oracle with named parameters

Extra practice

  1. Trace changing state and check loop boundaries
  2. Make a small learning project reproducible
  3. Check a C# function before connecting a user interface

Follow the ordered C# learning path · Practice with coding games · Visit DevStudyHub

C# constructors and inheritance: trace two museum passes

A museum prints a name for each visitor and keeps one count of passes issued. Which values belong to each object? Which belong to the class? Create a .NET console project with dotnet new console -n MuseumPass. Replace Program.cs with the example, then run dotnet run --project MuseumPass from the parent folder.

using System;

Pass first = new DayPass();
var second = new DayPass("Mira");
Console.WriteLine(first.Label());
Console.WriteLine(second.Label(2));
Console.WriteLine(Pass.Issued);
Console.WriteLine(first.Kind());
Console.WriteLine(second.Kind());

interface ILabel { string Label(); }
abstract class Pass : ILabel
{
    public static int Issued { get; private set; }
    public string Holder { get; }
    static Pass() { Issued = 0; }
    protected Pass(string holder) { Holder = holder; Issued++; }
    public static string Prefix() => "Day";
    public abstract string Label();
    public virtual string Kind() => "Pass";
}
sealed class DayPass : Pass
{
    public DayPass() : this("Guest") { }
    public DayPass(string holder) : base(holder) { }
    public override string Label() => Prefix() + ": " + Holder;
    public string Label(int visits) => Label() + " x" + visits;
    public new string Kind() => "Day pass";
}

Trace the constructors

new DayPass()
  → DayPass("Guest")
      → Pass("Guest") → set Holder and increment Issued
The arrows show constructor delegation. The base constructor body finishes before the derived constructor bodies finish.

A class describes the pass; each call to new creates an object. A constructor has the class name and no return type. A method such as Label can be called later and returns a result. The parameterless DayPass constructor forwards a default name through this. The parameterized constructor uses base to initialize the inherited part. Both routes increment the count exactly once.

A nonstatic class with no declared instance constructor normally receives a compiler-generated parameterless constructor. Declaring an instance constructor removes that automatic one. Here the parameterless constructor is explicit because it must choose Guest.

Compare instance state and static state

Holder belongs to one object. Issued belongs to Pass and is shared. The static constructor initializes the type once before it is needed here. It has no parameters or access modifier and cannot be overloaded. Instance constructors run for each new object and can accept different parameters. An abstract class can have both constructors and static methods: the example calls Prefix without creating a Pass directly.

Override, overload or hide a method

Day: Guest
Day: Mira x2
2
Pass
Day pass

The first Label call uses the DayPass override even through a Pass variable. Label(int) is an overload: the argument list tells the compiler which method to call. Kind uses new, so the variable’s declared type determines which implementation is selected. Change new to override on Kind and both final lines become Day pass.

Abstract classes, interfaces and access

ILabel states what a caller can ask for. Pass adds shared state and initialization. An abstract class can contain zero abstract methods. An abstract subclass can defer an implementation, but a concrete subclass must supply it. Only a virtual, abstract or already-overridden method supports override. Overriding an ordinary virtual method is optional.

Public permits callers to read Holder. The private setter on Issued reserves writes to Pass. Protected permits DayPass to call the base constructor. An ordinary namespace-level class defaults to internal, visible in its assembly. Class members default to private. Protected internal allows callers in the same assembly or derived types elsewhere; private protected requires a derived type in the same assembly (or the declaring type itself).

DayPass is sealed, so its inheritance chain ends there. To try sealing only one method, remove sealed from the class and change its Label declaration to public sealed override string Label(). A subclass may now extend DayPass, but attempting to override that Label again gives a compiler error.

Microsoft’s guide to C# constructors

C# arrays for beginners: combine study sessions and find a value

One learner records two sessions on Monday and one on Tuesday. A jagged array lets each day hold a different number of sessions. How would you search across both days and add two late entries?

Use a .NET 8 console project. Run dotnet new console -n StudyLog, replace StudyLog/Program.cs with the example, then run dotnet run --project StudyLog.

Monday   [12, 8] ─┐
Tuesday  [15]    ─┴─ flatten → [12, 8, 15]
Late entries [8, 5]   append → [12, 8, 15, 8, 5]
Each number is a separate session, so the repeated eight belongs in the result.
using System;
using System.Linq;
using System.Collections.Generic;

int[][] days = { new[] { 12, 8 }, new[] { 15 } };
int[] extra = { 8, 5 };
int[] minutes = days.SelectMany(day => day).Concat(extra).ToArray();
Console.WriteLine(string.Join(", ", minutes));
Console.WriteLine(Array.IndexOf(minutes, 8));
Console.WriteLine(Array.IndexOf(minutes, 99));
IEnumerable<int> readings = minutes;
using var cursor = readings.GetEnumerator();
while (cursor.MoveNext()) Console.WriteLine(cursor.Current);
Console.WriteLine((new Duration(12) + new Duration(8)).Minutes);

readonly record struct Duration(int Minutes) {
    public static Duration operator +(Duration a, Duration b) =>
        new Duration(a.Minutes + b.Minutes);
}

SelectMany visits each day and yields its sessions. Concat appends the late entries. ToArray collects the results into a new array. The first output is 12, 8, 15, 8, 5. Array.IndexOf returns 1 for the first eight because indexing starts at zero. It returns −1 for 99. Check for that result before using an index.

Walk through a sequence with IEnumerable and IEnumerator

IEnumerable supplies a cursor. The cursor begins before the first item. Each successful MoveNext makes Current available. The loop prints all five durations on separate lines. An empty array produces zero lines. A foreach loop handles the same movement and disposal for you.

Give the plus operator a meaning for Duration

The operator accepts two Duration values and returns a new one. Its body adds their integer Minutes properties. The final line prints 20. Try changing the operands to 5 and 15, then predict whether either original value changes.

C# interview practice: two short quizzes

Give yourself one point per correct prediction. Reveal each answer after you explain your reasoning.

Quiz 1: Arrays and iteration

What does days[1][0] return?

15. The first index selects Tuesday and the second selects its first session.

Does merging remove the second eight?

No. Concat preserves every entry, including repeated values.

When should a loop stop reading Current?

As soon as MoveNext returns false. The cursor has passed the last item.

Quiz 2: Classes and construction

If a class declares only a constructor taking a name, will new Student() compile?

No. An accessible parameterless constructor must be declared explicitly in this case.

Can two methods be overloaded by changing only their return type?

No. Give them different parameter signatures so the compiler can distinguish calls.

Which counter should count every pass issued by the same class?

A static counter shares the count across instances. An instance field would give each pass its own counter. Follow the museum-pass example on this page to see the difference.

References: Microsoft’s C# array guide and operator overloading reference.

Trace a C# for loop, increment, decrement and switch

Paste the code into a console project. Predict which value each line prints before running it. In a for loop the initializer runs once, the condition is checked before each pass, and the update runs after the body.

for (int seats = 2; seats >= 0; seats--) {
    switch (seats) {
        case 0: Console.WriteLine("Full"); break;
        case 1: Console.WriteLine("Last seat"); break;
        default: Console.WriteLine("Seats available"); break;
    }
}
int n = 2;
Console.WriteLine(n++);
Console.WriteLine(++n);

The loop prints Seats available, Last seat, Full. The final lines print 2 and 4. The postfix expression supplies the old value and then increments n. The prefix expression increments it before supplying the value. A standalone seats-- reduces the counter once per pass.

logoblog

No comments:

Post a Comment

Please do not enter any spam link in the comment box.