Details on what happens when a struct implements an interface - c#

I recently came across this Stackoverflow question: When to use struct?
In it, it had an answer that said something a bit profound:
In addition, realize that when a struct implements an interface - as
Enumerator does - and is cast to that implemented type, the struct
becomes a reference type and is moved to the heap. Internal to the
Dictionary class, Enumerator is still a value type. However, as soon
as a method calls GetEnumerator(), a reference-type IEnumerator is
returned.
Exactly what does this mean?
If I had something like
struct Foo : IFoo
{
public int Foobar;
}
class Bar
{
public IFoo Biz{get; set;} //assume this is Foo
}
...
var b=new Bar();
var f=b.Biz;
f.Foobar=123; //What would happen here
b.Biz.Foobar=567; //would this overwrite the above, or would it have no effect?
b.Biz=new Foo(); //and here!?
What exactly are the detailed semantics of a value-type structure being treated like a reference-type?

Every declaration of a structure type really declares two types within the Runtime: a value type, and a heap object type. From the point of view of external code, the heap object type will behave like a class with a fields and methods of the corresponding value type. From the point of view of internal code, the heap type will behave as though it has a field this of the corresponding value type.
Attempting to cast a value type to a reference type (Object, ValueType, Enum, or any interface type) will generate a new instance of its corresponding heap object type, and return a reference to that new instance. The same thing will happen if one attempts to store a value type into a reference-type storage location, or pass it as a reference-type parameter. Once the value has been converted to a heap object, it will behave--from the point of view of external code--as a heap object.
The only situation in which a value type's implementation of an interface may be used without the value type first being converted to a heap object is when it's passed as a generic type parameter which has the interface type as a constraint. In that particular situation, interface members may be used on the value type instance without its having to be converted to a heap object first.

Read about boxing and unboxing (search the internet). For example MSDN: Boxing and Unboxing (C# Programming Guide).
See also the SO thread Why do we need boxing and unboxing in C#?, and the threads linked to that thread.
Note: It is not so important if you "convert" to a base class of the value type, as in
object obj = new Foo(); // boxing
or "convert" to an implemented interface, as in
IFoo iFoo = new Foo(); // boxing
The only base classes a struct has, are System.ValueType and object (including dynamic). The base classes of an enum type are System.Enum, System.ValueType, and object.
A struct can implement any number of interfaces (but it inherits no interfaces from its base classes). An enum type implements IComparable (non-generic version), IFormattable, and IConvertible because the base class System.Enum implements those three.

I'm replying your post about your experiment on 2013-03-04, though I might be a bit late :)
Keep this in mind: Every time you assign a struct value to a variable of an interface type (or return it as an interface type) it will be boxed. Think of it like a new object (the box) will be created on the heap, and the value of the struct will be copied there. That box will be kept until you have a reference on it, just like with any object.
With behavior 1, you have the Biz auto property of type IFoo, so when you set a value here, it will be boxed and the property will keep a reference to the box. Whenever you get the value of the property, the box will be returned. This way, it mostly works as if Foo would be a class, and you get what you expect: you set a value and you get it back.
Now, with behavior 2, you store a struct (field tmp), and your Biz property returns its value as an IFoo. That means every time get_Biz is called, a new box will be created and returned.
Look through the Main method: every time you see a b.Biz, that's a different object (box). That will explain the actual behavior.
E.g. in line
b.Biz.Foobar=567;
b.Biz returns a box on the heap, you set the Foobar in it to 576 and then, as you do not keep a reference to it, it is lost immediatly for your program.
In the next line you writeline b.Biz.Foobar, but this call to b.Biz will then again create a quite new box with Foobar having the default 0 value, that's what printed.
Next line, variable f earlier was also filled by a b.Biz call which created a new box, but you kept a reference for that (f) and set its Foobar to 123, so that's still what you have in that box for the rest of the method.

So, I decided to put this behavior to the test myself. I'll give the "results", but I can't explain why things happen this way. Hopefully someone with more knowledge about how this works can come along and enlighten me with a more thorough answer
Full test program:
using System;
namespace Test
{
interface IFoo
{
int Foobar{get;set;}
}
struct Foo : IFoo
{
public int Foobar{ get; set; }
}
class Bar
{
Foo tmp;
//public IFoo Biz{get;set;}; //behavior #1
public IFoo Biz{ get { return tmp; } set { tmp = (Foo) value; } } //behavior #2
public Bar()
{
Biz=new Foo(){Foobar=0};
}
}
class MainClass
{
public static void Main (string[] args)
{
var b=new Bar();
var f=b.Biz;
f.Foobar=123;
Console.WriteLine(f.Foobar); //123 in both
b.Biz.Foobar=567; /
Console.WriteLine(b.Biz.Foobar); //567 in behavior 1, 0 in 2
Console.WriteLine(f.Foobar); //567 in behavior 1, 123 in 2
b.Biz=new Foo();
b.Biz.Foobar=5;
Console.WriteLine(b.Biz.Foobar); //5 in behavior 1, 0 in 2
Console.WriteLine(f.Foobar); //567 in behavior 1, 123 in 2
}
}
}
As you can see, by manually boxing/unboxing we get extremely different behavior. I don't completely understand either behavior though.

Related

How is the default ToString() method of Object class implemented?

Imagine you have two of this simple classes:
class Class1
{
}
class Class2
{
}
We all know that all classes by default inherits from object class.
So imagine this code:
int num = new Random().Next(1, 3);
object obj = num == 1 ? new Class1() : new Class2();
Console.WriteLine(obj.ToString());
So based on random number the output will be namespace.Class2 or namespace.Class1.
And note that I'm assigning these classes to object class.
My questions are:
How ToString() of objectclass can find out the original derived class type? (namespace.Class2 or namespace.Class1)
Can we use the result of ToString() method to cast the type successfuly? If yes, How?
How ToString() of objectclass can find out the original derived class type? (namespace.Class2 or namespace.Class1)
When casting you do not change the object itself, only the reference to the object. So ToString() will still check the actual object type (and not the reference type) to find the correct method to call.
All objects have a header that contain type information a bunch of other stuff used by the runtime. Note that value types like int and struct lack such a header so will be more compact. However, these value types will be boxed if cast to object, and that will incur the object overhead, so it is best avoided where possible.
Can we use the result of ToString() method to cast the type successfuly? If yes, How?
There is really no point. If you want to do a safe cast just do
if(obj is Class1 myClass1Reference){
...
}
You can also use dynamic to essentially turn of type-checking, resulting in runtime errors instead of compile-time errors, but that is rarely a good idea unless you are working with something like COM.

Object Passing Reference vs Value [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
To give context to the code imagine a collection of objects inside a cube. The objects are placed randomly and can affect each other. Several series of test events are planned then executed against the cube of objects. Only the best result is kept. This is not the real problem but a simplified version to focus the question.
Sample code
class Loc{
double UpDown
double LeftRight
double FrontBack
}
class Affects{
string affectKey
List<string> impacts //scripts that execute against properties
}
class Item{
Loc startLoc
Loc endLoc
List<string> affectedBy
string resultText // summary of analysis of changes
}
class ItemColl{
List<Item> myItems
}
class main{
ItemColl items
List<string> actions
void ProcessAffects(ItemColl tgt, List<string> acts){
// take actions against the tgt set and return
}
int IsBetter(ItemColl orig, List<Items> altered){
// compares the collection to determine "better one"
// positive better, negative worse, zero for no change
}
void DoThings(){
// original code
ItemColl temp = items
ProcessAffects(temp,actions)
IsBetter(temp,actions)
// the result was always zero - admittedly a duh error
}
}
When I added an alternate constructor that copied the object passed in and did the same to all subordinate objects, as in
class ItemColl{
public ItemColl(){}
public ItemColl (ItemColl clone){
// do a deep copy
}
// partial code from main DoThings
// replaced ItemColl temp = items
// with
ItemColl temp = new ItemColl(items)
it solved the problem that lead me to first question. (Thanks to the people who answered that question kindly.) What I am stuck on is whether or not there are other options to consider? I am hoping this restatement has a better focus and if I am not taking advantage of some newer efficiencies I would like to know.
I removed the old question entirely and re-phrased post face-palm.
Before you get into parameters, you need some background:
Background
There are two kinds of objects in .NET-land, Reference types and Value types. The main difference between the two is how assignment works.
Value Types
When you assign a value type instance to a variable, the value is copied to the variable. The basic numeric types (int, float, double, etc) are all value types. As a result, in this code:
decimal dec1 = 5.44m;
decimal dec2 = dec1;
dec1 = 3.1415m;
both decimal variables (dec and dec2) are wide enough to hold a decimal valued number. In each case, the value is copied. At the end, dec1 == 3.145m and dec2 == 5.44m.
Nearly all value types are declared as a struct (yes, if you get access to the .NET sources, int is a struct). Like all .NET types, they act when boxed as if they are derived from the object base class (their derivation is through System.ValueType. Both object (aka System.Object) and System.ValueType are reference types, even though the unboxed types that derive from System.ValueType are value types (a little magic happens here).
All value types are sealed/final - you can't sub-class them. You also can't create a default constructor for them - they come with a default constructor that initializes them to their default value. You can create additional constructors (which don't hide the built-in default constructor).
All enums are value types as well. They inherit from System.Enum but are value types and behave mostly like other value types.
In general, value types should be designed to be immutable; not all are.
Reference Types
Variables of reference types hold references, not values. That said, it sometimes help to think of them holding a value - it's just that that value is a reference to an object on the managed heap.
When you assign to a variable of reference type, you are assigning the reference. For example:
public class MyType {
public int TheValue { get; set; }
// more properties, fields, methods...
}
MyType mt1 = new MyType() {TheValue = 5};
MyType mt2 = mt1;
mt1.TheValue = 42;
Here, the mt1 and mt2 variables both contain references to the same object. When that object is mutated in the final line of code, you end up with two variables both referring to an object whose TheValue property is 42.
All types declared as a class are reference types. In general, other than the numeric types, enums and bools, most (but not all) of the types that you normally encounter will be reference types.
Anything declared to be a delegate or an event are also reference types under the covers. Someone mentioned interface. There is no such thing as an object typed purely as an interface. Both structs and classes may be declared to implement an interface - it doesn't change their value/reference type nature, but a struct stored as an interface will be boxed.
Difference in Constructor Behavior
One other difference between Reference and Value Types is what the new keyword means when constructing a new object. Consider this class and this struct:
public class CPoint {
public float X { get; set; }
public float Y { get; set; }
public CPoint (float x, float y) {
X = x;
Y = y;
}
}
public struct SPoint {
public float X { get; set; }
public float Y { get; set; }
public CPoint (float x, float y) {
X = x;
Y = y;
}
}
They are basically the same, except that CPoint is a class (a reference type) and SPoint is a struct (a value type).
When you create an instance of SPoint using the two float constructor (remember, it gets a default constructor auto-magically), like this:
var sp = new SPoint (42.0, 3.14);
What happens is that the constructor runs and creates a value. That value is then copied into the sp variable (which is of type SPoint and large enough to hold a two-float SPoint).
If I do this:
var cp = new CPoint (42.0, 3.14);
Something very different happens. First, memory is allocated on the managed heap large enough to hold a CPoint (i.e., enough to hold two floats plus the overhead of the object being a reference type). Then the two-float constructor runs (and that constructor is the only constructor - there is no default constructor (the additional, programmer-written constructor hides the compiler generated default constructor)). The constructor initializes that newCPoint in the memory allocated on the managed heap. Finally, a reference to that newly create object is created and copied to the variable cp.
Parameter Passing
Sorry the preamble took so long.
Unless otherwise specified, all parameters to functions/methods are passed by value. But, don't forget that the value of a variable of reference type is a reference.
So, if I have a function declared as (MyType is the class declared above):
public void MyFunction(decimal decValue, MyType myObject) {
// some code goes here
}
and some code that looks like:
decimal dec1 = 5.44m;
MyType mt1 = new MyType() {TheValue = 5};
MyFunction (dec1, mt1);
What happens is that the value of dec1 is copied to the function parameter (decValue) and available for use within MyFunction. If someone changes the value of the decValue within the function, no side effects outside the function occurs.
Similarly, but differently, the value of mt1 is copied to the method parameter myObject. However, that value is reference to a MyType object residing on the managed heap. If, within the method, some code mutates that object (say: myObject.TheValue=666;), then the object to which both the mt1 and myObject variables refer is mutated, and that results in a side effect viewable outside of the function. That said, everything is still being passed by value.
Passing Parameters by Reference
You can pass parameters by reference in two ways, using either the out or ref keywords. An out parameter does not need to be initialized before the function call (while a ref parameter must be). Within the function, an out parameter must be initialized before the function returns - ref parameters may be initialized, but they do not need to be. The idea is that ref parameters expect to pass in and out of the function (by reference). But out parameters are designed simply as a way to pass something out of the function (by reference).
If I declare a function like:
public void MyByRefFunction(out decimal decValue, ref MyType myObject) {
decValue = 25.624; //decValue must be intialized - it's an out parameter
myObject = new MyType (){TheValue = myObject.TheValue + 2};
}
and then I call it this way
decimal dec1; //note that it's not initalized
MyType mt1 = new MyType() {TheValue = 5};
MyType mt2 = mt1;
MyByRefFunction (out dec1, ref mt1);
After that call, dec1 will contain the value 25.624; that value was passed out of the function by reference.
Passing reference type variables by reference is more interesting. After the function call, mt1 will no longer refer to the object created with TheValue equal to 5, it will refer to the newly created object with TheValue equal to 5 + 2 (the object created within the function). Now, mt1 and mt2 will refer to different object with different TheValue property values.
With reference types, when you pass a variable normally, the object you pass it may mutate (and that mutation is visible after the function returns). If you pass a reference by reference, the reference itself may mutate, and the value of the reference may be different after the function returns.
All custom objects (derived from tobject) are "Reference type".
Nope. See the docs pages for Reference Types and Value Types
The following keywords are used to declare reference types:
class
interface
delegate
C# also provides the following built-in reference types:
dynamic
object
string
A value type can be one of the two following kinds:
a structure type ...
an enumeration type ...
So any time you make a class, it's always a Reference type.
EVERY type inherits from Object - Value Types and Reference Types.
Even if you pass it to a function with a reference parameter, as with the RefChange function both items are changed and both have exactly the same values in the integer list.
The ref keyword just forces your parameter to be passed by reference. Using ref with a Reference Type allows you to reassign the original passed in reference. See What is the use of “ref” for reference-type variables in C#?
.
Do not confuse the concept of passing by reference with the concept of reference types. The two concepts are not the same. A method parameter can be modified by ref regardless of whether it is a value type or a reference type. There is no boxing of a value type when it is passed by reference.
Source
Of course, the ref keyword is important when you pass in a Value Type, such as a struct.
If you want to pass a copy of an object, create an overloaded constructor to which you pass the original object and inside the constructor manage the duplication of the values that matter.
That's called a Copy Constructor, and is a long-established pattern, if you want to use it. In fact, there is a new c# 9.0 feature all about it: records.
well i cant comment since my reputation is too low, but value types are usually in built types such as int, float ...
everything else is reference type. reference type is always a shallow copy regardless of ref keyword.
ref keyword mainly served for value-type or act as a safeguard.
if u want to deep copy, Icloneable is very useful.

Does a variable of an interface type act as value type if the underlying implementation is a struct?

I was looking at this question, and aside from a rather odd way to enumerate something, the op was having trouble because the enumerator is a struct. I understand that returning or passing a struct around uses a copy because it is a value type:
public MyStruct GetThingButActuallyJustCopyOfIt()
{
return this.myStructField;
}
or
public void PretendToDoSomething(MyStruct thingy)
{
thingy.desc = "this doesn't work as expected";
}
So my question is if MyStruct implements IMyInterface (such as IEnumerable), will these types of methods work as expected?
public struct MyStruct : IMyInterface { ... }
//will caller be able to modify the property of the returned IMyInterface?
public IMyInterface ActuallyStruct() { return (IMyInterface)this.myStruct; }
//will the interface you pass in get its value changed?
public void SetInterfaceProp(IMyInterface thingy)
{
thingy.desc = "the implementing type is a struct";
}
Yes, that code will work, but it needs explanation, because there is a whole world of code that will not work, and you're likely to trip into that unless you know this.
Before I forget: Mutable structs are evil. OK, with that out of the way, let's move on.
Let's take a simple example, you can use LINQPad to verify this code:
void Main()
{
var s = new MyStruct();
Test(s);
Debug.WriteLine(s.Description);
}
public void Test(IMyInterface i)
{
i.Description = "Test";
}
public interface IMyInterface
{
string Description { get; set; }
}
public struct MyStruct : IMyInterface
{
public string Description { get; set; }
}
When executing this, what will be printed?
null
OK, so why?
Well, the problem is this line:
Test(s);
This will in fact box that struct and pass the boxed copy to the method. You're successfully modifying that boxed copy, but not the original s variable, which was never assigned anything, and is thus still null.
OK, so if we change just one line in the first piece of code:
IMyInterface s = new MyStruct();
Does this change the outcome?
Yes, because now you're boxing that struct here, and always use the boxed copy. In this context it behaves like an object, you're modifying the boxed copy and writing out the contents of the boxed copy.
The problem thus crops up whenever you box or unbox that struct, then you get copies that live separate lives.
Conclusion: Mutable structs are evil.
I see two answers about using ref here now, and this is barking up the wrong tree. Using ref means you've solved the problem before you added ref.
Here's an example.
If we change the Test method above to take a ref parameter:
public void Test(ref IMyInterface i)
Would this change anything?
No, because this code is now invalid:
var s = new MyStruct();
Test(ref s);
You'll get this:
The best overloaded method match for 'UserQuery.Test(ref UserQuery.IMyInterface)' has some invalid arguments
Argument 1: cannot convert from 'ref UserQuery.MyStruct' to 'ref UserQuery.IMyInterface'
And so you change the code to this:
IMyInterface s = new MyStruct();
Test(ref s);
But now you're back to my example, just having added ref, which I showed is not necessary for the change to propagate back.
So using ref is orthogonal, it solves different problems, but not this one.
OK, more comments regarding ref.
Yes, of course passing a struct around using ref will indeed make the changes flow throughout the program.
That is not what this question was about. The question posted some code, asked if it would work, and it would. In this particular variant of code it would work. But it's so easy to trip up. And pay particular note that the question was regarding structs and interfaces. If you leave interfaces out of it, and pass the struct around using ref, then what do you have? A different question.
Adding ref does not change this question, nor the answer.
Within the CLR, every value-type definition actually defines two kinds of things: a structure type, and a heap object type. A widening conversion exists from the structure type to the boxed object type, and a narrowing conversion exists from Object to the structure type. The structure type will behave with value semantics, and the heap object type will behave with mutable reference semantics. Note that the heap object types associated with all non-trivial structure types [i.e. those with any non-default states] are always mutable, and nothing in the structure definition can cause them to be otherwise.
Note that value types may be constrained, cast, or coerced to interface types, and cast or coerced to reference types. Consider:
void DoSomethingWithDisposable<T,U>(ref T p1,
List<int>.Enumerator p2) where T:IDisposable
{
IDisposable v1a = p1; // Coerced
Object v1b = p1; // Coerced
IDisposable v2a = (IDisposable)p2; // Cast
Object v2b = (Object)p2; // Cast
p1.Dispose(); // Constrained call
}
void blah( List<string>.Enumerator p1, List<int>.Enumerator p2) // These are value types
{
DoSomethingWithDisposable(p1,p2); // Constrains p1 to IDisposable
}
Constraining a generic type to an interface type does not affect its behavior as a value type. Casting or coercing an a value type to an interface or reference type, however, will create a new instance of the heap object type and return a reference to that. That reference will then behave with reference-type semantics.
The behavior of value types with generic constraints can at times be very useful, and such usefulness can apply even when using mutating interfaces, but unfortunately there's no way to tell the compiler that a value type must remain as a value type, and that the compiler should warn if it would find itself converting it to something else. Consider the following three methods:
bool AdvanceIntEnumerator1(IEnumerator<int> it)
{ return it.MoveNext(); }
bool AdvanceIntEnumerator2(ref T it) where T:IEnumerator<int>
{ return it.MoveNext(); }
bool AdvanceIntEnumeratorTwice<T>(ref T it) where T:IEnumerator<int>
{ return it.MoveNext() && AdvanceIntEnumerator1(it); }
If one passes to the first piece of code a variable of type List<int>.Enumerator, the system will copy its state to a new heap object, call MoveNext on that object, and abandon it. If one passes instead a variable of type IEnumerator<int> which holds a reference to a heap object of type List<int>.Enumerator, it will call MoveNext on that instance, which the calling code will still retain.
If one passes to the second piece of code a variable of type List<int>.Enumerator, the system will call MoveNext on that variable, thus changing its state. If one passes a variable of type IEnumerable<T>, the system will call MoveNext on the object referred to by that variable; the variable won't be modified (it will still point to the same instance), but the instance to which it points will be.
Passing to the third piece of code a variable of type List<int>.Enumerator will cause MoveNext to be called on that variable, thus changing its state. If that returns true, the system will copy the already-modified variable to a new heap object and call MoveNext on that. The object will then be abandoned, so the variable will only be advanced once, but the return value will indicate whether a second MoveNext would have succeeded. Passing the third piece of code a variable of type IEnumerator<T> which holds a reference to a List<T>.Enumerator, however, will cause that instance to be advanced twice.
No, interface is a contract, to make it work properly you need to use ref keyword.
public void SetInterfaceProp(ref IMyInterface thingy)
{
thingy.desc = "the implementing type is a struct";
}
What matters here is a real type that stays inside that interface wrap.
To be more clear:
even if code with method SetInterfaceProp defined like
public void SetInterfaceProp(IMyInterface thingy)
{
thingy.desc = "the implementing type is a struct";
}
will work:
IMyInterface inter= default(MyStruct);
SetInterfaceProp(inter);
this one will not :
MyStruct inter = default(MyStruct);
SetInterfaceProp(inter);
You can not gurantee that the caller of your method will always use IMyInterface, so to guarantee expected behavior, in this case, you can define ref keyword, that will guarantee that in both cases method would run as expected.

Assigning IEnumerable (Covariance)

Since IEnumerable has a covariant parameter in C# 4.0 I am confused how it is behaving in the following code.
public class Test
{
IEnumerable<IFoo> foos;
public void DoTestOne<H>(IEnumerable<H> bars) where H : IFoo
{
foos = bars;
}
public void DoTestTwo(IEnumerable<IBar> bars)
{
foos = bars;
}
}
public interface IFoo
{
}
public interface IBar : IFoo
{
}
So basically the DoTestOne method doesn't compile while DoTestTwo does. In addition to why it doesn't work, if anyone knows how I can achieve the effect of DoTestOne (assigning an IEnumberable<H> where H : IFoo to an IEnumberable<IFoo>) I would appreciate the help.
If you know that H will be a class, this does work:
public void DoTestOne<H>(IEnumerable<H> bars) where H : class, IFoo
{
foos = bars;
}
The issue here is that if H is a value type, the covariance is not exactly what you'd expect, as IEnumerable<MyStruct> actually returns the value types whereas IEnumerable<IFoo> has to return boxed instances. You can use an explicit Cast<IFoo> to get around this, if necessary.
You simply need a cast to IEnumerable<IFoo> in there:
public void DoTestOne<H>(IEnumerable<H> bars) where H : IFoo
{
foos = (IEnumerable<IFoo>)bars;
}
Edit courtesy of Dan Bryant: using foos = bars.Cast<IFoo>() instead of above circumvents the InvalidCastException when H is a struct.
Within the .net Runtime, every value type has an associated heap object type with the same name. In some contexts, the value type will be used; in other contexts, the heap type. When a storage location (variable, parameter, return value, field, or array slot) of value type is declared, that storage location will hold the actual contents of that type. When a storage location of class type is declared, it will hold either null or a reference to a heap object that is stored elsewhere. Interface-type storage locations are treated like reference-type ones, and hold heap references even if some (or all) of the implementations of the interface are actually value types.
An attempt to store a value type into a reference-type storage location will cause the system to create a new instance of the heap type associated with the value type, copy all the fields from the original storage location to corresponding fields in the new instance, and store a reference to that instance, a process called "boxing". An attempt to cast a heap reference to a value-type storage location will check whether it refers to an instance of the heap type associated with the value type; if it does, the fields of the heap object will be copied ("unboxed") into the corresponding ones in the value-type storage location.
Although it may look as though a type like System.Int32 derives from System.Object, that's only half true. There is a heap object type System.Int32, which does indeed derive from System.Object, but a variable of type System.Int32 doesn't hold a reference to such an object. Instead, such a variable holds the actual data associated with that integer; the data itself is just a collection of bits, and doesn't derive from anything.
If one thinks of interface-type storage locations as holding "Something derived from System.Object which implements interface _", then instances of any class type which implements that interface are an instance of that type, but instances of a value types--even if they are convertible to other types--are not instances of any other types. Code which uses an IEnumerator<IFoo> doesn't just want its Current method to return something which could be convertible to an IFoo, or implements IFoo; it wants it to return something that is a derivative of Object that implements IFoo. Consequently, for an IEnumerable<T> to substitute for an IEnumerable<IFoo>, it's necessary that T be constrained both to implement IFoo and to be a proper derivative of System.Object.
You forgot a cast in your return or a "class" identifier in your generic constraint. What your doing is of course possible, reference below.
From: http://msdn.microsoft.com/en-us/library/d5x73970.aspx
where T : <interface name>
The type argument must be or implement the specified interface.
Multiple interface constraints can be specified. The constraining interface can also be generic.

Why cannot IEnumerable<struct> be cast as IEnumerable<object>?

Why is the last line not allowed?
IEnumerable<double> doubleenumerable = new List<double> { 1, 2 };
IEnumerable<string> stringenumerable = new List<string> { "a", "b" };
IEnumerable<object> objects1 = stringenumerable; // OK
IEnumerable<object> objects2 = doubleenumerable; // Not allowed
Is this because double is a value type that doesn't derive from object, hence the covariance doesn't work?
Does that mean that there is no way to make this work:
public interface IMyInterface<out T>
{
string Method();
}
public class MyClass<U> : IMyInterface<U>
{
public string Method()
{
return "test";
}
}
public class Test
{
public static object test2()
{
IMyInterface<double> a = new MyClass<double>();
IMyInterface<object> b = a; // Invalid cast!
return b.Method();
}
}
And that I need to write my very own IMyInterface<T>.Cast<U>() to do that?
Why is the last line not allowed?
Because double is a value type and object is a reference type; covariance only works when both types are reference types.
Is this because double is a value type that doesn't derive from object, hence the covariance doesn't work?
No. Double does derive from object. All value types derive from object.
Now the question you should have asked:
Why does covariance not work to convert IEnumerable<double> to IEnumerable<object>?
Because who does the boxing? A conversion from double to object must box the double. Suppose you have a call to IEnumerator<object>.Current that is "really" a call to an implementation of IEnumerator<double>.Current. The caller expects an object to be returned. The callee returns a double. Where is the code that does the boxing instruction that turns the double returned by IEnumerator<double>.Current into a boxed double?
It is nowhere, that's where, and that's why this conversion is illegal. The call to Current is going to put an eight-byte double on the evaluation stack, and the consumer is going to expect a four-byte reference to a boxed double on the evaluation stack, and so the consumer is going to crash and die horribly with an misaligned stack and a reference to invalid memory.
If you want the code that boxes to execute then it has to be written at some point, and you're the person who gets to write it. The easiest way is to use the Cast<T> extension method:
IEnumerable<object> objects2 = doubleenumerable.Cast<object>();
Now you call a helper method that contains the boxing instruction that converts the double from an eight-byte double to a reference.
UPDATE: A commenter notes that I have begged the question -- that is, I have answered a question by presupposing the existence of a mechanism which solves a problem every bit as hard as a solution to the original question requires. How does the implementation of Cast<T> manage to solve the problem of knowing whether to box or not?
It works like this sketch. Note that the parameter types are not generic:
public static IEnumerable<T> Cast<T>(this IEnumerable sequence)
{
if (sequence == null) throw ...
if (sequence is IEnumerable<T>)
return sequence as IEnumerable<T>;
return ReallyCast<T>(sequence);
}
private static IEnumerable<T> ReallyCast<T>(IEnumerable sequence)
{
foreach(object item in sequence)
yield return (T)item;
}
The responsibility for determining whether the cast from object to T is an unboxing conversion or a reference conversion is deferred to the runtime. The jitter knows whether T is a reference type or a value type. 99% of the time it will of course be a reference type.
To understand what is allowed and not allowed, and why things behave as they do, it is helpful to understand what's going on under the hood. For every value type, there exists a corresponding type of class object, which--like all objects--will inherit from System.Object. Each class object includes with its data a 32-bit word (x86) or 64-bit longword (x64) which identifies its type. Value-type storage locations, however, do not hold such class objects or references to them, nor do they have a word of type data stored with them. Instead, each primitive-value-type location simply holds the bits necessary to represent a value, and each struct-value-type storage location simply holds the contents of all the public and private fields of that type.
When one copies a variable of type Double to one of type Object, one creates a new instance of the class-object type associated with Double and copies all the bytes from the original to that new class object. Although the boxed-Double class type has the same name as the Double value type, this does not lead to ambiguity because they can generally not be used in the same contexts. Storage locations of value types hold raw bits or combinations of fields, without stored type information; copying one such storage location to another copies all bytes, and consequently copies all public and private fields. By contrast, heap objects of types derived from value types are heap objects, and behave like heap objects. Although C# regards the contents of value-type storage locations as though they are derivatives of Object, under the hood the contents of such storage locations are simply collections of bytes, effectively outside the type system. Since they can only be accessed by code which knows what the bytes represent, there is no need to store such information with the storage location itself. Although the necessity for boxing when calling GetType on a struct is often described in terms of GetType being a non-shadowed, non-virtual function, the real necessity stems from the fact that the contents of a value-type storage location (as distinct from the location itself) don't have type information.
Variance of this type is only supported for reference types. See http://blogs.msdn.com/b/csharpfaq/archive/2010/02/16/covariance-and-contravariance-faq.aspx

Categories

Resources