C#C
C#6mo ago
yoush

✅ (solved) How does a list of structs that all implement an interface live in memory?

Simple question I can't find an answer to: Afaik structs are value types and exist on the stack, but they can implement interfaces like classes.
Would a Array of structs that all implement the same interface be an array of pointers towards the struct? or would the structs still exists on the stack?
For Example:
C#
public interface Shape
{
    public float area();
}

struct Rectangle(float width, float length) : Shape
{
    float width = width;
    float length = length;

    public float area()
    {
        return width * length;
    }
}

struct Circle(float radius) : Shape
{
    float radius = radius;

    public float area()
    {
        return (float)Math.Pow(Math.PI * radius, 2);
    }
}

class Program
{
    public static float calcualteArea(Shape s)
    {
        return s.area();
    }

    public static void Main()
    {
        Rectangle r = new(3, 4);
        Circle c = new(5);
        Shape[] shapes = [r, c]; // where do these values exist?
        Console.WriteLine(calcualteArea(shapes[0]));
        Console.WriteLine(calcualteArea(shapes[1]));
    }
}

new to C#, help is appreciated!
Was this page helpful?