How to implement an interface in C# struct

interface and struct boxing

struct is a value type while interface is a reference type. A cast from struct to an interface is a boxing.


using System;/*w w  w.j a  v a2  s .c  om*/
interface Printable
{
    void print();
}

struct Rectangle : Printable
{
    public void print()
    {
        Console.WriteLine("rectangle");
    }
}


class Test
{
    static void Main()
    {

        Printable p = new Rectangle(); // boxing
        p.print();
    }
}

The output:





















Home »
  C# Tutorial »
    Custom Types »




C# Class
C# Struct
C# Interface
C# Inheritance
C# Namespace
C# Object
C# Delegate
C# Lambda
C# Event
C# Enum
C# Attribute
C# Generics
C# Preprocessor