Question

In the C# Language Specification v5.0, in section 1.3, it says this:

An Interface type can have as its contents a null reference, a reference to an instance of a class type that implements that interface type, or a reference to a boxed value of a value type that implements that interface type

I have no problem with two out of three of those statements. However, the last one confuses me. How can an interface type hold a boxed value of a value type that implements that interface type? I thought value types couldn't implement interface types? Or is it saying that the boxed value implements the interface type? If that's the case, how can a boxed value implement an interface type?

I'm having a spot of trouble comprehending all of this.

Was it helpful?

Solution

Value type (struct) can implement interface. It cannot inherit another struct, but can implement interface.

struct (C# Reference)

Structs can implement an interface but they cannot inherit from another struct. For that reason, struct members cannot be declared as protected.

So when you have a struct which implements IInterface and you do following:

var value = new MyStruct();
var valueAsInterface = (IInterface)value;

valueAsInterface contains reference to a boxed value of a value type that implements that interface type.

OTHER TIPS

There's nothing that says that a value type can't implement an interface.

The following code is perfectly legal:

interface ITest
{
    void DoSomething();
}

struct MyTest : ITest
{
    public void DoSomething()
    {
        // do something
    }
}

Here is an example:

interface DisplayMsg
{
    void ShowMsg();
}
/// <summary>
/// Interface  implemented by Struct
/// </summary>
struct StructDisplayMsg : DisplayMsg
{

    public void ShowMsg()
    {
        Console.WriteLine("Inside struct Showmsg:");
    }
}
/// <summary>
/// Interface implemented by Class
/// </summary>
class ObjectDisplayMsg:DisplayMsg
{
    public int Integer { get; set; }

    public void ShowMsg()
    {
        Console.WriteLine("Inside Object ShowMsg:{0}", Integer);
    }
    /// <summary>
    /// Implicit operator for boxing value type to object
    /// </summary>
    /// <param name="value"></param>
    /// <returns></returns>
    public static implicit operator ObjectDisplayMsg(int value)
    {
        ObjectDisplayMsg classObject = new ObjectDisplayMsg();
        classObject.Integer = value;
        return classObject;
    }
}

private void CheckConcepts()
{
    StructDisplayMsg localDisplay = new StructDisplayMsg();
    localDisplay.ShowMsg();

    int localInteger = 10;
    /* Boxing of the integer type to  Object */
    ObjectDisplayMsg intobject = (ObjectDisplayMsg)localInteger;
    intobject.ShowMsg();
    Console.ReadKey();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top