I am studying C# and I am a little confused with the terminology... I saw that there are still many same questions like this but i am still confused... Can someone explain me the difference between an object and an instance?
2 Answers
The words object and instance basically refer to the same thing.
In object oriented programming there is the concept of classes. You can basically do nothing without a class.
A class is the blueprint for creating an object (classes marked as static, abstract etc. are excluded from this statement.), with specific characteristics and behaviour defined in the class. An object can be also called an instance of a class.
For example:
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
The above is a class. It just defines a type called Person with two properties Name and Age.
When you need a person object (or an instance of this class), you can create it using the new operator and an appropriate constructor (below I use an object initializer).
var person = new Person
{
Name = "Foo",
Age = 30
};
Now the person is an object or equivalently an instance of the class Person.
4 Comments
System.Object. Actually, you can think of a static class as an object which has been created automatically by the runtime on the loading of your application, but no other type can be created based on the class used to create this object. There would be only one object with the specifed behaviour in your app. Beware this is an analogy I tried to use to explain it. Regarding the term instance in this context, I think it's meaningless. You can't say I have an instance of a static class...What's the point?This is only terminology, and common usage. The word object is used, generally to refer to the thing that is created in memory, and referenced or represented by a variable in your code, when you create a data structure based on a class. The word instance means exactly the same thing, but is used when the emphasis is on the fact that a specific object is but one of many objects that may have been or could be created from that class. i.e., an object created from class MyClass is but one instance of myClass.
2 Comments
object as here instance and object are not interchangeable. Objects are "things" like "people", where as an in this analogy an instance would be an individual "person". As all "things" derive from object, people can still be objects, but a person is an instance of an object, not an object.object ? I'm not sure that is even possible. I think not. Or are you referring to the built-in .Net class object that is the root of the class hierarchy? If that is the case, then, technically, every instance (of anything, not just of a person) is indeed an object, just as every moose is indeed an animal.
xis an instance of aWidgetobject."