EDN Admin
Well-known member
I am building an app that generates a lot of percentages, so of course I have to deal with divide by zero issues. I can create a utility method that takes in the values and returns a valid value if a divide by zero is encountered, but I was hoping to implement
something global. Take this example:
<pre class="prettyprint double completedOnTime = (double)completedOnTime / completedTotal;[/code]
Theres actually 2 things Id like to do here. One probably isnt possible, and the other isnt looking good, either. First, if I dont cast one of the operands to double, I get a truncated integer (the operands are both integers). Since Im assigning the
division result to a double variable, it certainly would be nice if C# figured out that I wanted a double value from the operation, and not just convert the truncated integer to a double afterwards. I do a lot of programming in ASP.NET MVC with C#, and theres
a lot of programming by convention going on there, and Ill admit its spoiled me a bit. Its "understood" that you mean to do some things by default, so theres no need to spell very obvious things out. I cant think of many instances in which youd want
to assign a truncated integer result to a double variable. But thats a side-rant, and not my question (unless someone knows how to get around this - Im always looking for ways to clean up and minimize my code).
What I really want is to automatically return zero in any case that a divide by zero is encountered. What I do NOT want to do is write a separate try/catch handler for every single place in my app that a percentage is calculated. As I mentioned above, I
could write a utility method and pass all my values through it to calculate percentages, and do the check/return there. That will still require adding references and either instantiating a utility class or calling a static utility method. Sometimes
this is still an ugly solution, like the DaysInMonth method of the DateTime class. I wrote an extension method to get around it, because I found the calls unecessarily verbose.
<pre class="prettyprint // The normal way of calling this method:
DateTime someDate = DateTime.Now;
int daysInMonth = DateTime.DaysInMonth(someDate.Year, someDate.Month);
// My extension method:
/// <summary>
/// Returns an integer of the number of days in the current month.
/// </summary>
/// <param name="source" />DateTime
/// <returns>int</returns>
public static int DaysInMonth(this DateTime source)
{
return DateTime.DaysInMonth(source.Year, source.Month);
}
// Calling the new extension method:
DateTime someDate = DateTime.Now;
int daysInMonth = someDate.DaysInMonth();[/code]
I did the same thing for parsing a string into a date. I generally use nullable dates, unless Im VERY certain a value will be there, and using TryParse was just kind of clunky. Well, actually I still use it, but I encapsulated it so I dont have to muck
my code up with it everywhere Im parsing strings (which includes user input for nearly every form in my app):
<pre class="prettyprint /// <summary>
/// Parses a string into a DateTime object.
/// Returns null if parse fails.
/// </summary>
/// <param name="source" />
/// <returns>DateTime?</returns>
public static DateTime? ToDate(this string source)
{
DateTime date;
if (DateTime.TryParse(source, out date)) return date;
return null;
}
// To use, either with a string variable or
// FormCollection result:
DateTime? startDate = formCollection["startDate"].ToDate();[/code]
Sorry for the verbosity. Hopefully someone finds my listed extension methods helpful to counterbalance the extra reading. The point is that I hate writing unecessary code, and would like to put together an exception handler that will catch all divide by
zero exceptions and return a zero to the calling method. Thats the kicker there - the return value. Like I said, if possible Id like to avoid calling a method here to do the test, unless someone can list a reason why that would be preferred over handling
the exception and returning a default value. Of course, "Thats not possible" would certainly be a good reason, but Im hoping that it
is possible.
Once upon a time I was hoping to overload the assignment operator (=), so that predefined conversions would take place automatically, and youd think I was insulting peoples lineage. I received a number of responses that had little to nothing to do with
my question, like setting up classes to perform autoconversions (this only works with user-defined objects), and criticisms of trying to use C# as a loosely-typed language. I wasnt - what Id hoped to accomplish was to set up a list of predefined conversions
that would be checked against if an illegal assignment was made. So, if I tried this:
<pre class="prettyprint DateTime? start = formCollection["StartDate"];[/code]
Then I wanted my overload to search through conversion methods Id already written (something like the above for converting from a string to a DateTime?), and automatically execute them. Since that was deemed impossible and possible sacrilegious, I wrote
the extension method instead. I wrote up extension methods to do just about every type of conversion possible during the creation of my current application, and was thinking about how cool it would be to be able to wire these things up in a class library and
add them to projects going forward, so that certain exceptions and conversions were always handled in a specific way.
Anyhow, please jump in with ideas if anyone has them!
View the full article
something global. Take this example:
<pre class="prettyprint double completedOnTime = (double)completedOnTime / completedTotal;[/code]
Theres actually 2 things Id like to do here. One probably isnt possible, and the other isnt looking good, either. First, if I dont cast one of the operands to double, I get a truncated integer (the operands are both integers). Since Im assigning the
division result to a double variable, it certainly would be nice if C# figured out that I wanted a double value from the operation, and not just convert the truncated integer to a double afterwards. I do a lot of programming in ASP.NET MVC with C#, and theres
a lot of programming by convention going on there, and Ill admit its spoiled me a bit. Its "understood" that you mean to do some things by default, so theres no need to spell very obvious things out. I cant think of many instances in which youd want
to assign a truncated integer result to a double variable. But thats a side-rant, and not my question (unless someone knows how to get around this - Im always looking for ways to clean up and minimize my code).
What I really want is to automatically return zero in any case that a divide by zero is encountered. What I do NOT want to do is write a separate try/catch handler for every single place in my app that a percentage is calculated. As I mentioned above, I
could write a utility method and pass all my values through it to calculate percentages, and do the check/return there. That will still require adding references and either instantiating a utility class or calling a static utility method. Sometimes
this is still an ugly solution, like the DaysInMonth method of the DateTime class. I wrote an extension method to get around it, because I found the calls unecessarily verbose.
<pre class="prettyprint // The normal way of calling this method:
DateTime someDate = DateTime.Now;
int daysInMonth = DateTime.DaysInMonth(someDate.Year, someDate.Month);
// My extension method:
/// <summary>
/// Returns an integer of the number of days in the current month.
/// </summary>
/// <param name="source" />DateTime
/// <returns>int</returns>
public static int DaysInMonth(this DateTime source)
{
return DateTime.DaysInMonth(source.Year, source.Month);
}
// Calling the new extension method:
DateTime someDate = DateTime.Now;
int daysInMonth = someDate.DaysInMonth();[/code]
I did the same thing for parsing a string into a date. I generally use nullable dates, unless Im VERY certain a value will be there, and using TryParse was just kind of clunky. Well, actually I still use it, but I encapsulated it so I dont have to muck
my code up with it everywhere Im parsing strings (which includes user input for nearly every form in my app):
<pre class="prettyprint /// <summary>
/// Parses a string into a DateTime object.
/// Returns null if parse fails.
/// </summary>
/// <param name="source" />
/// <returns>DateTime?</returns>
public static DateTime? ToDate(this string source)
{
DateTime date;
if (DateTime.TryParse(source, out date)) return date;
return null;
}
// To use, either with a string variable or
// FormCollection result:
DateTime? startDate = formCollection["startDate"].ToDate();[/code]
Sorry for the verbosity. Hopefully someone finds my listed extension methods helpful to counterbalance the extra reading. The point is that I hate writing unecessary code, and would like to put together an exception handler that will catch all divide by
zero exceptions and return a zero to the calling method. Thats the kicker there - the return value. Like I said, if possible Id like to avoid calling a method here to do the test, unless someone can list a reason why that would be preferred over handling
the exception and returning a default value. Of course, "Thats not possible" would certainly be a good reason, but Im hoping that it
is possible.
Once upon a time I was hoping to overload the assignment operator (=), so that predefined conversions would take place automatically, and youd think I was insulting peoples lineage. I received a number of responses that had little to nothing to do with
my question, like setting up classes to perform autoconversions (this only works with user-defined objects), and criticisms of trying to use C# as a loosely-typed language. I wasnt - what Id hoped to accomplish was to set up a list of predefined conversions
that would be checked against if an illegal assignment was made. So, if I tried this:
<pre class="prettyprint DateTime? start = formCollection["StartDate"];[/code]
Then I wanted my overload to search through conversion methods Id already written (something like the above for converting from a string to a DateTime?), and automatically execute them. Since that was deemed impossible and possible sacrilegious, I wrote
the extension method instead. I wrote up extension methods to do just about every type of conversion possible during the creation of my current application, and was thinking about how cool it would be to be able to wire these things up in a class library and
add them to projects going forward, so that certain exceptions and conversions were always handled in a specific way.
Anyhow, please jump in with ideas if anyone has them!
View the full article