Show 25 50 100
PDF
2 result(s) in C# with 5+ ★ Clear

Index

Showing 2 topics
  1. Value Types vs Reference Types
  2. Inheritance, Interface and Abstract Class in C#
1 Index
Value typeReference type
Stores the data itselfStores a reference (address) to the data
int, double, bool, char, struct, enumclass, string, array, interface, delegate
Usually on the stackObject lives on the heap
Assignment copies the valueAssignment copies the reference (both point to the same object)

Copying a value type vs copying a reference

Copying a value type vs copying a reference

C# 9 lines
int a = 10;
int b = a;
b = 20;
Console.WriteLine(a);   // 10

var p1 = new Person { Name = "Rahim" };
var p2 = p1;
p2.Name = "Karim";
Console.WriteLine(p1.Name);   // Karim

Boxing = value type → object (heap). Unboxing = object → value type. string is a reference type but immutable.

2 Index

C# supports single class inheritance but a class can implement many interfaces. Use virtual + override for polymorphism, abstract for methods without a body, sealed to stop further inheritance.

C# 25 lines
public interface IShape { double Area(); }

public abstract class Shape : IShape
{
    public abstract double Area();
    public virtual string Describe() => $"Area = {Area():F2}";
}

public class Circle : Shape
{
    public double R { get; }
    public Circle(double r) => R = r;
    public override double Area() => Math.PI * R * R;
}

public sealed class Square : Shape
{
    public double A { get; }
    public Square(double a) => A = a;
    public override double Area() => A * A;
    public override string Describe() => "Square, " + base.Describe();
}

List<Shape> shapes = new() { new Circle(2), new Square(3) };
foreach (var s in shapes) Console.WriteLine(s.Describe());