Search code examples
c#objectinstancenew-operatorinstantiation

C# Object Intantiation format question declaring a variable vs not declaring a variable


I am new to C# and I think I am seeing 2 diferent ways to do the same thing or maybe I just am not understanding. My "Murach's C# 2015" book has on page 369 an example of creating 2 object instances like this:

Product product1, product2;
product1 = new Product("something", "something else", more stuff);
product2 = new Product("something different", "something else different", more different stuff);

Can you also do it this way?

Product product1 = new Product("something", "something else", more stuff);
Product product2 = new Product("something different", "something else different", more different stuff);

It seems like some sources online do it one way and other sources do it the other way, or like I said... Maybe I am just missing something.


Solution

  • You have to declare the variable (once) before you use it, but you can assign the declared object variable multiple times.

    // declare the variable
    Product product1 
    // assign to first product
    product1 = new Product("first product");
    // assign to a different product
    product1 = new Product("second product");
    

    You can use the technique of declaring and assigning as "shorthand", so you could combine the first two lines of code (not counting the comments):

    //declare and assign the variable in one step
    Product product1 = new Product("first product");
    //re-assign the previously declared variable to a different object
    product1 = new Product("second product");
    

    You only declare the variable once so this would give you an error:

    Product product1 = new Product("first product");
    Product product1 = new Product("second product");