Search code examples
c#syndicationsyndication-feedsyndication-item

Return T where are different return types


I have different return types so I can't decide what to use for that. I was thinking something like that below, but if you have other ideas I am open for that.

public T GetValue<T>(ContentType type)
{
    foreach (SyndicationItem item in feed.Items)
    {
        switch (type)
        {
            case ContentType.BaseUri:
                return item.BaseUri;
                break;
            case ContentType.Categories:
                return item.Categories;
                break;
            case ContentType.Content:
                return item.Content;
                break;
            case ContentType.Contributors:
                return item.Contributors;
                break;
            case ContentType.Copyright:
                return item.Copyright;
                break;
          }
     }
}

public enum ContentType
{
    BaseUri,
    Categories,
    Content,
    Contributors,
    Copyright
}

I would like to decide what type I want to return so It matches, otherwise it would drop an compile time error.


Solution

  • I don't get the point of putting the switch case in a for loop. you will exit the loop the first time one of the cases of your switch is true.
    But to handle the problem on uncertainty about the return type, in case you know that the return type would be a reference type, then you can do this too:

    You can set the return type to object and then the caller has to do a casting:

    public object GetValue(ContentType type)
    {
        switch (type)
        {
            case ContentType.BaseUri:
                return item.BaseUri;
                break;
            case ContentType.Categories:
                return item.Categories;
                break;
            case ContentType.Content:
                return item.Content;
                break;
            case ContentType.Contributors:
                return item.Contributors;
                break;
            case ContentType.Copyright:
                return item.Copyright;
                break;
          }
    }
    

    caller:

    public void Caller() 
    {
        object x = GetValue();
        if ( x.GetType() == typeof(BaseUri) ) // I assume that BaseUri is also a class name
        {
            BaseUri baseUri = (BaseUri)x;
            // now you can use baseUri to initialize another variable in outer scopes ... or use it as a parameter to some method or ...
        }
        else if(x.GetType() == typeof(Category))
        {
            // the same logic of casting and using goes here too ...
        }
    }