Reputation: 2665
I need to clarify a thing that how an object type variables accept class type instance an given in the below code snippet,
class MyClass
{
}
static void Main()
{
object obj = new MyClass();
}
Since the MyClass is not a type of object but still the instance of MyClass is accepted in the obj(object) variable.
Upvotes: 2
Views: 298
Reputation: 2382
MSDN:
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.
Inheritance Hierarchy:
All classes, structures, enumerations, and delegates.
This means when you use int.Parse()
to cast some value to int
, there is a class behind int
type which makes it able to have methods and do such stuffs. Object
has been rooted pretty much everywhere in .Net.
Upvotes: 1
Reputation: 10456
Actually, your class is an object.
In C# all classes derives from object.
Referring to a class as it's base type is one way of Polymorphism.
It might be better understood using an analogy:
Your class is an object, like a Dog is an animal.
Also, If you try the following:
object obj = new MyClass();
bool isMyType = obj == typeof(MyClass); //<--this will be true.
Take a look at this SO thread for more information how Polymorphism can be useful.
Upvotes: 3
Reputation: 32797
Everything in C# is derived from Object.
Even Value Types like struct(int,float,..) are all derived from Object type.
When you define your own class,it implicitly derives from the Object type.
It is mentioned in the docs
All classes, structures, enumerations, and delegates inherit from Object class
Upvotes: 1
Reputation: 12619
The concept that you do not understand is polymorphism which basically say that you can define an is
relation between your classes. For a simple logic every dog is an animal so you can have class Dog
that inherits from Animal
. This implies that you can assign to variable of type Animal
an instance of a Dog
but not the other way around - not every animal is a dog. Another thing is that every thing derives form object this is language concept that you simply can take for granted.
Upvotes: 2
Reputation: 11687
.Net
follows OOPs
(Object Oriented Programming Language) and here every class can act as a object. Every class inherits Object class and hence every class can act as an object. In your example, .Net creates a default constructor to create instance of the class. You can definitely write your own constructor there.
Hope it helps.
Upvotes: 1