Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Return multile value from a function using Out keyword

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 174
    Comment on it

     Sometimes we face the situation where we need to return more than one value from the function. But a function never returns more than one value. Here we need to do something different like we create a different function for a different task which returns always one value, but this is a lengthy process.

    So let's try to return more than two value from a function. Suppose we need to check a string, if this string in date format then our function return true and also convert the string in date and return that date.

    So here we are trying to return two value

    • One is bool type (True/False)
    • Second is our Date value


    So we are going to use Out keyword in our function.

    Out Parameter : Reference and Output parameter is a reference of a location in memory of a variable. We pass them in our function as a parameter and set them in function.

    Here is the code :

            private bool TryGetDate(string dateInString, out DateTime dateTime)
            {
                bool isDateValid = false;
                dateTime = DateTime.Now;
                try
                {
                    dateTime = Convert.ToDateTime(dateInString);
                    isDateValid = true;
                }
                catch (Exception ex)
                { }
                return isDateValid;
            }

    In above function, we pass here dateInString variable and check and convert this into the date. If this is incorrect date format then we return true and set its value in our out parameter.

    Let's call the method : -

                string dateString = "2015-16-16 10:10:10.190";
                DateTime dateTime;
                Program program = new Program();
    
                if (program.TryGetDate(dateString, out dateTime))
                    Console.WriteLine("Date successfull convert " + dateTime);
                else
                    Console.WriteLine("Invalid Date " + dateTime);
    
                Console.ReadLine();

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: