Fixed array size

I am developing a WPF game with C # and .NET Framework 4.5.1.

I have this class:

public class Player
{
    public Card[4] Hand { get; set; }
}

      

And I need to set what Player.Hand

can only contain four cards ( Card

is the class representing the card).

How can i do this? The above code shows the exception "matrix size cannot be specified in variable declaration"

. And if I use List<Card>()

, I can set the maximum size.

+3


source to share


2 answers


The size of the array is not part of its type.

You need to create it with this size:

public Card[] Hand {get; set;}

public MyClass()
{
    Hand = new Card[4];
}

      



You can also use the full property and initialize the array to that size.

private Card[] hand = new Card[4];
public Card[] Hand
{
    get { return hand; }
    //Set if you want!
}

      

+3


source


In a property declaration, you must only specify the type of the property, not the data. The size of the array can be specified at the time the array is created.



public class Player
{
   public void Initialize()
   {
       // An example of initialization logic
       Hand = new Card[4];
       for (int i = 0; i < Hand.Length; i++)
           Hand[i] = new Card();
   }

   public Card[] Hand { get; set; } 
}

public class Card
{
}

      

+1


source







All Articles