I have a struct called Foo
and Bar
- both if these implement an interface called IFoo
.
public interface IFoo
{
string StrTest { get; set; }
int NumTest { get; set; }
}
public struct Foo : IFoo
{
public Foo(string backTest, int numTest)
{
StrTest = backTest;
NumTest = numTest;
}
public string StrTest { get; set; }
public int NumTest { get; set; }
}
public struct Bar : IFoo
{
public Bar(string backTest, int numTest)
{
StrTest = backTest;
NumTest = numTest;
}
public string StrTest { get; set; }
public int NumTest { get; set; }
}
Let's say I have an array of IFoo
, at index "0" I have a Foo
struct. The problem comes when I move that struct over to a new index - such as "1" (which should copy it). Now, you would expect both of them to be separate, meaning you change one and the other shouldn't change as well.
However, I find that if I change one of the properties for the newly moved one - both change... isn't this class
(reference type) functionality?
Take a look at the following example:
// Create a list of "BackInterface"s - with foo and bar.
List<IFoo> arr = new List<IFoo>
{
new Foo("A", 2),
new Bar("B", 4)
};
// Now, place the SAME struct at index "0" (the foo) at the end - it should be copied?
arr.Add(arr[0]);
// Modify the item at the last newly-created index
arr[2].StrTest = "C";
Both arr[0]
and arr[2]
's StrTest
are now "C"
.
If I have an array of just Foo
or Bar
I don't have this problem - only when I have an array of IFoo
. I have also tried normal arrays (of type "object
) and ArrayList
(which doesn't have generics) - none of which have worked.
Any idea what is happening in here, and how to still be able to have an array of both Foo
and Bar
, both having to have an implementation of something?