I need to pass structs as value types in a list. Suppose I have a struct which derives from an interface:
interface IFoo
{
...
}
struct Foo1 : IFoo { ... }
struct Foo2 : IFoo { ... }
//Some other class which contains this:
List<IFoo> listOfFoo;
I know if I did it like so: IFoo foo = new Foo1()
, it would turn the value into a reference (boxing).
Foo1
or Foo2
to List<IFoo>
?List<object>
and only add in these structs, or would it be better to do MemberwiseClone on a class?I'm also looking for efficiency, as this will be for collision detection in a tile map.
A class or struct can implement multiple interfaces, but a class can only inherit from a single class. For more information about abstract classes, see Abstract and Sealed Classes and Class Members. Interfaces can contain instance methods, properties, events, indexers, or any combination of those four member types.
Yes you can have a list in struct but you cannot initialise it with a field initialiser and instead you must use the constructor. Also note that you can not have a parameter-less constructor.
By accepting an interface, you create a flexible API that returns a more tenable and readable struct. Structs and interfaces are Go's way of organizing methods and data handling.
Although a ref class can inherit from at most one concrete base class, it can implement any number of interface classes. An interface class (or interface struct) itself can inherit (or require) multiple interface classes, can overload its member functions, and can have type parameters.
The structs would be boxed. Why wouldn't they be? Every value in List<IFoo>
must be an IFoo
, so each struct instance you add is converted -- through boxing.
The structs are still boxed because object
is a reference type as well. In your scenario, there is simply no way to avoid boxing unless you declare the list to be of a specific value type (List<Foo1>
or List<Foo2>
).
In general, using structs for "efficiency" is not at all a simple or obvious thing. In particular, simply chucking in struct
where you'd otherwise write class
is not guaranteed to make your code perform better. Write your code in the obvious way first (and obvious here means: using classes), then determine (through profiling) if you need to optimize it and if so, how.
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