Home > database >  combining 2 methods into a generic method in c#
combining 2 methods into a generic method in c#

Time:06-11

I'm trying to find a way to make this into one generic method, where I can either parse the value as a decimal or as an int. Does anyone know a good way to do this?

        private int ParseIntField(string value, int linecount, string fieldName)
        {
            if (!Int32.TryParse(value, out int result))
            {
                throw new Exception($"TryParse failed, line {linecount} Fieldname: {fieldName} Value: {value}");
            }
            return result;
        }

        private decimal ParseDecimalField(string value, int linecount, string fieldName)
        {
            if (!decimal.TryParse(value, out decimal result))
            {
                throw new Exception($"TryParse failed, line {linecount} Fieldname: {fieldName} Value: {value}");
            }
            return result;
        }

CodePudding user response:

There is no really good way to use a generic method for this, but you could perhaps split the method to share the common functionality, for example:

int? ParseInt(string s) => int.TryParse(s, out r) ? r : null;
decimal? ParseDouble(string s) => decimal.TryParse(s, out r) ? r : null;
T ParseOrThrow<T>(string str, int linecount, string fieldName, Func<string, T?> parser){
    return parser(s) ?? throw new Exception($"TryParse failed, line {linecount} Fieldname: {fieldName};
}

And called like ParseOrThrow("5", 2, "five", ParseInt);. But the benefit is probably marginal unless you have more code that needs to be shared between the different types.

CodePudding user response:

This is what I've ended up with, so far it seems to have worked fine. Please let me know if there is any issue with this is!

public static T TryParseAndException<T>(string value, int linecount, string fieldName)
        {
            T results;
            try
            {
                results = (T)Convert.ChangeType(value, typeof(T));
            }
            catch (Exception)
            {

                throw new Exception($"TryParse failed, line {linecount} Fieldname: {fieldName} Value: {value}");
            }
            return results;
        }```
  • Related