Reputation: 11
Yeah, sorry if my question wasn't asked right- im new, dont know all the rules. Thanks for correcting me, ill definitely keep these in mind for the future.
Basically, I'd like to know if there is a method in C# which checks a variable's type and returns a bool value.
Kinda like isinstance(variable, type) in Python.
Example for that:
x = "apple"
isinstance(x, str) -> returns true, because x is a string
isinstance(x, int) -> returns false, because x is not an int
Thanks,
Upvotes: 1
Views: 1429
Reputation: 172478
Each player object returns a PlayedCard variable. If the player puts down one card, the PlayedCard will be a single Card object, if the player puts down multiple cards, it will be an Array of Card objects.
Frankly, this is not a good idea.
On of the great strengths of C# is its strong type system. Once your program compiles, a lot of potential bugs are already gone.
I suggest the following alternatives (in order from simple to complex):
Always return an array. If the player puts one card down, return a single-element array.
Or wrap the array in a custom object with exactly the properties you need (bool PlayedSingleCard => backingArray.Count == 1;
, etc.).
Upvotes: 3
Reputation: 750
You want the is
operator
if (playedCard is Card card)
{
//do single card stuff
}
else if (playedCard is Card[] cards)
{
//do things with the array
}
You could also consider making the second check be on IEnumerable<Card>
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/is
Upvotes: 1