Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding Struct : Interface to a List<Interface>

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).

  1. Would the structs not be passed as a reference if I added Foo1 or Foo2 to List<IFoo>?
  2. If not, is it safe to do 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.

like image 600
Shyy Guy Avatar asked Feb 12 '15 16:02

Shyy Guy


People also ask

Can a struct implement an interface?

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.

Can a struct contain a list?

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.

Can a struct have an interface Golang?

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.

Can a struct implement an interface C++?

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.


1 Answers

  1. 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.

  2. 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.

like image 137
Jeroen Mostert Avatar answered Sep 26 '22 01:09

Jeroen Mostert