Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does every type in .net inherit from System.Object? [duplicate]

Tags:

c#

.net

This might be a very basic question, but I am a bit confused about it. If I reflect the Int32/Double/any value type code, I see that they are structs and look like :

[Serializable, StructLayout(LayoutKind.Sequential), ComVisible(true)] public struct Double : IComparable, IFormattable, IConvertible, IComparable<double>, IEquatable<double> { .... } 

So, why do we say that everything in .NET is derived from System.Object. I think am missing some crucial point here.

EDIT: What confuses me further is that how can a value type which is struct inherit from System.Object which is a class.

like image 987
P.K Avatar asked Aug 22 '09 18:08

P.K


People also ask

Which data types are inherited from System object?

Solution 2. All types are inherited from System. Object , including System. ValueType , and all value types inherit from System.

Are value types derived from System object?

You are correct that, while Object is a reference type, value types do inherit from it implicitly, as stated on msdn's reference for Value Types (according to the reference, they technically inherit from the ValueType class, which in turn inherits from Object.

Does interface inherit from object C#?

Every type in C# directly or indirectly derives from the object class type. Eric Lippert says: Interface types, not being classes, are not derived from object.

Why Multiple inheritance is not possible in C#?

C# compiler is designed not to support multiple inheritence because it causes ambiguity of methods from different base class. This is Cause by diamond Shape problems of two classes If two classes B and C inherit from A, and class D inherits from both B and C.


1 Answers

Eric Lippert has covered this in a blog entry: Not everything derives from object (This is the title of the blog entry; not the answer to this question. Don't get confused.)

Yes, all structs inherit from System.ValueType which in turn inherits from System.Object. enums you declare inherit from System.Enum which inherits from System.ValueType.

Update:

Inherently, there's not a problem with a value type being derived from a reference type. Inheritance is a "is-a" relationship between two types. However, in order to treat a value type as an object instance, it has to be boxed. This is done implicitly when you are passing a value to a method that expects an object parameter (or when you call instance methods implemented in System.Object.)

like image 62
mmx Avatar answered Oct 02 '22 16:10

mmx