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.
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:
- If value=0 then it returns a DataTable.
- If value=1 then it returns an int value.
- 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:
- Take an object of the "object" class.
- Set each value into that object.
- Return that object in the end.
- The return type will be of the "object" class.
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
}
- Create the object OBJ of the "object" class.
- Call the function and set the return value to OBJ.
- 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.
- Again if OBJ is the value of an int type then convert it into an "int" variable and print the value of it.
- And finally if OBJ is the value of a string type then convert it into a "string" variable and print the value of it.