patterncsharpMinor
Converting objects to type Bool
Viewed 0 times
typeconvertingboolobjects
Problem
The following extension method is being used in our code base:
It leverages off another extension method:
(where the ToInt and all the Is* methods are wrappers around the appropriate objects IsNullEmpty / Parse method)
This does not 'feel' right but I cannot explain it to the author. Besides for the obvious problem of passing an object that cannot be cast to a string what other reasons are there to justify this as bad code?
Are there any other concrete reasons why this code may be good or bad?
public static bool ToBool(this object src)
{
return src != null && ((string) src).ToBool(false);
}It leverages off another extension method:
public static bool ToBool(this string src, bool defaultValue)
{
if (src.IsEmpty())
return defaultValue;
if (src.IsNumeric())
return src.ToInt() != 0;
var ret = false;
if (bool.TryParse(src, out ret))
return ret;
return defaultValue;
}(where the ToInt and all the Is* methods are wrappers around the appropriate objects IsNullEmpty / Parse method)
This does not 'feel' right but I cannot explain it to the author. Besides for the obvious problem of passing an object that cannot be cast to a string what other reasons are there to justify this as bad code?
Are there any other concrete reasons why this code may be good or bad?
Solution
I'd criticize:
- Extension methods on "object" should be avoided because of the broad scope, except for special cases (which such a "ToBool" method is not one). It also feels like an overuse of extension methods.
- The first one takes an "object", but really wants a string, and will blow up with an
InvalidCastExceptionat runtime.
- The second one does not check for
null(which wouldn't be a problem in itself, but having overloads for default values with differing behavior is bad).
Context
StackExchange Code Review Q#920, answer score: 7
Revisions (0)
No revisions yet.