-
January 26th, 2010, 08:24 PM
#1
wierd allocation
I am wondering about this piece of code:
Code:
class Deck
{
//Wow didn't know you would ever want to allocate in the class definition
private List<Card> Cards = new List<Card>(52);//52 is not a hard and fast number
public Deck()
{
It looks like the List will be a static because it gets allocated when the class is read by the compiler. Is this sort of a bad way to allocate this? Shouldn't the objects be allocated in the constructor?
ahoodin
To keep the plot moving, that's why.
-
January 26th, 2010, 08:31 PM
#2
Re: wierd allocation
No, it is not static at all, it is by definition an instance variable, i.e., each instance of a class owns a separate copy. You are confused about when it is allocated, and it is not bad at all; you should do that when you need a variable to hang around for the lifetime of an object. What do you think is going on when you create a backing field for a property? You are creating an instance variable and two methods, one to set it and one to return it.
-
January 27th, 2010, 05:28 AM
#3
Re: wierd allocation
Just to add to BigEd781's explanation...
Instance fields will be initialised when the instance of the class is created. You could decided to have initialisation in the constructor (directly or via an initialisation method). The benefit of that is when you have a complex initialisation (e.g. you are initialising a collection of items) or when you have constructor arguments that are key for the initialisation of the class. Secondly the number 52 only specifies the initial capacity of the list. The list can grow if need be.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|