If we had a class, say MyClass, when instantiating an object of that class, what is the difference between these two:
Object obj=new MyClass();
MyClass obj2=new MyClass();
I know that in .NET, all classes derive from System.Object, so that in this case, obj and obj2 variables just contain references to the objects.
However, is there any difference?
And if so, what is it, when using these two ways of instantiating objects?
Supposing your class had a property called
Name, if you used this,and tried to use:
This would be a compiler error, because the Object class does not have a
Nameproperty. This, however, would be fine:because the
obj2is aMyClass. In short, in order to access a variable’s class members (properties, methods, variables), that variable has to be of a type that has those members, or it needs to be cast to the necessary class:However, constantly casting variables in order to get at their members is not good, as it requires extra CPU cycles and can lead to InvalidCastExceptions.