Click here to Skip to main content
15,885,546 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
public List<Pizza> Pizzas { get; set; }  = new List<Pizza>(); 


Above is code line which is in one of books.
Below is code snippet written by me.
I am new to C# ,will anyone please help me
What is meaning of "=new List<pizza>()"
And what if I write like below?

public List<Pizza> pizzas
        {
            get { return pizzas; }
            set { pizzas = value; }
        }


What I have tried:

I found though net the down snippet
Posted
Updated 9-Aug-22 1:58am

1 solution

The first snippet is a correct auto-property with an initializer:
Auto-Implemented Properties - C# Programming Guide | Microsoft Docs[^]

Auto properties have been around since C# 3; the property initializer syntax was added in C# 6.

The second snippet is a StackOverflowException waiting to happen. The property get method calls itself in an infinite recursion. The property set method does the same.

The correct implementation requires a field:
C#
private List<Pizza> _pizzas = new List<Pizza>(); 

public List<Pizza> Pizzas
{
    get { return _pizzas; }
    set { _pizzas = value; }
}
As you can see, that's a lot more code "ceremony" for exactly the same result.
 
Share this answer
 
Comments
adityarao31 9-Aug-22 8:26am    
Thanks

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900