So I'm trying to write a C# function print_r() that prints out information about a value passed much in the same way that the PHP print_r() function works.
What I'm doing is taking in an object as an input in to the function, and depending on what type it is, I'll output the value, or loop through an array and print out the values inside the array. I have no problem printing out basic values, but when I try to loop through the object if I detect it is an array, I get an error from C# saying "Error 1 foreach statement cannot operate on variables of type 'object' because 'object' does not contain a public definition for 'GetEnumerator'".
Now I'm assuming this is just because object doesn't implement IEnumerable<>, but is there any way that I can process this taking in the input as type object?
This is my current code for the function (the IEnumerable<> part is blank in terms of content, but this is the code that is giving me an error.
Thanks.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Reflection;
namespace ConsoleApplication1
{
class Program
{
static void print_r(object val)
{
if (val.GetType() == typeof(string))
{
Console.Write(val);
return;
}
else if (val.GetType().GetInterface(typeof(IEnumerable).FullName) != null)
{
foreach (object i in val)
{
// Process val as array
}
}
else
{
Console.Write(val);
return;
}
}
static void Main(string[] args)
{
int[] x = { 1, 4, 5, 6, 7, 8 };
print_r(x);
Console.Read();
}
}
}