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.

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

13 Comments

You beat me to it by a fraction of a second ;) +1
I am guessing that this members shouldn't be static anyway :)
@Yiğit Yener - Agreed, but I have taken the code from the OP, perhaps this is intentional...
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.
|
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"]));
}

5 Comments

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. :)
No problem. Added the indexer. Hope it helps.
Thanks again. I used this but modified a little bit to suit the exact requirement. Thank you very much! :)
I also tried doing this with list and got another answer, just letting you know. stackoverflow.com/questions/6777699/….
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 :)
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;
        }
    }
}

2 Comments

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.
Really appreciate your work for spending time for writing codes.
-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"
    }
};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.