2

I have the following problem. I have an Enum which defines types of possible objects whom all (the objects) inherits from a base class. Now, I know the type of the object I would like to create.

However, I would like to prevent code duplicity. So in order to do so, I wanted to do the following:

Type myType = null;
string myParemeters = "json valid value" // the value to deserialize from
switch (enumType)
{
    case EnumType.X:
        myType = typeof(X);                    
        break;
    case EnumType.Y:
        myType = typeof(Y);                    
        break;
}
if (myType != null)
{
    myRequest = JsonConvert.DeserializeObject<myType>(myParameters);
}

while myRequest is an object which can be X, Y or any other value listed in the Enum (because they are all inherit from a base class).

However, it can't be compiled since I get the following error:

The type or namespace name 'myType' could not be found (are you missing a using directive or an assembly reference?)

My solution now is to create the instance in every case.. but I really don't want to do it.

Does anybody know how this problem can be solved?

John Saunders
  • 160,644
  • 26
  • 247
  • 397
Gilad
  • 43
  • 8
  • I have edited your title. Please see, "[Should questions include “tags” in their titles?](http://meta.stackexchange.com/questions/19190/)", where the consensus is "no, they should not". – John Saunders Dec 30 '13 at 14:24

1 Answers1

0

Try this

JsonConvert.DeserializeObject("somejson", myType);

To understand why you cannot pass a type as a generic parameter in the way you are doing, please see this link:

c-sharp-use-system-type-as-generic-parameter

I used this code to test it:

    class TypeA : BaseClass {}

    class TypeB : BaseClass {}

    class BaseClass
    {
        public string Name { get; set; }
    }

    public enum Test
    {
        A = 0,
        B
    }

    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    static void Main()
    {
        const Test enumType = Test.A;
        Type myType = null;

        switch (enumType)
        {
            case Test.A:
                myType = typeof(TypeA);                    
                break;
            case Test.B:
                myType = typeof(TypeB);                    
                break;
        }

        var result = JsonConvert.DeserializeObject("{ 'Name': 'test' }", myType);
  • apologies, I mis-read your original problem. Have replicated your code and realized your issue.
Community
  • 1
  • 1
Applejack
  • 1
  • 1
  • Thanks for your answer. I'll try your solution. However, I return the request from this function.. I think I have a compilation error. I'll try to solve it and let you know if it solved my problem. Thanks! – Gilad Dec 30 '13 at 12:49
  • No problem, hope it helps! – Applejack Dec 30 '13 at 13:25