I am working on developing a playing cards game in C# as part of my training in this new language. I have received several errors that I have been able to Google Fu and work out on my own, but this current error of:
Unhandled Exception:
System.NullReferenceException: Object reference not set to an instance of an object
at Deck..ctor () [0x00087] in :0
at Program.Main (System.String[] args) [0x00000] in :0
[ERROR] FATAL UNHANDLED EXCEPTION: System.NullReferenceException: Object reference not set to an instance of an object
at Deck..ctor () [0x00087] in :0
at Program.Main (System.String[] args) [0x00000] in :0
has me blocked. I have tried a few different ways of refactoring public class Card
and the Card
constructor function, but I just get different errors and more errors and don't get any closer to resolving it as what the error message above is telling me is that I haven't correctly initialized the object Card card = new Card(rank, suit);
using System.Collections.Generic;
public class Deck {
// public List<Card> Cards = new List<Card>();
public List<Card> cards;
public Deck() {
string[] ranks = { "Ace", "Two", "Three", "Four", "Five" };
string[] suits = { "Diamonds", "Hearts", "Clubs", "Spades" };
foreach (string suit in suits) {
foreach (string rank in ranks) {
Card card = new Card(rank, suit);
cards.add(card);
}
}
}
}
public class Card {
// properties
public string suit { get; set; }
public string rank { get; set; }
public Card(string rank, string suit){
//initializations
rank = rank;
suit = suit;
}
}
I looked through similar posts, but they are not specific to my case and I have also been following this guide: