Generic C# Class: Set "Generic" Property
- by BlaM
I'm quite new to C#, so I might have a problem that C# has a simple solution for. I have a generic class with a property of "generic" type. I want to have a function to set that property, but I need to convert it to do so.
public class BIWebServiceResult<T>
{
public T Data;
public delegate StatusCode StringToStatusCode(string Input);
public void SetData(string Input, StringToStatusCode StringToError)
{
if (StringToError(Input) == 0)
{
if (Data is string[])
{
Data = new string[1];
Data[0] = Input;
}
else if (Data is string)
{
Data = Input;
}
else if (Data is bool)
{
Data = DetectBool(Input);
}
}
}
private bool DetectBool(string Compare)
{
return Compare == "true";
}
}
The problem with that approach is, that it does not work :)
(No that's not all code, just a snippet to show what my problem is)
It doesn't even compile, because "Data = new string[]" can't work if Data is - for example - boolean.
How do I implement a function that behaves differently depending on the type of my generic property?