Generic C# Class: Set "Generic" Property

Posted by BlaM on Stack Overflow See other posts from Stack Overflow or by BlaM
Published on 2010-06-11T17:44:53Z Indexed on 2010/06/11 17:52 UTC
Read the original article Hit count: 317

Filed under:
|
|

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?

© Stack Overflow or respective owner

Related posts about c#

Related posts about datatypes