3

I created an object array with different types of elements in them:

public static int a;
public static string b;
public static ushort c;

object[] myobj = new obj[]{ a, b, c};

If I want to create an array that contains elements of arrays of this myobj type, how would I do it?

I mean something like this:

myobj[] myarray = new myobj[];  <= but to do this, myobj should be a type. 

Not sure how to work it out.

Thanks everyone.

Chris Schiffhauer
  • 17,102
  • 15
  • 79
  • 88
Vikyboss
  • 940
  • 2
  • 11
  • 23

4 Answers4

9

Create a type containing the types you want and make an array of those.

public class MyType // can be a struct. Depends on usage.
{
  // should really use properties, I know, 
  // and these should probably not be static
  public static int a;
  public static string b;
  public static ushort c;
}

// elsewhere
MyType[] myobj = new MyType[]{};

Not sure why you would want to jump through hoops with object[] and having to cast all over the place.

Oded
  • 489,969
  • 99
  • 883
  • 1,009
  • You beat me to it by a fraction of a second ;) +1 – BenAlabaster Jul 20 '11 at 19:50
  • I am guessing that this members shouldn't be static anyway :) – Yiğit Yener Jul 20 '11 at 19:51
  • @Yiğit Yener - Agreed, but I have taken the code from the OP, perhaps this is intentional... – Oded Jul 20 '11 at 19:52
  • Yeah, that is a nice way to do it. I already discussed in StackOverflow and found that I can't access the fields of class like an array. What I gave here is short form of it. And people in last discussion suggested to use array so can access the fields of classes with indexes. – Vikyboss Jul 20 '11 at 19:56
  • http://stackoverflow.com/questions/6750265/how-to-access-members-of-an-struct-like-an-array-in-c – Vikyboss Jul 20 '11 at 19:57
  • @Vikyboss - It is better to use properties on a type you create. – Oded Jul 20 '11 at 19:59
  • Sorry, could you say more on that? Thanks – Vikyboss Jul 20 '11 at 20:00
  • @Vikyboss - What exactly do you want to know? – Oded Jul 20 '11 at 20:01
  • The reason I used object[] is to group different types of elements. – Vikyboss Jul 20 '11 at 20:02
  • @Vikyboss - That's practically the definition of a struct. – Oded Jul 20 '11 at 20:03
  • I'm trying to port c to c#. And I need to pass a struct or class like the one you gave into a function and access the fields of that class like an array with index. But someone in my last discussion it's not doable. – Vikyboss Jul 20 '11 at 20:04
  • @Vikyboss - Sounds like you need to ask a new question, including _all_ and _as much_ detail as possible regarding what you are trying to do and what you have tried. – Oded Jul 20 '11 at 20:06
  • I did already here : http://stackoverflow.com/questions/6750265/how-to-access-members-of-an-struct-like-an-array-in-c But people suggested to not use struct and use array, thats why I asked this question with array. – Vikyboss Jul 20 '11 at 20:07
5

How about we use a Dictionary to store any types you need?

So, while you will not exactly have myType.a, you can have myType.Values["a"], which is close enough, makes use of standard C# constructs, and gives you lots of flexibility/maintainability

public class MyType
{
    public MyType()
    {
        this.Values = new Dictionary<object, object>();
    }

    public Dictionary<object, object> Values
    {
        get;
        set;
    }
}

And sample usage:

using System;
using System.Collections.Generic;

public static class Program
{
    [STAThread]
    private static void Main()
    {
        var myTypes = new MyType[3];

        myTypes[0] = new MyType();
        myTypes[1] = new MyType();
        myTypes[2] = new MyType();

        for (var current = 0; current < myTypes.Length; ++current)
        {
            // here you customize what goes where
            myTypes[current].Values.Add("a", current);
            myTypes[current].Values.Add("b", "myBvalue");
            myTypes[current].Values.Add("c", (ushort)current);
        }

        foreach (var current in myTypes)
        {
            Console.WriteLine(
               string.Format("A={0}, B={1}, C={2}", 
                              current.Values["a"], 
                              current.Values["b"],
                              current.Values["c"]));
        }

 }

Plus, if you want, you can easily add an indexer property to your class, so you can access elements with the syntax myType["a"]. Notice that you should add error checking when adding or retrieving values.

public object this[object index]
{
    get
    {
        return this.Values[index];
    }

    set
    {                    
        this.Values[index] = value;
    }
}

And here's a sample using indexer. Increment the entries by '1' so we see a difference in the ouptut:

for (var current = 0; current < myTypes.Length; ++current)
{
    myTypes[current]["a"] = current + 1;
    myTypes[current]["b"] = "myBvalue2";
    myTypes[current]["c"] = (ushort)(current + 1);
}

foreach (var current in myTypes)
{
    Console.WriteLine(string.Format("A={0}, B={1}, C={2}", 
                                    current["a"], 
                                    current["b"], 
                                    current["c"]));
}
Gustavo Mori
  • 8,319
  • 3
  • 38
  • 52
  • Wow, thanks a lot. Let me try that will reply if that works in mine, but by looking at it it should definitely work. Thanks for ur tremendous help. Much appreciated. Will soon try and mark as an answer. :) – Vikyboss Jul 20 '11 at 20:52
  • 1
    No problem. Added the indexer. Hope it helps. – Gustavo Mori Jul 20 '11 at 21:00
  • Thanks again. I used this but modified a little bit to suit the exact requirement. Thank you very much! :) – Vikyboss Jul 21 '11 at 13:31
  • I also tried doing this with list and got another answer, just letting you know. http://stackoverflow.com/questions/6777699/how-to-update-a-field-of-a-class-when-a-list-of-the-class-gets-modified-in-c. – Vikyboss Jul 21 '11 at 14:54
  • Glad it worked. As for the `List`, while the solution provided was good for that question, I shudder at the thought of doing it that way :) – Gustavo Mori Jul 21 '11 at 17:30
1

I made a couple of changes, but I think this would be in the spirit of what you want to do.

Since the properties are the only differentiating characteristics for array elements, 'static' makes no sense, so I removed it.

If you define the class as follows:

    public class MyType
    {
        /// <summary>
        /// Need a constructor since we're using properties
        /// </summary>
        public MyType()
        {
            this.A = new int();
            this.B = string.Empty;
            this.C = new ushort();
        }

        public int A
        {
            get;
            set;
        }

        public string B
        {
            get;
            set;
        }

        public ushort C
        {
            get;
            set;
        }
    }

You could use it like so:

using System;

public static class Program
{
    [STAThread]
    private static void Main()
    {
        var myType = new MyType[3];

        myType[0] = new MyType();
        myType[1] = new MyType();
        myType[2] = new MyType();

        for (var i = 0; i < myType.Length; ++i)
        {
            myType[i].A = 0;
            myType[i].B = "1";
            myType[i].C = 2;
        }

        // alternatively, use foreach
        foreach (var item in myType)
        {
            item.A = 0;
            item.B = "1";
            item.C = 2;
        }
    }
}
Gustavo Mori
  • 8,319
  • 3
  • 38
  • 52
  • Thanks Gustavo. But one thing I need is the A, B and C fields of MYTYPE needs to be accessed with index. I do not to say it with names like myType.A instead myType[A] and access the A of the instance of type MYType. – Vikyboss Jul 20 '11 at 20:16
  • Really appreciate your work for spending time for writing codes. – Vikyboss Jul 20 '11 at 20:17
-1

Declare your Class / Model

class Movie {
    public required string Name { get; set; }
}

Create your array

var movies = new List<Movie>
{
    new Movie {
        Name = "first"
    },
    new Movie {
        Name = "second"
    },
    new Movie {
        Name = "third"
    },
    new Movie {
        Name = "fourth"
    }
};
Craig Wayne
  • 4,499
  • 4
  • 35
  • 50