Can a struct be derived from a class in c#?
If not, Why can primitive data types, such as int, be derived from the class object
? Since the data type int is basically a struct type(value type).
Is this just an exception to the rule?
A struct cannot inherit from another struct or class, and it cannot be the base of a class.
Yes. you can derive a class from a struct. In C++, a struct is simply a class where the default access is public rather than private.
Structs can implement an interface but they cannot inherit from another struct.
In C++, a structure's inheritance is the same as a class except the following differences: When deriving a struct from a class/struct, the default access-specifier for a base class/struct is public.
In C++, structs and classes are pretty much the same; the only difference is that where access modifiers (for member variables, methods, and base classes) in classes default to private, access modifiers in structs default to public.
Integers and other value types (e.g. bool) are objects, because it allows them to leverage inheritance (i.e. they have access to the common .Equals()
, .GetType()
, .ToString()
functions).
It's a design decision in the .NET framework. Rather than writing separate functions for all the value types under System.ValueType, they use a common code base.
Microsof's document on Types
All structs inherit System.ValueType
, which in turn inherits Object
.
You cannot change that.
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