0

I created the below class with constant properties so I can use it as sort of enum.

public class Interval
{
  public const string FiveMinutes = "5m";
  public const string FifteenMinnutes = "15m";
  public const string OneDay = "1d";
  public const string OneWeek = "1wk";
  public const string OneMonth = "1mo";
}

The content of the method expects Interval.

public IRestResponse GetSpark(string Symbol, Interval Interval)
        {
  var url = $"https://...?interval={Interval}";
  return RestAPI.RestCall(url);
}

When using Interval.OneWeek I get the error 'CS1503: Argument 2: cannot convert from 'string' to 'class.Enum.Interval'.'

var foo = new fooClass();
var fooMethod = fooClass.GetInfo("Example", Interval.OneWeek);

Why do I get this error and how to resolve it?

Rufus L
  • 36,127
  • 5
  • 30
  • 43
Alex_P
  • 2,580
  • 3
  • 22
  • 37
  • Could you show the code for _fooClass.GetInfo_? The error talks about an enum involved but I can't see anywhere an enum here – Steve Oct 04 '20 at 21:43

2 Answers2

3

Assuming the call is actually:

fooClass.GetSpark("Example", Interval.OneWeek);

You're calling this method with two strings as arguments: "Example" and "1wk" (the const string defined in Interval). The GetSpark method actually requires a string and an Interval class, which is not what you're supplying.

So rewrite your GetSpark method to:

public IRestResponse GetSpark(string symbol, string interval)
{
  var url = $"https://...?interval={interval}";
  return RestAPI.RestCall(url);
}
Styco
  • 93
  • 7
1

Note. There are inconsistencies in your question (the method name in the second code snippet is GetSpark, but you call GetInfo in the third snippet)

The method expects the class Interval, but you're only passing in the string value constant of Interval. Either change the method signature to accept a string instead of an Interval

public IRestResponse GetSpark(string Symbol, string Interval)

Or replace Interval with an enum

public enum Interval
{
    [Display(Name = "5m")]
    FiveMinutes,
    [Display(Name = "15m")]
    FifteenMinutes,
    [Display(Name = "1d")]
    OneDay,
    [Display(Name = "1wk")]
    OneWeek,
    [Display(Name = "1mo")]
    OneMonth,
}

You can use this extension method to retrieve the Display Names (thanks to this answer):

public static class Extensions
{
    public static string GetEnumDisplayName(this Enum enumType)
    {
        return enumType.GetType().GetMember(enumType.ToString())
            .First()
            .GetCustomAttribute<DisplayAttribute>()
            .Name;
    }
}

And replace the first line with this:

var url = $"https://...?interval={Interval.GetEnumDisplayName()}";
Hayden
  • 2,902
  • 2
  • 15
  • 29