I have been struggling with this issue for a while and I am not sure if it's even possible to deal without some magic. I have a class container that takes generics and stores them and might use other procedures. However, I struggle to extend my ToString() function that should take the generic elements and printing them if they are themselves a collection.
Here is my MCE:
namespace MyNamespace
{
public class Container<T>
{
public T value1;
public T value2;
public Container()
{
value1 = default;
value2 = default;
}
public Container(T firstValue, T secondValue)
{
value1 = firstValue;
value2 = secondValue;
}
...
public override string ToString()
{
// Check if the type is a collection/enumerable and attempt to convert the elements of that collectiont/enumerable to String.
if (typeof(T).GetInterface(nameof(IEnumerable<T>)) != null)
{
return string.Join(", ", value1) +"; " + string.Join(", ", value2); // THIS IS THE PROBLEM
}
// This part works
return value1.ToString() + ", " + value2.ToString();
}
}
}
This manages to work when the generic is a basic datatype (int, float, uint, etc) but giving it a collection will just give back the collection's name. This is weird because extracting said collection from my class and using the same method does actually work as intended.
Container<uint[]> exampleContainer = new Container<uint[]>(new uint[4] { 0, 1, 2, 3 }, new uint[4] { 4, 5, 6, 7 });
Console.WriteLine("This doesn't work " + exampleContainer.ToString()); // This doesn't work System.UInt32[]; System.UInt32[]
Console.WriteLine("But this does " + string.Join(", ", exampleContainer.value1) + " " + string.Join(", ", exampleContainer.value2)); // But this does 0, 1, 2, 3 4, 5, 6, 7
Is there something I am missing here?
Note: I am using .Net framework but I am curious of how this applies to a general C# case