Creating a dynamic array...

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Matthew Wells

    Creating a dynamic array...

    Hello.

    I have figured out how to create an instance of an object only knowing the
    type by string.

    string sName = "MyClassNam e";
    Type t = Type.GetType(sN ame);
    Object objNew = Activator.Creat eInstance(t);

    This works, but now I need to declare an array like

    Object[] objNew = Activator.Creat eInstance(t)[0];

    This doesn't work. Can anyone help?

    Thanks.

    Matthew Wells
    Matthew.Wells@F irstByte.net


  • Jason Newell

    #2
    Re: Creating a dynamic array...

    Matt,

    I believe this is what you're looking for.

    Array array = Array.CreateIns tance(type, length);

    Jason Newell
    Software Engineer


    Matthew Wells wrote:
    Hello.
    >
    I have figured out how to create an instance of an object only knowing the
    type by string.
    >
    string sName = "MyClassNam e";
    Type t = Type.GetType(sN ame);
    Object objNew = Activator.Creat eInstance(t);
    >
    This works, but now I need to declare an array like
    >
    Object[] objNew = Activator.Creat eInstance(t)[0];
    >
    This doesn't work. Can anyone help?
    >
    Thanks.
    >
    Matthew Wells
    Matthew.Wells@F irstByte.net
    >
    >

    Comment

    • Matthew Wells

      #3
      Re: Creating a dynamic array...

      Not quite. This still returns an Array type, not an Object type. . I need
      to have the equivalent of these statements as if I knew what type I had to
      start with.

      public MyClass Person
      {
      string Name;
      }

      Person[] = new Person[2];

      The problem is I don't know what type I will need. The code you gave
      returns an error when I try to assign a "person" to an elememt in the
      array. - "Can't apply indexing with [] to an expression of type
      'System.Array'" I can't cast it because I don't know what type it is.

      This is definitely towards the goal. Any more ideas?


      "Jason Newell" <nospam@nospam. comwrote in message
      news:%2361se3n6 HHA.1900@TK2MSF TNGP02.phx.gbl. ..
      Matt,
      >
      I believe this is what you're looking for.
      >
      Array array = Array.CreateIns tance(type, length);
      >
      Jason Newell
      Software Engineer

      >
      Matthew Wells wrote:
      >Hello.
      >>
      >I have figured out how to create an instance of an object only knowing
      >the type by string.
      >>
      >string sName = "MyClassNam e";
      >Type t = Type.GetType(sN ame);
      >Object objNew = Activator.Creat eInstance(t);
      >>
      >This works, but now I need to declare an array like
      >>
      >Object[] objNew = Activator.Creat eInstance(t)[0];
      >>
      >This doesn't work. Can anyone help?
      >>
      >Thanks.
      >>
      >Matthew Wells
      >Matthew.Wells@F irstByte.net
      >>

      Comment

      • Marc Gravell

        #4
        Re: Creating a dynamic array...

        Hang on - originally you said you only knew the type as a string; you
        will struggle to get much better than Array in this case (note that
        Array has GetValue() and SetValue() to work in this case).

        Another option might involve generics.

        You can get a Type from a string using a few tricks;
        Type.GetType(na me) sometimes works, but it depends on where the class
        is... you may need to enumerate a little...

        From a Type, you can call a generic method using MakeGenericMeth od().

        Something like:

        class Person { }
        static class Program {
        static void Main() {
        Person[] typed = SomeMethod<Pers on>();
        Person p1 = typed[3];

        Type t = Type.GetType("P erson");
        Array untyped = (Array)
        typeof(Program) .GetMethod("Som eMethod").MakeG enericMethod(t) .Invoke(null,
        null);
        Person p2 = (Person) untyped.GetValu e(3);
        }
        public static T[] SomeMethod<T>() where T : class, new() {
        T[] data = new T[10];
        for (int i = 0; i < 10; i++) {
        data[i] = new T();
        }
        return data;
        }
        }


        Comment

        • Jason Newell

          #5
          Re: Creating a dynamic array...

          Matt,

          Have a look at this approach then.

          ArrayList arrayList = new ArrayList();
          arrayList.Add(1 );
          arrayList.Add(5 .3);
          arrayList.Add(t rue);
          arrayList.Add(" Hello World");
          object[] array = arrayList.ToArr ay();

          Jason Newell
          Software Engineer


          Matthew Wells wrote:
          Not quite. This still returns an Array type, not an Object type. . I need
          to have the equivalent of these statements as if I knew what type I had to
          start with.
          >
          public MyClass Person
          {
          string Name;
          }
          >
          Person[] = new Person[2];
          >
          The problem is I don't know what type I will need. The code you gave
          returns an error when I try to assign a "person" to an elememt in the
          array. - "Can't apply indexing with [] to an expression of type
          'System.Array'" I can't cast it because I don't know what type it is.
          >
          This is definitely towards the goal. Any more ideas?
          >
          >
          "Jason Newell" <nospam@nospam. comwrote in message
          news:%2361se3n6 HHA.1900@TK2MSF TNGP02.phx.gbl. ..
          >Matt,
          >>
          >I believe this is what you're looking for.
          >>
          >Array array = Array.CreateIns tance(type, length);
          >>
          >Jason Newell
          >Software Engineer
          >www.jasonnewell.net
          >>
          >Matthew Wells wrote:
          >>Hello.
          >>>
          >>I have figured out how to create an instance of an object only knowing
          >>the type by string.
          >>>
          >>string sName = "MyClassNam e";
          >>Type t = Type.GetType(sN ame);
          >>Object objNew = Activator.Creat eInstance(t);
          >>>
          >>This works, but now I need to declare an array like
          >>>
          >>Object[] objNew = Activator.Creat eInstance(t)[0];
          >>>
          >>This doesn't work. Can anyone help?
          >>>
          >>Thanks.
          >>>
          >>Matthew Wells
          >>Matthew.Wells@F irstByte.net
          >>>
          >

          Comment

          • Jon Skeet [C# MVP]

            #6
            Re: Creating a dynamic array...

            On Aug 30, 4:31 pm, "Matthew Wells" <Matthew.We...@ FirstByte.net>
            wrote:

            <snip>
            I don't think this works because 't' is not strongly typed.
            >
            Why is this so difficult?
            Because the type information is largely there for the *compiler*.
            You're trying to provide it at runtime.

            Could you try to explain *why* you believe you need this? There's
            almost certainly a better approach to the problem.

            Jon

            Comment

            • Marc Gravell

              #7
              Re: Creating a dynamic array...

              and I don't think generics are
              an option because I am also getting the type dynamically.
              Except of course that this is in response to a post that does
              *precisely* this.

              Marc



              Comment

              • Jon Skeet [C# MVP]

                #8
                Re: Creating a dynamic array...

                Matthew Wells <Matthew.Wells@ FirstByte.netwr ote:
                I did find a way.
                Yes, involving this:

                Type t = Type.GetType(sM yType + "[]");

                and then using Activator.Creat eInstance.

                However, Array.CreateIns tance had previously been suggested, and I
                believe that would solve your problem more simply. What does it not do
                that you needed it to do?

                --
                Jon Skeet - <skeet@pobox.co m>
                http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
                If replying to the group, please do not mail me too

                Comment

                • Matthew Wells

                  #9
                  Re: Creating a dynamic array...

                  I did say that's what I'm using (this is a little corrected from my last
                  post - I checked the actual line)

                  Object objList = Activator.Creat eInstance(t, new Object[1] {5}); \\ for five
                  elements

                  You'll notice that I'm now using the signature for CreatteInstance that is
                  needed for an array of type t.

                  But like I said before, if you use this, you can't assign a value to an
                  element of the array like:

                  objList[0] = 2;

                  You'll get an error. You have to declare another array, cast it, and then
                  assign this array to that.

                  Object[] ObjListNew = (Object[])objList;

                  After you're done using ObjListNew, you can jsut refer to the original
                  objList since they refer to the same object.

                  Nice and neat.


                  "Jon Skeet [C# MVP]" <skeet@pobox.co mwrote in message
                  news:MPG.2143b7 b3cc5b77b042b@m snews.microsoft .com...
                  Matthew Wells <Matthew.Wells@ FirstByte.netwr ote:
                  >I did find a way.
                  >
                  Yes, involving this:
                  >
                  Type t = Type.GetType(sM yType + "[]");
                  >
                  and then using Activator.Creat eInstance.
                  >
                  However, Array.CreateIns tance had previously been suggested, and I
                  believe that would solve your problem more simply. What does it not do
                  that you needed it to do?
                  >
                  --
                  Jon Skeet - <skeet@pobox.co m>
                  http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
                  If replying to the group, please do not mail me too

                  Comment

                  • Jon Skeet [C# MVP]

                    #10
                    Re: Creating a dynamic array...

                    Matthew Wells <Matthew.Wells@ FirstByte.netwr ote:
                    I did say that's what I'm using (this is a little corrected from my last
                    post - I checked the actual line)
                    >
                    Object objList = Activator.Creat eInstance(t, new Object[1] {5}); \\ for five
                    elements
                    >
                    You'll notice that I'm now using the signature for CreatteInstance that is
                    needed for an array of type t.
                    But you're still using *Activator*.Cre ateInstance rather than
                    *Array*.CreateI nstance.

                    The call to Array.CreateIns tance is simpler and more obviously
                    understandable, IMO.
                    But like I said before, if you use this, you can't assign a value to an
                    element of the array like:
                    >
                    objList[0] = 2;
                    >
                    You'll get an error. You have to declare another array, cast it, and then
                    assign this array to that.
                    >
                    Object[] ObjListNew = (Object[])objList;
                    >
                    After you're done using ObjListNew, you can jsut refer to the original
                    objList since they refer to the same object.
                    >
                    Nice and neat.
                    All of that is still true with Array.CreateIns tance, but you don't have
                    to go through as many hoops.

                    --
                    Jon Skeet - <skeet@pobox.co m>
                    http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
                    If replying to the group, please do not mail me too

                    Comment

                    • Matthew Wells

                      #11
                      Re: Creating a dynamic array...

                      I am creating an array of a specific type. If I use Array.CreateIns tance
                      and then try to assign as Object into an element I get

                      Error 2 Cannot apply indexing with [] to an expression of type
                      'System.Array'

                      Remember that I still can't cast becaue I don't know the type ahead of time.

                      You would think that the array is of type t becaust that's what it is
                      supposed to do. I believe that Array.CreateIns tance is creating a generic
                      Array that can hold the type t, not creating an array of t types. I'm open
                      to suggestions.



                      "Jon Skeet [C# MVP]" <skeet@pobox.co mwrote in message
                      news:MPG.2143e5 9bc1f7b1b42f@ms news.microsoft. com...
                      Matthew Wells <Matthew.Wells@ FirstByte.netwr ote:
                      >I did say that's what I'm using (this is a little corrected from my last
                      >post - I checked the actual line)
                      >>
                      >Object objList = Activator.Creat eInstance(t, new Object[1] {5}); \\ for
                      >five
                      >elements
                      >>
                      >You'll notice that I'm now using the signature for CreatteInstance that
                      >is
                      >needed for an array of type t.
                      >
                      But you're still using *Activator*.Cre ateInstance rather than
                      *Array*.CreateI nstance.
                      >
                      The call to Array.CreateIns tance is simpler and more obviously
                      understandable, IMO.
                      >
                      >But like I said before, if you use this, you can't assign a value to an
                      >element of the array like:
                      >>
                      >objList[0] = 2;
                      >>
                      >You'll get an error. You have to declare another array, cast it, and
                      >then
                      >assign this array to that.
                      >>
                      >Object[] ObjListNew = (Object[])objList;
                      >>
                      >After you're done using ObjListNew, you can jsut refer to the original
                      >objList since they refer to the same object.
                      >>
                      >Nice and neat.
                      >
                      All of that is still true with Array.CreateIns tance, but you don't have
                      to go through as many hoops.
                      >
                      --
                      Jon Skeet - <skeet@pobox.co m>
                      http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
                      If replying to the group, please do not mail me too

                      Comment

                      • Jon Skeet [C# MVP]

                        #12
                        Re: Creating a dynamic array...

                        Matthew Wells <Matthew.Wells@ FirstByte.netwr ote:
                        I am creating an array of a specific type. If I use Array.CreateIns tance
                        and then try to assign as Object into an element I get
                        >
                        Error 2 Cannot apply indexing with [] to an expression of type
                        'System.Array'
                        >
                        Remember that I still can't cast becaue I don't know the type ahead of time.
                        >
                        You would think that the array is of type t becaust that's what it is
                        supposed to do. I believe that Array.CreateIns tance is creating a generic
                        Array that can hold the type t, not creating an array of t types. I'm open
                        to suggestions.
                        I'm not suggesting you remove *all* your code and replace it with a
                        call to Array.CreateIns tance - just the bit that's calling
                        Activator.Creat eInstance.

                        Activator.Creat eInstance is declared to return Object, so you're
                        already having to cope with that - just cope with Array.CreateIns tance
                        returning Array in exactly the same way. Cast it to object[] (for
                        reference types - that won't work for value type arrays) or whatever
                        you currently do.

                        Note that if you *just* need indexing, you can do:

                        IList array = Array.CreateIns tance(...);

                        IList provides an indexer.

                        --
                        Jon Skeet - <skeet@pobox.co m>
                        http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
                        If replying to the group, please do not mail me too

                        Comment

                        Working...