Using Generics to return a literal string or from Dictionary<string, object>

Posted by Mike on Stack Overflow See other posts from Stack Overflow or by Mike
Published on 2010-04-22T13:50:42Z Indexed on 2010/04/22 13:53 UTC
Read the original article Hit count: 204

Filed under:
|

I think I outsmarted myself this time. Feel free to edit the title also I could not think of a good one.

I am reading from a file and then in that file will be a string because its like an xml file. But in the file will be a literal value or a "command" to get the value from the workContainer

so

<Email>[email protected]</Email>

or

<Email>[? MyEmail ?]</Email>

What I wanted to do instead of writing ifs all over the place to put it in a generic function

so logic is

If Container command grab from container else grab string and convert to desired type 
Its up to the user to ensure the file is ok and the type is correct 

so another example is

so

<Answer>3</Answer>

or

<Answer>[? NumberOfSales ?]</Answer>

This is the procedure I started to work on

public class WorkContainer:Dictionary<string, object>
{
    public T GetKeyValue<T>(string Parameter) 
    {
        if (Parameter.StartsWith("[? "))
        {
            string key = Parameter.Replace("[? ", "").Replace(" ?]", "");

            if (this.ContainsKey(key))
            {
                return (T)this[key];
            }
            else
            {
                // may throw error for value types
                return default(T);
            }

        }
        else
        {
            // Does not Compile
            if (typeof(T) is string)
            {
                return Parameter
            }
            // OR return (T)Parameter

        }
    }
}

The Call would be

  mail.To = container.GetKeyValue<string>("[email protected]");

or

  mail.To = container.GetKeyValue<string>("[? MyEmail ?]");

  int answer = container.GetKeyValue<int>("3");

or

  answer = container.GetKeyValue<int>("[? NumberOfSales ?]");

But it does not compile?

© Stack Overflow or respective owner

Related posts about c#

Related posts about generics