Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can a struct be derived from a class in c#?

Tags:

c#

class

struct

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?

like image 213
Nithish Inpursuit Ofhappiness Avatar asked Dec 04 '12 17:12

Nithish Inpursuit Ofhappiness


People also ask

Can struct can be used as a base class for another class?

A struct cannot inherit from another struct or class, and it cannot be the base of a class.

Can we derive a class from struct in C++?

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.

Can struct derive from struct?

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

How do you inherit a 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.

Is a struct in C like a class?

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.


2 Answers

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

like image 177
Alexander Matusiak Avatar answered Sep 23 '22 22:09

Alexander Matusiak


All structs inherit System.ValueType, which in turn inherits Object.

You cannot change that.

like image 37
SLaks Avatar answered Sep 22 '22 22:09

SLaks