Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. casting at runtime in c#

casting at runtime in c#

Scheduled Pinned Locked Moved C#
helpcsharp
13 Posts 3 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • P Offline
    P Offline
    prasadbuddhika
    wrote on last edited by
    #1

    hi , I got an object which is a generic, at runtime i pass the type for T and create the proper object. the generic object as follows

    class parent {
    string name;
    T childObject;
    }

    I create the parent in runtime using the reflection , for e.g.

    Type type = x;
    Dynamic response = Activator.CreateInstance(typeof(parent<>).MakeGenericType(type));

    it works fine , but the problem is when I try to assign an object to response.childObject it gives me an exception saying that i'm missing cast and it cannot implicitly cast the object. the object try to assign is also created using reflection, ADDED LATER: I'm not sure this part will be important for this issue , but anyway , the object i'm trying to assign to response.childObject is also an object created by deserialization , means for in order to deserialize this object i have to give the type , so that type also crated using reflection in a similar way described above. i would really appreciate your help on this. thanks in advance.

    S 1 Reply Last reply
    0
    • P prasadbuddhika

      hi , I got an object which is a generic, at runtime i pass the type for T and create the proper object. the generic object as follows

      class parent {
      string name;
      T childObject;
      }

      I create the parent in runtime using the reflection , for e.g.

      Type type = x;
      Dynamic response = Activator.CreateInstance(typeof(parent<>).MakeGenericType(type));

      it works fine , but the problem is when I try to assign an object to response.childObject it gives me an exception saying that i'm missing cast and it cannot implicitly cast the object. the object try to assign is also created using reflection, ADDED LATER: I'm not sure this part will be important for this issue , but anyway , the object i'm trying to assign to response.childObject is also an object created by deserialization , means for in order to deserialize this object i have to give the type , so that type also crated using reflection in a similar way described above. i would really appreciate your help on this. thanks in advance.

      S Offline
      S Offline
      Simon_Whale
      wrote on last edited by
      #2

      I dont know how it actual works if I am honest (as I found the question interesting) but my modifying your code to this

      Type t = typeof(Parent<>);
      int y = 1234;
      Type type = y.GetType();

      dynamic response = Activator.CreateInstance(t.MakeGenericType(type));
      response.MyValue = 123;

      public class Parent
      {
      public string name = string.Empty;
      public T MyValue;
      }

      I was able to assign a value to the property MyValue. *Edit* Not sure if it helps but I've just read through this MSDN article on Type.MakeGenericType[^], I found this an interesting Question :-D

      Lobster Thermidor aux crevettes with a Mornay sauce, served in a Provençale manner with shallots and aubergines, garnished with truffle pate, brandy and a fried egg on top and Spam - Monty Python Spam Sketch

      P 1 Reply Last reply
      0
      • S Simon_Whale

        I dont know how it actual works if I am honest (as I found the question interesting) but my modifying your code to this

        Type t = typeof(Parent<>);
        int y = 1234;
        Type type = y.GetType();

        dynamic response = Activator.CreateInstance(t.MakeGenericType(type));
        response.MyValue = 123;

        public class Parent
        {
        public string name = string.Empty;
        public T MyValue;
        }

        I was able to assign a value to the property MyValue. *Edit* Not sure if it helps but I've just read through this MSDN article on Type.MakeGenericType[^], I found this an interesting Question :-D

        Lobster Thermidor aux crevettes with a Mornay sauce, served in a Provençale manner with shallots and aubergines, garnished with truffle pate, brandy and a fried egg on top and Spam - Monty Python Spam Sketch

        P Offline
        P Offline
        prasadbuddhika
        wrote on last edited by
        #3

        thanks , I also tried the value types and it works , but the problem came when i'm trying to assign reference type.

        S 1 Reply Last reply
        0
        • P prasadbuddhika

          thanks , I also tried the value types and it works , but the problem came when i'm trying to assign reference type.

          S Offline
          S Offline
          Simon_Whale
          wrote on last edited by
          #4

          Type t = typeof(Parent<>);
          Type type = typeof(Data);

          dynamic response = Activator.CreateInstance(t.MakeGenericType(type));
          Data es = new Data() { Name = "Fred", value = 213 };
          response.value = es;

          public class Parent
          {
          public string name = string.Empty;
          public T value;
          }

          public class Data
          {
              public string Name = string.Empty;
              public int value = 0;
          }
          

          I have also tried it with the following and it still works can you expand your problem with some sample code? or a snippet?

          Lobster Thermidor aux crevettes with a Mornay sauce, served in a Provençale manner with shallots and aubergines, garnished with truffle pate, brandy and a fried egg on top and Spam - Monty Python Spam Sketch

          P 1 Reply Last reply
          0
          • P prasadbuddhika

            Thanks again , ok then I think I have to focus on the deserialzed object , unfortunately i haven't got the code snippet right now , but I will definitely post that code snippet soon. thanks .

            S Offline
            S Offline
            Simon_Whale
            wrote on last edited by
            #5

            Your welcome :-D

            Lobster Thermidor aux crevettes with a Mornay sauce, served in a Provençale manner with shallots and aubergines, garnished with truffle pate, brandy and a fried egg on top and Spam - Monty Python Spam Sketch

            P 1 Reply Last reply
            0
            • S Simon_Whale

              Type t = typeof(Parent<>);
              Type type = typeof(Data);

              dynamic response = Activator.CreateInstance(t.MakeGenericType(type));
              Data es = new Data() { Name = "Fred", value = 213 };
              response.value = es;

              public class Parent
              {
              public string name = string.Empty;
              public T value;
              }

              public class Data
              {
                  public string Name = string.Empty;
                  public int value = 0;
              }
              

              I have also tried it with the following and it still works can you expand your problem with some sample code? or a snippet?

              Lobster Thermidor aux crevettes with a Mornay sauce, served in a Provençale manner with shallots and aubergines, garnished with truffle pate, brandy and a fried egg on top and Spam - Monty Python Spam Sketch

              P Offline
              P Offline
              prasadbuddhika
              wrote on last edited by
              #6

              Thanks again , ok then I think I have to focus on the deserialzed object , unfortunately i haven't got the code snippet right now , but I will definitely post that code snippet soon. thanks .

              S 1 Reply Last reply
              0
              • S Simon_Whale

                Your welcome :-D

                Lobster Thermidor aux crevettes with a Mornay sauce, served in a Provençale manner with shallots and aubergines, garnished with truffle pate, brandy and a fried egg on top and Spam - Monty Python Spam Sketch

                P Offline
                P Offline
                prasadbuddhika
                wrote on last edited by
                #7

                hi , this is how i'm doing the deserialization

                Type genericSyncObj = typeof(SyncObject<>);
                Type syncObj = genericSyncObj.MakeGenericType(type);
                IList customObjectList = (IList)Activator.CreateInstance((typeof(List<>).MakeGenericType(type)));

                foreach (string value in pullRequest.Knowledge)
                {
                dynamic syncObject = JasonSerializer.Deserialize(value, syncObj, null);
                customObjectList.Add(syncObject.Object);
                }

                and i'm getting the exception at here

                dynamic responseSync = Activator.CreateInstance(typeof(SyncObject<>).MakeGenericType(type));
                responseSync.Object = customObjectList[y] ;

                thanks .

                S B 2 Replies Last reply
                0
                • P prasadbuddhika

                  hi , this is how i'm doing the deserialization

                  Type genericSyncObj = typeof(SyncObject<>);
                  Type syncObj = genericSyncObj.MakeGenericType(type);
                  IList customObjectList = (IList)Activator.CreateInstance((typeof(List<>).MakeGenericType(type)));

                  foreach (string value in pullRequest.Knowledge)
                  {
                  dynamic syncObject = JasonSerializer.Deserialize(value, syncObj, null);
                  customObjectList.Add(syncObject.Object);
                  }

                  and i'm getting the exception at here

                  dynamic responseSync = Activator.CreateInstance(typeof(SyncObject<>).MakeGenericType(type));
                  responseSync.Object = customObjectList[y] ;

                  thanks .

                  S Offline
                  S Offline
                  Simon_Whale
                  wrote on last edited by
                  #8

                  The problem is that customObject[y] is returned as an object which is why it fails. if you then hard code a cast such as for example.

                  //assume SomeTestClass is the type of class that you are using
                  //Type type = typeof(SomeTestClass);
                  responseSync.Object = (SomeTestClass)customObject[y];

                  it works as you need it to do, but how to create this as a generic routine I'm not sure at the moment as (typeof(SomeTestClass))customObject[y] or even (typeof(SomeTestClass))CustomObject[y] is rejected by the compiler.

                  Lobster Thermidor aux crevettes with a Mornay sauce, served in a Provençale manner with shallots and aubergines, garnished with truffle pate, brandy and a fried egg on top and Spam - Monty Python Spam Sketch

                  P 1 Reply Last reply
                  0
                  • S Simon_Whale

                    The problem is that customObject[y] is returned as an object which is why it fails. if you then hard code a cast such as for example.

                    //assume SomeTestClass is the type of class that you are using
                    //Type type = typeof(SomeTestClass);
                    responseSync.Object = (SomeTestClass)customObject[y];

                    it works as you need it to do, but how to create this as a generic routine I'm not sure at the moment as (typeof(SomeTestClass))customObject[y] or even (typeof(SomeTestClass))CustomObject[y] is rejected by the compiler.

                    Lobster Thermidor aux crevettes with a Mornay sauce, served in a Provençale manner with shallots and aubergines, garnished with truffle pate, brandy and a fried egg on top and Spam - Monty Python Spam Sketch

                    P Offline
                    P Offline
                    prasadbuddhika
                    wrote on last edited by
                    #9

                    thanks , yes this is the place where i'm stuck , need to cast in runtime , if you find a way please share it .

                    S 1 Reply Last reply
                    0
                    • P prasadbuddhika

                      thanks , yes this is the place where i'm stuck , need to cast in runtime , if you find a way please share it .

                      S Offline
                      S Offline
                      Simon_Whale
                      wrote on last edited by
                      #10

                      //Create sample data in the same method as OP
                      IList datalist = (IList)Activator.CreateInstance(typeof(List<>).MakeGenericType(typeof(Data)));

                      datalist.Add(new Data {Name = "SIMON", value = 1});
                      datalist.Add(new Data {Name = "SIMON", value = 2});
                      datalist.Add(new Data {Name = "SIMON", value = 3});

                      //Create the destination object that is declared using
                      //the dynamic keyword
                      Type t = typeof(Parent<>);
                      Type type = typeof(Data);

                      dynamic response = Activator.CreateInstance(t.MakeGenericType(type));

                      //************ possible work around not sure if it would be a correct way
                      //************ but it works.

                      Type SingleRecordType = datalist[0].GetType();
                      dynamic Destination = Activator.CreateInstance(SingleRecordType);
                      Desintation = datalist[0];

                      //Add the record to the response object
                      response.value = Desintation;

                      have a look at this. it is a bit of a work around converting the list item from object to a specific type at runtime. Thanks Simon **edit** missed a GetType()

                      Lobster Thermidor aux crevettes with a Mornay sauce, served in a Provençale manner with shallots and aubergines, garnished with truffle pate, brandy and a fried egg on top and Spam - Monty Python Spam Sketch

                      P 1 Reply Last reply
                      0
                      • P prasadbuddhika

                        hi , this is how i'm doing the deserialization

                        Type genericSyncObj = typeof(SyncObject<>);
                        Type syncObj = genericSyncObj.MakeGenericType(type);
                        IList customObjectList = (IList)Activator.CreateInstance((typeof(List<>).MakeGenericType(type)));

                        foreach (string value in pullRequest.Knowledge)
                        {
                        dynamic syncObject = JasonSerializer.Deserialize(value, syncObj, null);
                        customObjectList.Add(syncObject.Object);
                        }

                        and i'm getting the exception at here

                        dynamic responseSync = Activator.CreateInstance(typeof(SyncObject<>).MakeGenericType(type));
                        responseSync.Object = customObjectList[y] ;

                        thanks .

                        B Offline
                        B Offline
                        BobJanova
                        wrote on last edited by
                        #11

                        If you're getting a runtime exception, then it's probably because the object actually isn't of the right type. The exception message should tell you what it is and what it's trying to cast it to.

                        P 1 Reply Last reply
                        0
                        • S Simon_Whale

                          //Create sample data in the same method as OP
                          IList datalist = (IList)Activator.CreateInstance(typeof(List<>).MakeGenericType(typeof(Data)));

                          datalist.Add(new Data {Name = "SIMON", value = 1});
                          datalist.Add(new Data {Name = "SIMON", value = 2});
                          datalist.Add(new Data {Name = "SIMON", value = 3});

                          //Create the destination object that is declared using
                          //the dynamic keyword
                          Type t = typeof(Parent<>);
                          Type type = typeof(Data);

                          dynamic response = Activator.CreateInstance(t.MakeGenericType(type));

                          //************ possible work around not sure if it would be a correct way
                          //************ but it works.

                          Type SingleRecordType = datalist[0].GetType();
                          dynamic Destination = Activator.CreateInstance(SingleRecordType);
                          Desintation = datalist[0];

                          //Add the record to the response object
                          response.value = Desintation;

                          have a look at this. it is a bit of a work around converting the list item from object to a specific type at runtime. Thanks Simon **edit** missed a GetType()

                          Lobster Thermidor aux crevettes with a Mornay sauce, served in a Provençale manner with shallots and aubergines, garnished with truffle pate, brandy and a fried egg on top and Spam - Monty Python Spam Sketch

                          P Offline
                          P Offline
                          prasadbuddhika
                          wrote on last edited by
                          #12

                          hi thanks it seems to be working, though it is a workaround . thanks for the clue . ** yes i noticed that and i fixed it by calling the GetType() thanks.

                          1 Reply Last reply
                          0
                          • B BobJanova

                            If you're getting a runtime exception, then it's probably because the object actually isn't of the right type. The exception message should tell you what it is and what it's trying to cast it to.

                            P Offline
                            P Offline
                            prasadbuddhika
                            wrote on last edited by
                            #13

                            hi , yes , that's the case , I was searching for a way to solve this at runtime. anyway I got a clue a from Simon_Whale. thanks.

                            1 Reply Last reply
                            0
                            Reply
                            • Reply as topic
                            Log in to reply
                            • Oldest to Newest
                            • Newest to Oldest
                            • Most Votes


                            • Login

                            • Don't have an account? Register

                            • Login or register to search.
                            • First post
                              Last post
                            0
                            • Categories
                            • Recent
                            • Tags
                            • Popular
                            • World
                            • Users
                            • Groups