Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can a value type implement an interface type?

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.

like image 346
Lincoln Bergeson Avatar asked Jan 25 '14 00:01

Lincoln Bergeson


People also ask

What is the value type in interface?

Interfaces are implemented by types, and those types are either value types or reference types. Obviously, both int and string implement IComparable , and int is a value type, and string is a reference type.

Can reference type BE interface?

You can use interface names anywhere you can use any other data type name. If you define a reference variable whose type is an interface, any object you assign to it must be an instance of a class that implements the interface.

Can an interface return a value?

Yes an interface is a very valid return value.

How do you implement an interface in Golang?

Implementing an interface in Go To implement an interface, you just need to implement all the methods declared in the interface. Unlike other languages like Java, you don't need to explicitly specify that a type implements an interface using something like an implements keyword.


2 Answers

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.

like image 94
MarcinJuraszek Avatar answered Sep 29 '22 17:09

MarcinJuraszek


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
    }
}
like image 20
Kenneth Avatar answered Sep 29 '22 17:09

Kenneth