How do I call a string inside a different class?

I’m trying to call a string that’s inside a different class, and am wondering how to do so. Currently my though process is just Console.WriteLine(CardData.cardType) But that’s obviously not working.

Code:


namespace ConsoleUno
{
    class Program
    {
        public static class wholeTing
        {
          public static List<CardData> cardDataList = new List<CardData>();

          public class CardData
          {
            public string cardType { get; set; }
            public int cardColor { get; set; }
          }

          static void Main(string[] args){
           Console.WriteLine(this.cardDataList.FirstOrDefault().CardType);
        }
    }
}

>Solution :

Let me write a little summary. Objects in C# are passed by reference. This means the object will hold the value changed in all functions and will be carried to the others. The order of the calling of the function, however, decides which value when will be added.

public static List<CardData> cardDataList = new List<CardData>();

public class CardData
{
  public string cardType { get; set; }
  public int cardColor { get; set; }
}

static void Main(string[] args){
 Console.WriteLine(this.cardDataList.FirstOrDefault().CardType);
}

// another function should be called before the printing
public void MyAddFunction()
{
  cardDataList.Add(new CardData() { cardType = boxLine1, cardColor = randColor });
}

Hope that answers your question. Happy coding!

Edit:

If the function does not change the public value, you should return the new list from the function and assign it to your list.

public List<CardData> MyAddFunction()
{
  var cardDataList = new List<CardData>();
  cardDataList.Add(new CardData() { cardType = boxLine1, cardColor = randColor });
  return cardDataList;
}

static void Main(string[] args){
  this.cardDataList = MyAddFunction();
  Console.WriteLine(this.cardDataList.FirstOrDefault().CardType);
}

Edit

Regarding your question on how to search inside cardType for specific keywords. You can use many functions like
.StartsWith .EndsWith .Contains … etc.

static void Main(string[] args){
 var yourKeyword = "...Whatever";
 var theObjectYouWant = this.cardDataList.FirstOrDefault(x => x.CardType.StartsWith(yourKeyword));
 // the theObjectYouWant should contain the first match item or null in case of no match
 Console.WriteLine(theObjectYouWant.CardType);
}

Leave a Reply