Home > Enterprise >  How can I return the specified type in generic method?
How can I return the specified type in generic method?

Time:12-19

I want to get specified type value from database. Here is my code:

public static T Get<T>(string key)
        {
            Databases.Context Context = new Databases.Context();
            var i = Context.Setting.FirstOrDefault(_ => _.Key == key)?.Value;
            if (i == null) {
                return default;
            }
            switch (typeof(T))
            {
                case Type intType when intType == typeof(int):
                    {
                        if (int.TryParse(i, out int Result))
                        {
                            return Result;
                        }
                        else{
                            return default;
                        }
                    }
            }
        }

As the code above, part of my code is about to return int type value. However, VS reports an error that it cannot convert int to T. How can I solve this? Thank you.

CodePudding user response:

To solve the error, you can use the Convert class to explicitly convert the int value to the desired type T.

public static T Get<T>(string key)
{
    Databases.Context Context = new Databases.Context();
    var i = Context.Setting.FirstOrDefault(_ => _.Key == key)?.Value;
    if (i == null) {
        return default;
    }
    switch (typeof(T))
    {
        case Type intType when intType == typeof(int):
            {
                if (int.TryParse(i, out int Result))
                {
                    return (T)(object)Result;
                }
                else{
                    return default;
                }
            }
    }
}

Alternatively, you can use the System.ComponentModel.TypeConverter class to perform the conversion. This approach allows you to handle more complex types and may be more flexible in some cases.

You can modify your code to use TypeConverter,

public static T Get<T>(string key)
{
    Databases.Context Context = new Databases.Context();
    var i = Context.Setting.FirstOrDefault(_ => _.Key == key)?.Value;
    if (i == null) {
        return default;
    }
    var converter = System.ComponentModel.TypeDescriptor.GetConverter(typeof(T));
    if (converter.CanConvertFrom(typeof(string)))
    {
        return (T)converter.ConvertFromString(i);
    }
    else
    {
        return default;
    }
}

CodePudding user response:

You can do like this, you need to convert to the respective type.

public static T Get<T>(string key)
{
    
    Databases.Context Context = new Databases.Context();
    var i = Context.Setting.FirstOrDefault(_ => _.Key == key)?.Value;
    if (i == null)
    {
        return default;
    }
    switch (typeof(T))
    {
        case Type intType when intType == typeof(int):
            {
                if (int.TryParse(i, out int Result))
                {
                    return (T)Convert.ChangeType(Result, typeof(T));
                }
                else
                {
                    return default;
                }
            }
    }

    return (T)Convert.ChangeType(default, typeof(T));
}

CodePudding user response:

You'll have to provide different versions of your function for different types: GetAsInt, GetAsString, etc.

A common pattern is to have the shared code in a helper method which returns a string and then specialised methods call TryParse.

Something like:

int? GetAsInt(string name) 
{
   var s = GetSetting(name);
  if(string.IsNullOrEmpty(s)) return null;

  if(int.TryParse(s out var i)) return i;

 return null; //or throw

// repeat for uint, long, etc. as needed

You could also provide Try versions : bool TryGet(string name, out int setting)

CodePudding user response:

You could pass a generic type T as a parameter and return int if that's what the function will always return

  •  Tags:  
  • c#
  • Related