5

I'm 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 that Player.Hand can only contain four cards (Card is a class that represent a card).

How can I do it? The above code show the exception "matrix size cannot be specified in variable declaration". And if I use List<Card>(), I can set max size.

1
  • 1
    While the error is quite apparent here, posting the actual error is preferable to "It doesn't work". Just some advice for future questions. Commented Nov 25, 2014 at 19:06

2 Answers 2

7

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

You need to create it with that size:

public Card[] Hand {get; set;}

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

You could also use a 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!
}
Sign up to request clarification or add additional context in comments.

Comments

2

In the property declaration, you should specify only property type, but not the data. The array size can be specified in the moment of array creation.

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
{
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.