C# and .NET Core Fundamentals: Essential Programming Concepts

Posted by Anonymous and classified in Computers

Written on in English with a size of 14.54 KB

.NET Framework and Its Core Components

The Microsoft .NET Framework is a comprehensive and consistent programming model developed by Microsoft for building applications with visually stunning user experiences, seamless and secure communication, and the ability to model a range of business processes. The .NET Framework is a software development platform used for building and running Windows applications. It provides a controlled programming environment where software can be developed, installed, and executed primarily on Windows-based operating systems.

Key Components of .NET Framework:

  1. Common Language Runtime (CLR): The CLR is the execution engine for .NET applications. It provides core services such as:
    • Memory management (garbage collection)
    • Thread management
    • Exception handling
    • Type safety
    • Security
    • Just-In-Time (JIT) compilation
  2. .NET Class Library (Base Class Library - BCL): This is a rich set of reusable classes, interfaces, and value types that provide access to system functionality.
  3. Languages Supported: The .NET Framework supports multiple languages, including:
    • C#
    • VB.NET
    • F#
    • C++/CLI
  4. Common Type System (CTS): Defines how data types are declared, used, and managed in the .NET Framework. Ensures that types are consistent across all .NET languages.
  5. Common Language Specification (CLS): A set of rules and guidelines that languages must follow to be compatible with .NET. Allows interoperability between different .NET languages.
  6. Application Domains and Assemblies: Application Domains are isolated environments where applications run, providing security and isolation.
  7. ASP.NET and Windows Forms: ASP.NET is a framework for building web applications. Windows Forms is used for creating graphical desktop applications.

C# Finalizers and the 'base' Keyword

A finalizer is a special method in C# used to perform cleanup operations before an object is destroyed by the garbage collector.

Finalizer Example:

using System;

class Demo
{
    ~Demo()
    {
        Console.WriteLine("Finalizer called. Object is being destroyed.");
    }
}

class Program
{
    static void Main()
    {
        Demo obj = new Demo();
        obj = null;
        GC.Collect();
        Console.ReadLine();
    }
}

Using the base Keyword in C#:

The base keyword is used in C# to access members (methods, properties, or constructors) of the base (parent) class from the derived (child) class.

base Keyword Example:

using System;

class Parent
{
    public Parent() => Console.WriteLine("Parent constructor");
    public void ShowMessage() => Console.WriteLine("Parent message");
}

class Child : Parent
{
    public Child() : base() => Console.WriteLine("Child constructor");
    public void Display()
    {
        base.ShowMessage();
        Console.WriteLine("Child message");
    }
}

class Program
{
    static void Main()
    {
        new Child().Display();
    }
}

C# Operator Overloading: Binary Operators

Operator overloading allows you to define custom behavior for operators (like +, -, *, etc.) when they are used with user-defined types (like classes or structs). You use the operator keyword with a function. The operator must be overloaded as a static method. Commonly overloaded operators include +, -, *, /, ==, !=, etc.

Binary Operator Overloading Example:

using System;

class Complex
{
    public int real, imag;

    public Complex(int r, int i)
    {
        real = r;
        imag = i;
    }

    public static Complex operator +(Complex c1, Complex c2)
    {
        return new Complex(c1.real + c2.real, c1.imag + c2.imag);
    }

    public void Display()
    {
        Console.WriteLine($"{real} + {imag}i");
    }
}

class Program
{
    static void Main()
    {
        Complex c1 = new Complex(3, 4);
        Complex c2 = new Complex(5, 6);
        Complex c3 = c1 + c2;
        c3.Display();
    }
}

Inheritance in C#: Multilevel and Multiple

Inheritance is an important concept in Object-Oriented Programming (OOP) that allows a class to inherit properties and methods from another class. It promotes code reuse, extensibility, and hierarchical classification. The class that inherits is called the derived class (child). The class being inherited from is called the base class (parent).

Multilevel Inheritance:

using System;

class A
{
    public void ShowA() => Console.WriteLine("A method");
}

class B : A
{
    public void ShowB() => Console.WriteLine("B method");
}

class C : B
{
    public void ShowC() => Console.WriteLine("C method");
}

class Program
{
    static void Main()
    {
        new C().ShowA();
        new C().ShowB();
        new C().ShowC();
    }
}

Multiple Inheritance (via Interfaces):

using System;

interface IFirst
{
    void ShowFirst();
}

interface ISecond
{
    void ShowSecond();
}

class Multiple : IFirst, ISecond
{
    public void ShowFirst() => Console.WriteLine("From IFirst");
    public void ShowSecond() => Console.WriteLine("From ISecond");
}

class Program
{
    static void Main()
    {
        new Multiple().ShowFirst();
        new Multiple().ShowSecond();
    }
}

Object-Oriented vs. Object-Based Programming

Here's a differentiation between Object-Oriented Programming (OOP) and Object-Based Programming (OBP):

  • Object-Oriented Programming (OOP):
    • Programming model based on objects and classes.
    • Supports inheritance.
    • Uses both classes and objects.
    • More complex due to full OOP features.
    • Better real-world modeling through class hierarchies.
  • Object-Based Programming (OBP):
    • Programming model based only on objects, without classes.
    • Does not support inheritance.
    • Uses only objects, no class-based hierarchy.
    • Simpler and suitable for smaller applications.
    • Limited in modeling complex real-world relationships.

Common Language Runtime (CLR) and Its Features

CLR stands for Common Language Runtime. It is the heart of the .NET Framework and works like a virtual machine that manages the execution of .NET programs.

Key Features of CLR:

  • Memory Management: CLR automatically allocates and releases memory using Garbage Collection, reducing memory leaks.
  • Language Interoperability: CLR allows code written in different .NET languages (C#, VB.NET, F#) to work together seamlessly.
  • Exception Handling: CLR provides a robust exception handling mechanism across all .NET languages.
  • Type Safety: CLR ensures that code only accesses memory it's authorized to, preventing type errors and corruption.
  • Security: CLR uses Code Access Security (CAS) and validation to ensure safe execution of code.

C# Static Classes and Static Constructors

Static Class:

A static class is a class that cannot be instantiated (you cannot create objects of it). It contains only static members (methods, properties, variables). Static classes are useful for utility or helper methods that don’t need object state. They are declared using the keyword static.

Static Constructor:

A static constructor is used to initialize static data or perform actions that need to be done once only for a class. It is called automatically before any static member is accessed, or the class is used for the first time. It does not take parameters and cannot be called explicitly.

Static Class and Constructor Example:

using System;

static class Utility
{
    static int counter;

    static Utility()
    {
        counter = 100;
        Console.WriteLine("Static constructor called.");
    }

    public static void ShowCounter()
    {
        Console.WriteLine("Counter: " + counter);
    }
}

class Program
{
    static void Main()
    {
        Utility.ShowCounter();
    }
}

Understanding .NET Standard 2.0

.NET Standard 2.0 is a formal specification of .NET APIs that are available across all .NET platforms, such as .NET Framework, .NET Core, Xamarin, Unity, and Mono. It was introduced to create a unified Base Class Library (BCL) that different .NET implementations can share. This ensures code compatibility and reuse across platforms.

The primary purpose of .NET Standard 2.0 is to provide a common set of APIs that can be used across different .NET environments. This allows developers to write libraries that work on multiple platforms without modification, helping to reduce code duplication and confusion caused by platform-specific libraries.

.NET Standard 2.0 is a powerful compatibility layer that brings all .NET platforms together by defining a common set of APIs. It enables code sharing, simplifies cross-platform development, and supports migration to modern .NET technologies.

C# Value Types vs. Reference Types

Value Types:

  • Store actual data directly in memory.
  • When you assign a value type to another variable, a copy of the value is made.
  • Stored in the stack memory.
  • Examples: int, float, char, bool, struct, enum.

Value Type Example:

int a = 10;
int b = a;
b = 20;
Console.WriteLine(a); // Output: 10
Console.WriteLine(b); // Output: 20

Reference Types:

  • Store references (addresses) to the actual data.
  • When you assign a reference type to another variable, both variables point to the same memory location.
  • Allocated on the heap memory.
  • Examples: class, interface, delegate, string, object, arrays.

Working with StringBuilder in C#

StringBuilder is a class provided by the System.Text namespace that is used to work with mutable strings (i.e., strings that can be changed without creating a new object). Unlike string, which is immutable (cannot be changed once created), StringBuilder allows modifying strings in-place, which is more efficient for frequent string manipulations.

StringBuilder Example:

using System;
using System.Text;

class Program
{
    static void Main()
    {
        StringBuilder sb = new StringBuilder("Hello");
        sb.Append(" World");
        sb.Replace("World", "C#");
        sb.Insert(0, "Welcome to ");
        sb.Remove(0, 4);
        Console.WriteLine(sb.ToString()); // Output: come to Hello C#
    }
}

C# Namespaces: Organization and Conflict Resolution

In C#, a namespace is a way to organize classes, interfaces, structs, enums, and other namespaces. It helps to avoid name conflicts and to logically group related code elements.

Why Use Namespaces?

  1. Avoid Naming Conflicts: Two classes with the same name can exist in different namespaces without conflict.
  2. Organized Code Structure: It helps in organizing code into logical groups, especially in large projects.
  3. Code Reusability: Reusable components can be grouped and reused easily across different projects.
  4. Access Control: Namespaces can define a scope to keep specific classes hidden from others, contributing to better encapsulation.

Namespace Example:

// Define a namespace
namespace MyNamespace
{
    public class MyClass
    {
        public void Display()
        {
            Console.WriteLine("Hello from MyNamespace.MyClass!");
        }
    }
}

// Use the namespace
using MyNamespace;

class Program
{
    static void Main()
    {
        MyClass obj = new MyClass();
        obj.Display();
    }
}

C# Method Overloading: Concepts and Examples

Method Overloading in C# means having multiple methods in the same class with the same name but different parameters (either in number, type, or order). It allows a class to perform similar tasks in different ways based on the arguments passed.

Method Overloading Example:

using System;

class Calculator
{
    public int Add(int a, int b)
    {
        return a + b;
    }

    public int Add(int a, int b, int c)
    {
        return a + b + c;
    }

    public double Add(double a, double b)
    {
        return a + b;
    }
}

class Program
{
    static void Main()
    {
        Calculator calc = new Calculator();
        Console.WriteLine(calc.Add(10, 20));
        Console.WriteLine(calc.Add(10, 20, 30));
        Console.WriteLine(calc.Add(10.5, 20.5));
    }
}

C# Data Types: Value and Reference Categories

C# data types are broadly categorized into Value Types and Reference Types, determining how they store data and behave during assignment.

Value Types:

  • Store data directly in memory.
  • Allocated on the stack.
  • Examples include:
    • int (integer numbers)
    • float (single-precision floating-point numbers)
    • double (double-precision floating-point numbers)
    • decimal (high-precision decimal numbers, often used for financial calculations)
    • char (single Unicode characters)
    • bool (Boolean values: true or false)
    • struct (user-defined value types)
    • enum (set of named integer constants)

Reference Types:

  • Store references (addresses) to the actual data.
  • Allocated on the heap.
  • Examples include:
    • class (user-defined reference types)
    • string (sequence of characters)
    • object (the base class for all types in C#)
    • Arrays
    • Delegates
    • Interfaces

Related entries: