Technically what are the meanings and differences of the terms declaring, instantiating, initializing and assigning an object in C#?
I think I know the meaning of assigning but I have no formal definition.
In msdn, it is said "the act of creating an object is called instantiation". But the meaning creating seems vague to me. You can write
int a;
is a
then created?
Declaring - Declaring a variable means to introduce a new variable to the program. You define its type and its name.
Instantiate - Instantiating a class means to create a new instance of the class. Source.
Initialize - To initialize a variable means to assign it an initial value.
Assigning - Assigning to a variable means to provide the variable with a value.
In general:
Declare means to tell the compiler that something exists, so that space may be allocated for it. This is separate from defining or initializing something in that it does not necessarily say what "value" the thing has, only that it exists. In C/C++ there is a strong distinction between declaring and defining. In C# there is much less of a distinction, though the terms can still be used similarly.
Instantiate literally means "to create an instance of". In programming, this generally means to create an instance of an object (generally on "the heap"). This is done via the
new
keyword in most languages. ie:new object();
. Most of the time you will also save a reference to the object. ie:object myObject = new object();
.Initialize means to give an initial value to. In some languages, if you don't initialize a variable it will have arbitrary (dirty/garbage) data in it. In C# it is actually a compile-time error to read from an uninitialized variable.
Assigning is simply the storing of one value to a variable.
x = 5
assigns the value5
to the variablex
. In some languages, assignment cannot be combined with declaration, but in C# it can be:int x = 5;
.Note that the statement
object myObject = new object();
combines all four of these.new object()
instantiates a newobject
object, returning a reference to it.object myObject
declares a newobject
reference.=
initializes the reference variable by assigning the value of the reference to it.