What is the difference between “instantiated” and “initialized”?

后端 未结 11 2275
青春惊慌失措
青春惊慌失措 2020-11-30 17:02

I\'ve been hearing these two words used in Microsoft tutorials for VB.NET. What is the difference between these two words when used in reference to variables?

11条回答
  •  清歌不尽
    2020-11-30 17:58

    A variable is initialized with a value. An object is instantiated when memory is allocated for it and it's constructor has been run.

    For instance here is a variable:

    Dim obj as Object
    

    This variable has not been initialized. Once I assign a value to the obj variable, the variable will be initialized. Here are examples of initialization:

    obj = 1
    obj = "foo"
    

    Instantiation is a very different thing but is related since instantiation is usually followed by initialization:

    Dim obj As New Object()
    

    In the preceding line of code, the obj variable is initialized with the reference to the new Object that was instantiated. We say that the new Object was instantiated because we have created a new instance of it.

    Now I believe that VB.NET makes this a lot more confusing than C# because it is not clear that an assignment is taking place in the code above. In C# it is much clearer that there is both an instantiation of an instance and an initialization of a variable:

    Object obj = new Object();
    

提交回复
热议问题