0

I have this class and i want that to accept a generic as an enum I can pas it in the constructor but I want to use generic.

this is my interface:

public interface ITrnApi<TEnum> : IDisposable where TEnum : struct

and I want my class to be like this one

public class TrnApi<TEnum> : ITrnApi<TEnum> where TEnum : struct
{
    private readonly HttpClient _http;

    public TrnApi(HttpClient http, TEnum company)
    {
        _http = http;
        _http.BaseAddress = company.ToBaseUrl().ToUri();

        //public enum Company
        //{
        //    test = 1,
        //    othertest = 2
        //}
    }
}

but get this error:

'TEnum' does not contain a definition for 'ToBaseUrl' and the best extension method overload 'Extentions.ToBaseUrl(Company, string)' requires a receiver of type 'Company'

How can I do that?

alirezas
  • 89
  • 1
  • 10
  • 2
    If you are looking for a generic `enum` constraint, see [Create Generic method constraining T to an Enum](https://stackoverflow.com/q/79126/3744182). But it appears that `Extentions.ToBaseUrl()` is an extension method on a *specific type* of enum, specifically `Company`, so using a generic here isn't sensible. – dbc Jan 19 '20 at 10:08
  • @dbc you mean it cant be done? – alirezas Jan 19 '20 at 10:18
  • I don't understand what you want to do. Why are you making the class generic when only one specific `enum` type is actually allowed? Is the `enum` saved somewhere in the class, even though it isn't shown? Can you edit your question to share a [mcve]? – dbc Jan 19 '20 at 10:19
  • @dbc the thing I trying to do you said it in your first comment so you suggest I should use the constructor for that – alirezas Jan 19 '20 at 10:26
  • @alirezas Please, share with us `ToBaseUrl()` method, how it's declared – Pavel Anikhouski Jan 19 '20 at 12:37

1 Answers1

2

The System.Enum constraint is available starting from C# 7.3.

public class TrnApi<TEnum> : ITrnApi<TEnum> where TEnum : struct, Enum
{
    private readonly HttpClient _http;

    public TrnApi(HttpClient http, TEnum company)
    {
        _http = http;
        _http.BaseAddress = company.ToBaseUrl().ToUri();
        /* ... */
    }
}
smolchanovsky
  • 1,775
  • 2
  • 15
  • 29