Ben
Ben

Reputation: 11

combining 2 methods into a generic method in c#

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;
        }

Upvotes: 0

Views: 59

Answers (1)

JonasH
JonasH

Reputation: 36361

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.

Upvotes: 2

Related Questions