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.
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.
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.
Yes an interface is a very valid return value.
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.
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.
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With