Click here to Skip to main content
15,867,986 members
Articles / Programming Languages / C#
Tip/Trick

Inherit a struct in C#? Why (can)not?

Rate me:
Please Sign up or sign in to vote.
4.51/5 (22 votes)
18 Feb 2015CPOL2 min read 70.9K   14   16
Understanding structs - why C# does not allow a struct to be inherited

Introduction - Why Use Structs Anyway?

Why struct anyway?
We all like C#'s structs very much [an idea alien to Java, apart from primitive types]. Structs, when they do not have to be boxed frequently, provide a nice way to handle relatively small and short lived data.

Allocations and deallocations of value types are in general cheaper than allocations and deallocations of reference types, since structs are allocated either on the stack or inline in containing types and deallocated when the stack unwinds or when their containing type gets deallocated, while reference types are allocated on the heap and garbage-collected.

Hmmm, It Won't Let Me Inherit....

Object Oriented Programming gives us the ability to do quite a lot of stuff, and the basic concept in OO is of course the inheritance.

Many of us have tried at one point to inherit a struct, only to find out that C# does not allow it.

Consider this code for example:

C#
// What on earth can be wrong with this simple code? 
// NOTE: DateTime is a struct, if you didn't already know it, Now() is a good time to find out :)
struct MyDateTime : DateTime
{
    double SecondsFromMyBirthday { get; private set; }
}

// or with this fairly reasonable inherit request:
struct Point
{
   int x, y;
}

struct Point3D : Point
{
   int z;
}

Image 1

An honest programmer wishes to expand the DateTime struct, why shouldn't she?

This code will produce the compile time error: Type 'DateTime' in interface list is not an interface (the reason for this specific error message is the fact that since inheritance is not allowed the compiler expects only an interface after the colon symbol - it does not even take a misuse of inheritance into account...)

If the struct would be replaced to class, the compile time error will produce: 'MyDateTime': cannot derive from sealed type 'System.DateTime'

We understand then, that System.DateTime is (implicitly) sealed. But why?

Note: Actually the fact is that all struct types implicitly inherit from the class System.ValueType, which, in turn, inherits from class object.

Note: Although a Struct cannot be inherited, it can implement an interface.

The Answer

A struct has a fixed size allocated already on the stack.

Now consider the Point / Point3D example above which seems like a nice innocent case. Consider the following line of code:

C#
// Assume we have a p2d which is a Point, 
// and a p3d which is a Point3D
p2d = p3d; 

What should happen on the assignment line then? A memory expansion of p2d on the stack to support the assignment?

Furthermore - structs, being a value type of course, do not use references (unless boxed), this would make polymorphism somewhat meaningless since there is no indirection via a reference pointer.

Also, consider the case of arrays - arrays of value types are stored "inline" (for performance and garbage collection reasons). If we use a struct without knowing it is actually a "derived struct", it will cause memory corruption.

In conclusion - we've seen why it is highly unreasonable for .NET to allow inheritance of a struct. The good news is that you can always inherit ... well ... a class!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Chief Technology Officer
United States United States
Senior dish washing consultant for over 25 years!

Comments and Discussions

 
SuggestionThe article requires significant changes. Pin
Pavel Evgenjevich Timoshenko1-Apr-15 3:29
Pavel Evgenjevich Timoshenko1-Apr-15 3:29 
QuestionIntersting one Pin
Sacha Barber25-Feb-15 22:56
Sacha Barber25-Feb-15 22:56 
AnswerRe: Intersting one Pin
Joezer BH26-Feb-15 2:11
professionalJoezer BH26-Feb-15 2:11 
QuestionWhat do these 2 statements mean ? Pin
Bilal Fazlani23-Feb-15 17:47
Bilal Fazlani23-Feb-15 17:47 
AnswerRe: What do these 2 statements mean ? Pin
Joezer BH23-Feb-15 20:19
professionalJoezer BH23-Feb-15 20:19 
QuestionStructs, why use? Pin
KP Lee23-Feb-15 0:06
KP Lee23-Feb-15 0:06 
QuestionMy vote of 5 Pin
Abhinaw Kumar19-Feb-15 18:56
professionalAbhinaw Kumar19-Feb-15 18:56 
AnswerRe: My vote of 5 Pin
Joezer BH21-Feb-15 20:00
professionalJoezer BH21-Feb-15 20:00 
GeneralMy vote of 5 Pin
_Vitor Garcia_19-Feb-15 3:38
_Vitor Garcia_19-Feb-15 3:38 
GeneralRe: My vote of 5 Pin
Joezer BH19-Feb-15 4:11
professionalJoezer BH19-Feb-15 4:11 
GeneralMy vote of 5 Pin
Humayun Kabir Mamun18-Feb-15 19:51
Humayun Kabir Mamun18-Feb-15 19:51 
GeneralRe: My vote of 5 Pin
Joezer BH18-Feb-15 20:10
professionalJoezer BH18-Feb-15 20:10 
QuestionThankfully we have extension methods Pin
Eric Lynch18-Feb-15 12:30
Eric Lynch18-Feb-15 12:30 
GeneralMy vote of 5 Pin
Afzaal Ahmad Zeeshan18-Feb-15 6:07
professionalAfzaal Ahmad Zeeshan18-Feb-15 6:07 
GeneralRe: My vote of 5 Pin
Joezer BH18-Feb-15 19:08
professionalJoezer BH18-Feb-15 19:08 
GeneralRe: My vote of 5 Pin
Afzaal Ahmad Zeeshan19-Feb-15 4:24
professionalAfzaal Ahmad Zeeshan19-Feb-15 4:24 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.