Home > front end >  C# Cannot implicitly convert type
C# Cannot implicitly convert type

Time:12-14

I am a bit confused on why isn't this code running through. This is only a small portion of the code, but everything works besides the part of the code where I try to:

return item.priceUsd and return "No Price Found", That I am trying to assign to a variable string coin_price

public class Exchange
{
    public string exchangeId { get; set; }
    public string baseId { get; set; }
    public string quoteId { get; set; }
    public string baseSymbol { get; set; }
    public string quoteSymbol { get; set; }
    public string volumeUsd24Hr { get; set; }
    public string priceUsd { get; set; }
    public string volumePercent { get; set; }
}

public class Exchanges
{
    public List<Exchange> data { get; set; }
}

public static Exchanges GetPrice(string coin_name, string exchange_name)
    {
        using (HttpClient Client = new HttpClient())
        {
            
            string response = Client.GetStringAsync(base_URL   "assets/"   coin_name   "/markets").Result;
            Exchanges list = JsonConvert.DeserializeObject<Exchanges>(response);
            
            foreach(var item in list.data)
            { 
                if(item.exchangeId == exchange_name)
                {
                    return item.priceUsd;
                }

            }

            return "No Price Found";
        }
        
    }
public class Program
{

    static void Main(string[] args)
    { 
       
        string coin_price = Method.GetPrice(name, ename);
        
        //Console.WriteLine(coin_price);

        Console.ReadLine();
    }
}

I keep getting the " Cannot implicitly convert type " error. But I've made sure the type of "item.priceUsd" is a string and I am trying to return it and assign to another string "coin_price".

What am I missing here?

CodePudding user response:

So, the main issue I see is that the method needs to return the class type Exchanges and you are returning a string

C# is type-safe, meaning that when you declare a new method and tell it that the return value is supposed to be a string, the method body needs to return a string.

so that is why it is returning the error Can't implicitly convert type.

Since you are returning strings, either way, try to change the methods return type to string.

Like this:

public static string GetPrice(string coin_name, string exchange_name){
  //your code here.
}

If you want to return another type, you need to change the return values so that it returns the type the method needs.

  • Related