How to use single object instance for class to set the multiple member value?

Curretly i am using below code to set the DateRanges Class member variables.

       DateRanges DateRanges1 = new DateRanges();
       DateRanges DateRanges2 = new DateRanges();
       DateRanges DateRanges3 = new DateRanges();

        DateRanges1.Label = "Last Week";
        DateRanges1.Range = Lastweek;
        this.dateRange.Ranges.Add(DateRanges1);
        DateRanges2.Label = "Last 1 Month";
        DateRanges2.Range = Lastmonth;
        this.dateRange.Ranges.Add(DateRanges2);
        DateRanges3.Label = "Last 2 Months";
        DateRanges3.Range = Last2month;
        this.dateRange.Ranges.Add(DateRanges3);

I want to reduce the code in this. is there any way to do this.

Here DateRanges, class that have label(string type), ranges(object) members. this.daterange.ranges is my custom component property. Thanks for any help.

Jon Skeet
people
quotationmark

To make this code cleaner, I'd suggest:

  • Renaming Lastmonth etc to follow .NET naming conventions
  • Not bothering with any separate variables (but if you do, make them follow .NET naming conventions too)
  • Renaming DateRanges to DateRange (as it only appears to be a single date range)
  • Creating a constructor for DateRange accepting the range and the label

You can then have:

dateRange.Ranges.Add(new DateRange(LastWeek, "Last Week"));
dateRange.Ranges.Add(new DateRange(LastMonth, "Last 1 Month"));
dateRange.Ranges.Add(new DateRange(Last2Months, "Last 2 Months"));

Or possibly (depending on the type of Ranges):

// Here AddRange would be expected to accept IEnumerable<DateRange>
dateRange.Ranges.AddRange(new[] {
    new DateRange(LastWeek, "Last Week"),
    new DateRange(LastMonth, "Last 1 Month"),
    new DateRange(Last2Months, "Last 2 Months")
});

Both of those are considerably cleaner IMO than using an object initializer and an unconventional local variable name.

If you're doing this around the same code you're initializing dateRanges, you could just use:

dateRanges = new FooBar // Whatever the type actually is
{
    // Other properties as well
    Ranges =
    {
        new DateRange(LastWeek, "Last Week"),
        new DateRange(LastMonth, "Last 1 Month"),
        new DateRange(Last2Months, "Last 2 Months")
    }
};

people

See more on this question at Stackoverflow