An abstract class in C# is a class that cannot be instantiated on its own and is typically used as a base class for other classes. It can contain both abstract (unimplemented) and concrete (implemented) methods. Subclasses that derive from an abstract class must provide implementations for all its abstract members.
Example:
abstract class Shape
{
public abstract double Area(); // Abstract method
public void Display()
{
Console.WriteLine("This is a shape.");
}
}
class Circle : Shape
{
public double Radius { get; set; }
public Circle(double radius)
{
Radius = radius;
}
public override double Area()
{
return Math.PI * Radius * Radius;
}
}
Interface:
An interface in C# defines a contract of methods and properties that a class must implement. It provides a way to achieve multiple inheritance since a class can implement multiple interfaces.
Example:
interface IDrawable
{
void Draw(); // Method declaration without implementation
}
interface IResizable
{
void Resize(int width, int height); // Method declaration without implementation
}
class Rectangle : IDrawable, IResizable
{
public void Draw()
{
Console.WriteLine("Drawing a rectangle.");
}
public void Resize(int width, int height)
{
Console.WriteLine($"Resizing to width: {width}, height: {height}");
}
}
C# static class:
A ‘static class’ cannot be instantiated and is used to provide utility functions.
Example:
static class Logger
{
public static void Log(string message)
{
// Log the message
}
}
Logger.Log("An important message");
C# Partial Class:A partial class in C# allows you to split a single class declaration across multiple source files. This is often used to separate auto-generated code from developer-written code or to organize a large class into manageable parts while still treating it as a single class.
Example:
// File1.cs
partial class MyPartialClass
{
public void Method1()
{
Console.WriteLine("Method1 from File1");
}
}
// File2.cs
partial class MyPartialClass
{
public void Method2()
{
Console.WriteLine("Method2 from File2");
}
}
// Program.cs
using System;
class Program
{
static void Main()
{
MyPartialClass myObj = new MyPartialClass();
myObj.Method1(); // Output: Method1 from File1
myObj.Method2(); // Output: Method2 from File2
}
}