-9

Please, I want to implement inheritance between two Structs. Performance is highly important.

Sample code:

struct IntColl
{
}

struct ValidIntColl : IntColl
{
}

Message from Visual Studio:

Error 1 Type 'IntColl' in interface list is not an interface

How do I get this error? IntColl is a Struct, not an Interface!

Yandros
  • 722
  • 1
  • 8
  • 16

5 Answers5

4

Structs can only implement interfaces, they can't inherit other structs.

For more information, please see these other questions:

Community
  • 1
  • 1
valverij
  • 4,871
  • 1
  • 22
  • 35
1

struct (C# Reference)

Structs can implement an interface but they cannot inherit from another struct.

So you simply can't inherit from struct to create another struct.

MarcinJuraszek
  • 124,003
  • 15
  • 196
  • 263
1

You can also use composition, since inheritance won't work here:

struct IntColl
{
}

struct ValidIntColl
{
    IntColl MyIntCollField;
}
mao47
  • 967
  • 10
  • 25
0

C# doesn't have struct inheritance. You'll need to change them into classes. Speed shouldn't be impacted all that much.

System Down
  • 6,192
  • 1
  • 30
  • 34
0

I want to create a struct that inherits from another struct so it gets put on the stack

You cant:

Structs can implement an interface but they cannot inherit from another struct.

per MSDN

Speed is of high importance

You are assuming that structs are slower than classes. While there may be some speed difference, I would not make this assumption categorically. What you are doing with the clases/structs is very likely to be slower than the memory access.

If inheritance is a key requirement, then you'll need to build your objects as classes rather than structs. Or use another pattern like encapsulation (have one struct be a property of another).

If you get to the point that you can prove that classes will be slower that structs in your scenario, your only option may be to replicate the necessary fields in the structure map.

D Stanley
  • 149,601
  • 11
  • 178
  • 240