As stated above, is it redundant to inherit from Object in c#? Do both sets of code below result in equivalent objects being defined?
class TestClassUno : Ob
Yes, everything ultimately inherits from an object if defined as class
. Leave the explicit inheritance out of your code.
Object is the mother of all classes in .Net. There is nothing above it.
All classes inherit from it. So this code
class TestClassDos
{
// Stuff
}
automatically means it is inheriting from object.
Proof: You can typecast any entity to object which is possible if it is inheriting from it.
Summary of Object class says
// Supports all classes in the .NET Framework class hierarchy and provides low-level
// services to derived classes. This is the ultimate base class of all classes
// in the .NET Framework; it is the root of the type hierarchy.
MSDN : Object class : Supports all classes in the .NET Framework class hierarchy and provides low-level services to derived classes. This is the ultimate base class of all classes in the .NET Framework; it is the root of the type hierarchy.
Check this research : inherits from object? An investigation into how.
Yes it is redundant to inherit from object in class
Yes, they are both the same thing, I don't think I saw anyone mention structs, but all objects (that is regardless if you declare a class or a struct) they all ultimately inherit from Object, see this Object MSDN article and this other article on Structs
If left unspecified every class
definition will implicitly inherit from System.Object
hence the two definitions are equivalent.
The only time these two would be different is if someone actually defined another Object
type in the same namespace. In this case the local definition of Object
would take precedence and change the inheritance object
namespace Example {
class Object { }
class C : Object { }
}
Very much a corner case but wouldn't point it out if I hadn't seen it before
Note that the same is not true if you used object
instead of Object
. The C# keyword object
is a type alias for System.Object
and hence it wouldn't match Example.Object
.
namespace Example2 {
class Object { }
class C : Object { } // Uses Example.Object
class D : object { } // Uses System.Object
}
Of course if you have a truly evil developer you could still cause confusion with object
namespace System {
class Object {
private Object() { }
}
}
namespace Example3 {
// This will properly fail to compile since it can't bind to the private
// Object constructor. This demonstrates that we are using our definition
// of Object instead of mscorlib's
class C : object { } // Uses our System.Object
}