Thursday, November 14, 2013

C# multiple value return from single function

There are a number of ways to return two object from one function. You can class or structure and another one as out parameter. Alternatively, you can use generic type with two members. Such type, in particular, it Tuple:

#I am using Tuple to returns 2 datetime value(fromDate , toDate )
  public Tuple GetDates()
   {

          DateTime fromDate = DateTime.Now;
          DateTime toDate = DateTime.Now;
          int year = Convert.ToInt32(this.ddlQYear.SelectedItem.Value);

            if (Convert.ToInt32(ddlQ.SelectedItem.Value) > 0)
            {
                int month = Convert.ToInt32(ddlQ.SelectedItem.Value);
                fromDate = new DateTime(year, month, 1);
                if (month == 12)
                    toDate = new DateTime(year + 1, 1, 1);
                else
                    toDate = new DateTime(year, month + 1, 1);
            }
            return new Tuple(fromDate, toDate);
   }
===========Call this function bellow way==============================
            
DateTime fromDate = GetDates().Item1;
DateTime toDate = GetDates().Item2;


#Another way use "out" keyword:

 public static int GetDates(out DateTime FDate, out DateTime TDate)
   {
            DateTime fromDate = DateTime.Now;
            DateTime toDate = DateTime.Now;

           // Calculate your date

            FDate=fromDate ;
            TDate=toDate
     

         return 1;
   }
Hope that this helps!!

No comments:

Post a Comment