How to create an array of custom type in C#?
Solution 1
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"]));
}
Solution 2
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.
Solution 3
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;
}
}
}
Vikyboss
Updated on May 12, 2020Comments
-
Vikyboss about 4 years
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.
-
BenAlabaster almost 13 yearsYou beat me to it by a fraction of a second ;) +1
-
Yiğit Yener almost 13 yearsI am guessing that this members shouldn't be static anyway :)
-
Oded almost 13 years@Yiğit Yener - Agreed, but I have taken the code from the OP, perhaps this is intentional...
-
Vikyboss almost 13 yearsYeah, 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 almost 13 years
-
Oded almost 13 years@Vikyboss - It is better to use properties on a type you create.
-
Vikyboss almost 13 yearsSorry, could you say more on that? Thanks
-
Oded almost 13 years@Vikyboss - What exactly do you want to know?
-
Vikyboss almost 13 yearsThe reason I used object[] is to group different types of elements.
-
Oded almost 13 years@Vikyboss - That's practically the definition of a struct.
-
Vikyboss almost 13 yearsI'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.
-
Oded almost 13 years@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.
-
Vikyboss almost 13 yearsI did already here : stackoverflow.com/questions/6750265/… But people suggested to not use struct and use array, thats why I asked this question with array.
-
Vikyboss almost 13 yearsThanks 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 almost 13 yearsReally appreciate your work for spending time for writing codes.
-
Vikyboss almost 13 yearsWow, 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. :)
-
Gustavo Mori almost 13 yearsNo problem. Added the indexer. Hope it helps.
-
Vikyboss almost 13 yearsThanks again. I used this but modified a little bit to suit the exact requirement. Thank you very much! :)
-
Vikyboss almost 13 yearsI also tried doing this with list and got another answer, just letting you know. stackoverflow.com/questions/6777699/….
-
Gustavo Mori almost 13 yearsGlad 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 :)