Reputation: 7438
In the following method, parameters fromDate and toDate's value are never used because they are overwritten in the body before being read.
static void GetDatesFromMonth(string month, ref DateTime fromDate, ref DateTime toDate)
{
DateTime userDateTime = TimeHelper.getUserGMTNow();
DateTime calculatedDate = Convert.ToDateTime(month + " 01," + userDateTime.Year);
toDate = calculatedDate.AddMonths(1).AddSeconds(-1);
fromDate = toDate.AddMonths(-12).AddSeconds(1);
}
I am using this code at many places in my class file.
When I run Resharper on my code it shows this message and unlike all its other suggessions it is not able to correct this code block
can anybody help me to rewrite this method with good coding practice.
Upvotes: 4
Views: 3384
Reputation: 42991
Alternatively since out parameters are generally a code smell you may want to rewrite your method as something like:
static Tuple<DateTime, DateTime> GetDatesFromMonth(string month)
{
...
}
or
static ToFromDates GetDatesFromMonth(string month)
{
...
}
with
class ToFromDates
{
public DateTime To{get;set;}
public DateTime From{get;set;}
}
You could also create an extension method
static class DateExtensions
{
public static Tuple<DateTime, DateTime> GetDatesFromMonth(this string month)
{
...
}
}
and use this in your code like this
var dates = "January".GetDatesFromMonth();
Upvotes: 8
Reputation: 216293
Change the two date parameters to out
static void GetDatesFromMonth(string month, out DateTime fromDate, out DateTime toDate)
See here for a clarification on out vs ref
Simply, you use out when your method need to return two or more values, the out means 'I will set this values before exiting'. On the contrary ref is more complicated. It means 'I need this values/objects inside this method and I will change them before exit'
Upvotes: 13
Reputation: 25742
Simply use out
in place of ref
. It will show your intentions (that parameters will be out parameters) and it will also indicate that initial values of those parameters are irrelevant. That should also fix R# warning. If you use ref
, R# expects you to use the parameter values before any overwrite.
Upvotes: 2