Unit 1: Introduction to .NET and C#

CSE253 — .Net Programming 11 min read

I. Platform Orientation

.NET is a software development platform created by Microsoft for building applications that run on Windows, Linux, and macOS. Its central principle is managed execution: source code written in languages such as C# is compiled into Intermediate Language (IL), and the Common Language Runtime (CLR) executes that IL while providing services such as memory management, security, and exception handling.

  • Language independence: C#, F#, and Visual Basic can use the same runtime and class libraries.
  • Managed execution: The CLR controls memory allocation, garbage collection, type safety, and runtime errors.
  • Cross-platform development: Modern .NET applications can target Windows, Linux, and macOS.
  • Reusable libraries: The .NET Class Library provides ready-made types for files, collections, networking, dates, and more.
  • Project-based conventions: Source code, dependencies, settings, and build information are organized in a project file.
  • Package-based extensibility: NuGet allows applications to use third-party and Microsoft libraries.

II. Introduction to .NET and Its Features

.NET is an open-source, general-purpose platform for developing console, web, desktop, mobile, cloud, and service applications. Modern .NET is distributed through the .NET SDK and uses a unified runtime and tooling model.

A. Introduction to .NET and its features

This subsection establishes the purpose and major capabilities of the .NET platform.

  • Application support: .NET can build console programs, ASP.NET Core web applications, Windows desktop applications, cloud services, and .NET MAUI mobile or desktop applications.
  • Common runtime: Programs compiled from different .NET languages can execute through the CLR because they use a common type system and IL.
  • Automatic memory management: Objects no longer referenced are identified by the garbage collector and their memory is reclaimed automatically.
  • Strong typing: A variable declared as int cannot normally receive a string, helping detect errors during compilation.
  • Asynchronous programming: The async and await keywords support non-blocking operations such as file and network access.
  • Open-source ecosystem: The .NET platform and many libraries are developed publicly, with source code hosted on GitHub.
  • Performance: JIT compilation, ahead-of-time compilation options, and optimized libraries support high-performance applications.

III. .NET Versions and Execution Components

.NET has changed from a Windows-focused framework into a unified, cross-platform platform. Understanding its versions and execution components prevents confusion when selecting tools and project templates.

A. Difference between .NET Framework, .NET Core and .NET

This comparison distinguishes the original Windows platform, its cross-platform successor, and the current unified platform.

  • .NET Framework: The original implementation, released in the early 2000s, is Windows-only and includes technologies such as Windows Forms, WPF, and ASP.NET Framework. Its latest major release is .NET Framework 4.8.1.
  • .NET Core: Introduced in 2016, it was modular, open-source, and cross-platform. Versions were named .NET Core 1.0 through .NET Core 3.1.
  • Modern .NET: Beginning with .NET 5 in 2020, Microsoft removed “Core” from the name and unified the platform. Versions such as .NET 6, .NET 7, .NET 8, and .NET 9 use the command dotnet.
  • Compatibility: .NET Framework applications may require Windows-specific APIs, while modern .NET applications generally provide better cross-platform support.
  • Version selection: New applications normally use a supported modern .NET release; existing enterprise applications may continue using .NET Framework for compatibility.

B. .NET SDK and Runtime

The SDK supplies development tools, while the runtime supplies the components needed to execute an application.

  • SDK contents: The SDK includes the CLI, compiler, project templates, MSBuild, testing tools, and commands such as dotnet new and dotnet build.
  • Runtime contents: The runtime includes the CLR and runtime libraries required to run a compiled application.
  • Development machine: A developer installs the SDK because it can also run applications.
  • Deployment machine: A machine that only runs an application may install the appropriate runtime instead of the full SDK.
  • Verification: Installed SDKs and runtimes can be inspected with:
    BASH
      dotnet --list-sdks
      dotnet --list-runtimes
  • Target framework: A project such as <TargetFramework>net8.0</TargetFramework> identifies the .NET version for which it is built.

C. Common Language Runtime (CLR)

The CLR is the execution environment responsible for managing and running .NET programs.

  • Compilation process: C# source is compiled into IL stored in an assembly, usually a .dll or executable.
  • JIT compilation: The Just-In-Time compiler converts IL into machine code for the current processor during execution.
  • Garbage collection: The GC tracks managed objects and releases memory that is no longer reachable.
  • Exception handling: Runtime failures are represented by objects such as FileNotFoundException and can be handled with try and catch.
  • Type safety: The CLR validates operations involving types, reducing invalid memory access and unsafe conversions.
  • Interoperability: Managed code can interact with native operating-system libraries through mechanisms such as P/Invoke.

D. .NET Class Library

The .NET Class Library is the standard collection of reusable types that supports common programming tasks.

  • Collections: List<T>, Dictionary<TKey,TValue>, and Queue<T> store and organize data.
  • Input and output: System.IO.File can read or write files, for example File.ReadAllText("data.txt").
  • Networking: Namespaces such as System.Net.Http provide HttpClient for HTTP requests.
  • Data and time: DateTime, DateOnly, TimeSpan, and numeric types represent common values.
  • Language features: System.String, System.Linq, and System.Threading.Tasks support text processing, queries, and asynchronous work.
  • Namespaces: Namespaces group related types and avoid naming conflicts; using System; allows shorter references to types in System.

IV. Development Tools and Command-Line Workflow

.NET development can be performed through a full integrated development environment or lightweight editor combined with the CLI.

A. Setting up development environment using Visual Studio and VS Code

This subsection describes the two common development environments.

  • Visual Studio: Install the required workload, such as “ASP.NET and web development” or “.NET desktop development.” Visual Studio provides project creation, IntelliSense, debugging, breakpoints, testing, and graphical NuGet management.
  • VS Code: Install the .NET SDK, VS Code, and the official C# extension or C# Dev Kit. VS Code provides editing, IntelliSense, debugging, and terminal-based project management.
  • SDK check: Run dotnet --version in a terminal to confirm that the SDK is available.
  • Debug configuration: Visual Studio stores settings in its solution environment; VS Code commonly uses .vscode/launch.json and tasks.json when custom configurations are needed.
  • Source control: Both environments integrate with Git, showing changed files and supporting commits.

B. Introduction to .NET CLI and commonly used CLI commands

The .NET CLI is a cross-platform command-line interface for creating, building, running, testing, and publishing applications.

  • Create a project: dotnet new console -n HelloApp creates a console project named HelloApp.
  • Enter the project: cd HelloApp changes the terminal’s working directory.
  • Restore dependencies: dotnet restore downloads packages listed by the project; most build commands perform this automatically.
  • Build code: dotnet build compiles the project and reports compiler errors.
  • Run code: dotnet run builds when necessary and launches the application.
  • Create a solution: dotnet new sln -n SchoolApp creates a solution; dotnet sln add HelloApp/HelloApp.csproj adds a project.
  • Test code: dotnet test builds and executes test projects.
  • Publish output: dotnet publish -c Release creates deployable output using the Release configuration.
  • Inspect help: dotnet --help or dotnet new --list displays available commands or templates.

V. Project Organization and Dependencies

A .NET application is defined by its project metadata, source files, generated output, and external package references.

A. Project structure in .NET applications

This subsection explains the files and directories commonly found in a project.

  • .csproj file: The XML project file identifies the target framework and dependencies:
    XML
      <PropertyGroup>
        <OutputType>Exe</OutputType>
        <TargetFramework>net8.0</TargetFramework>
        <Nullable>enable</Nullable>
      </PropertyGroup>
  • Program.cs: The usual entry-point source file. Modern templates may use top-level statements instead of an explicit Main method.
  • bin/: Contains compiled binaries and runtime-specific output after building.
  • obj/: Contains intermediate build files and generated metadata; it should normally not be committed to Git.
  • Solution file: A .sln file groups multiple related projects, such as an application and its test project.
  • Configuration files: Files such as appsettings.json commonly store application settings, especially in web applications.
  • Target framework: net8.0, for example, controls which APIs and runtime the project expects.

B. NuGet Package Manager

NuGet is the package management system used to distribute and consume .NET libraries.

  • Package reference: A project records a dependency with:
    XML
      <PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
  • CLI installation: dotnet add package Newtonsoft.Json adds the latest compatible package reference.
  • Restore behavior: dotnet restore reads package references and obtains packages from configured feeds.
  • Version control: A package version such as 13.0.3 makes builds more reproducible than an unspecified dependency.
  • Transitive dependencies: A package may depend on other packages, which NuGet resolves automatically.
  • Security and maintenance: Packages should be obtained from trusted sources and updated carefully because upgrades can change APIs or behavior.

C. Building and executing .NET applications

Building transforms source code into executable output, while execution loads that output through the runtime.

  • Build stages: The compiler checks C# syntax and types, produces IL, and writes assemblies under bin/Debug/<framework>/ or bin/Release/<framework>/.
  • Debug versus Release: Debug builds favor diagnostics; Release builds apply optimizations for deployment.
  • Execution: dotnet run starts a framework-dependent application using the installed runtime.
  • Direct execution: A compiled DLL can be launched with dotnet MyApp.dll.
  • Self-contained publishing: dotnet publish --self-contained includes a runtime for a selected operating system and architecture, increasing deployment size.
  • Failure diagnosis: Compiler errors stop the build; runtime exceptions occur after successful compilation and require debugging or exception handling.

VI. C# Language and Program Structure

C# is a strongly typed, object-oriented language designed for the .NET platform. It supports procedural, object-oriented, functional, and asynchronous programming styles.

A. Introduction to C

This subsection introduces the language’s essential characteristics.

  • Types and variables: int count = 3; declares an integer variable, while string name = "Asha"; declares text.
  • Object orientation: Classes define data and behavior; an object is an instance created from a class.
  • Control flow: if, switch, for, while, and foreach control execution.
  • Methods: A method groups reusable behavior and can declare a return type, parameters, and access modifier.
  • Properties: Properties expose controlled access to object data, such as public string Name { get; set; }.
  • Nullability: With nullable reference types enabled, string? explicitly permits a null reference and encourages compiler warnings for unsafe use.
  • Compilation: The C# compiler converts .cs files into IL within a .NET assembly.

B. C# program structure

A C# program contains statements, declarations, namespaces, types, and an entry point.

  • Minimal program: Modern templates can use top-level statements:
    CSHARP
      Console.WriteLine("Hello, .NET!");

    Console.WriteLine writes a line to standard output.
  • Explicit structure: The equivalent traditional form is:
    CSHARP
      using System;
    
      namespace HelloApp;
    
      class Program
      {
          static void Main(string[] args)
          {
              Console.WriteLine("Hello, .NET!");
          }
      }
  • using directive: using System; makes types in the System namespace available without fully qualifying them.
  • Namespace: namespace HelloApp; logically groups types and can reflect the project’s organization.
  • Class: Program contains application behavior in the explicit form.
  • Main method: static void Main(string[] args) is the conventional entry point; args contains command-line arguments.
  • Syntax conventions: Statements usually end with semicolons, blocks use braces, and identifiers commonly follow PascalCase for types and methods and camelCase for local variables.

VII. Git and GitHub

Git records source-code history locally, while GitHub hosts Git repositories for collaboration and remote backup.

A. Introduction to Git and GitHub for source code management

This subsection explains the basic workflow for managing .NET source code safely.

  • Repository: git init creates a local repository containing a hidden .git directory.
  • Working tree and staging area: Modified files exist in the working tree; git add Program.cs places selected changes in the staging area.
  • Commit: git commit -m "Create console application" records a permanent snapshot with a message.
  • Status and history: git status shows changed and untracked files; git log --oneline displays compact commit history.
  • Ignore generated files: A .gitignore should exclude bin/, obj/, user-specific IDE files, and secrets such as local credentials.
  • Remote repository: GitHub stores a shared remote repository. git remote add origin <url> connects the local repository to it.
  • Synchronization: git push -u origin main uploads commits; git pull retrieves and integrates remote changes.
  • Branches: git switch -c feature/login creates an isolated line of development that can later be merged into main.
  • Collaboration principle: Commits should be focused and descriptive, while source code, project files, and reproducible configuration should be tracked rather than generated build output.