C# – If a struct cannot inherit another class or struct, why does Int32 have a ToString() method?

cinheritancenetstruct

int a = 2;

Console.WriteLine(a.ToString()); // displays 2

// definition of ToString() here - public override string ToString();

Now, here are some of my understandings:

  1. All the classes in .net get a ToString() method, which is inherited from the Object class.
  2. A structure cannot be derived from a Class or another struct. int is a structure of type Int32, which gets a couple of ToString() [With Parameters] methods from the Interfaces which it implements.
  3. There is also a ToString() [without params] function in struct Int32

According to http://msdn.microsoft.com/en-us/library/system.int32.tostring.aspx,

struct Int32 overrides ValueType.ToString() method

If a struct cannot inherit some class or struct, can you please explain how this ToString() method is available for Int32?

Best Answer

If a struct cannot inherit some class or struct,

This isn't true. All structs (and the built-in value types, like System.Int32, System.Single, etc) always implicitly inherit from System.ValueType (which, in turn, inherits from System.Object).

However, you can't make a struct that inherits from anything else.

This is clearly spelled out in the C# language spec, 4.1.1:

4.1.1 The System.ValueType type

All value types implicitly inherit from the class System.ValueType, which, in turn, inherits from class object. It is not possible for any type to derive from a value type, and value types are thus implicitly sealed (ยง10.1.1.2).

Then, later (4.1.3) struct is explicitly defined to be a value type:

4.1.3 Struct types

A struct type is a value type that can declare constants, fields, methods, properties, indexers, operators, instance constructors, static constructors, and nested types.