-2

I have this if statement, where I validate that if the id is null and the currentIndex is equal to 1, then I assign the id as "dunk1", but my problem is that the ID is always empty, what am I doing wrong?

public void TryBuyById(string id)
    {
        if (id is null && currentIndex == '1')
        {
            id = "dunk1";
            ShopManager.Instance.BuyProductById(id);
        }
        else
        {
            UnityEngine.Debug.Log("Este es el currentIndex... :" + currentIndex);
            UnityEngine.Debug.Log("Este es el ID... :" + id);           
        }
    }

I thank you for your help!

  • I think you can knock down your [mre] to [this code](https://dotnetfiddle.net/FWSeSJ). – gunr2171 Feb 02 '22 at 22:09
  • You need to show a [mcve]. We can't see where `id` and `currentIndex` is updated. All we can say is that `id` is not `null` or `currentIndex` is not `'1'`. – Enigmativity Feb 02 '22 at 22:09
  • 1
    Does this answer your question? [C# string reference type?](https://stackoverflow.com/questions/1096449/c-sharp-string-reference-type) – gunr2171 Feb 02 '22 at 22:10
  • Good pick up, @gunr2171. I think you're probably right. – Enigmativity Feb 02 '22 at 22:11
  • 1
    If I'm not right (and knowing me, good possibility) then `id` is an empty string as the parameter value, and we need more information to figure this out. – gunr2171 Feb 02 '22 at 22:12
  • @mariano-bozzone If the id is empty when the method is called, say like `id = ""`, then the code will always go into the else loop. If the control should go to the if loop, then you may want to check for `id == ""` instead of `id is null` as null and empty string "" are not the same . – Ragavendra Feb 02 '22 at 22:58

1 Answers1

0

Finally I was able to solve it, I changed the script for this:

public void TryBuyById()
    {
        string id = "";
        int currentindex = currentIndex;

        if (currentindex == 1)

        {
            id = "dunk1";
            ShopManager.Instance.BuyProductById(id);                        
        }
        else
         if ( currentindex == 2)

        {
            id = "dunk2";           
            ShopManager.Instance.BuyProductById(id);                        
        }

just by passing the value of the currentIndex I reach it.

Thank you all for your messages, they helped me!

  • You don't need the `currentindex` variable here -- just check `if (currentIndex == 1)` directly. – Astrid E. Feb 04 '22 at 13:24
  • Also, if nothing more is happening inside `TryBuyById()`, you could simply say `if (currentId == 1) { ShopManager.Instance.BuyProductById("dunk1") }`, and similarily for the case of `currentIndex == 2`. – Astrid E. Feb 04 '22 at 13:27