How to Return a Single Value of Unpredictable DataType From a Function

Introduction

In this article I show how to send a single value from a function when you don’t know the exact DataType of that value.

Function1

In the preceding scenario I have a function named "getData" with a parameter named "value" and in this function I am returning various values of various DataTypes on the basis of the parameter value, as in the following:

  1. If value=0 then it returns a DataTable.
  2. If value=1 then it returns an int value.
  3. Else it returns a string value.

Question: So what DataType will you return in this function, DataTable, int or string?

Answer: No one from all of 3. Use the following procedure:

  1. Take an object of the "object" class.
  2. Set each value into that object.
  3. Return that object in the end.
  4. The return type will be of the "object" class.

    Function2

Example:

private object getData(int value)

    {

        object ret; // create a object of object class

 

        if (value == 0)

        {

            String[] arr = new String[] { "Rahul""Bansal" };

            DataTable dt = new DataTable();

            dt.Columns.Add("FirstName");

            dt.Columns.Add("LasttName");

            dt.Rows.Add(arr);

            ret = dt;

        }

        else if (value == 1)

        {

            ret = 1234;

        }

        else 

        {

            ret = "This is  string";

        }

 

        return ret; //return the object

 }

Like in the code above I have a function that returns an object for any kind of value, now I want to call the following function.

object OBJ = new object();         // 1

OBJ = getData(0); // 2

 

        if (OBJ is DataTable) // 3

        {

 

            DataTable dt = (DataTable)OBJ;

            Response.Write(dt.Rows[0][0].ToString());//Output:-Rahul

        }

        else if (OBJ is int) //4

        {

 

            int int_val = (int)OBJ;

            Response.Write(int_val); //Output:-1234

        }

        else if (OBJ is string) //5

        {

 

            string str = (string)OBJ;

            Response.Write(str); //Output:-This is  string

 }

  1. Create the object OBJ of the "object" class.
     
  2. Call the function and set the return value to OBJ.
     
  3. If OBJ is the value of the DataTable type then convert it into a "DataTable" class object and print the value of the first row and the first column.

    Function3

  4. Again if OBJ is the value of an int type then convert it into an "int" variable and print the value of it.

    Function4
     
  5. And finally if OBJ is the value of a string type then convert it into a "string" variable and print the value of it.

    Function5

 


Similar Articles