Home > Software design >  Having trouble with C# arrays and objects
Having trouble with C# arrays and objects

Time:09-14

I come from a javascript background, and I'm having trouble understanding C#.

I'm trying to implement an array of objects, like so

Javascript

var objectArray = [];

objectArray[0] = {
    name: "Test",
    text: "Hello!",
    turn: 25
};

objectArray[1] = {
    name: "Test2",
    text: "Hello, the second time!",
    turn: 27
};

....

How would I do something like this in C#?

CodePudding user response:

So firstly the schema of the object would need to be created as a class.

public class YourObjectName 
{
    public string Name { get; set; }
    public string Text { get; set; }
    public int Turn { get; set; }
}

Then you can instantiate a list of this class like so ...

var myList = new List<YourObjectName>();

If you want to initialise with values you can do ...

var myList = new List<YourObjectName>()
{
    {
        Name: "Test",
        Text: "Hello!",
        Turn: 25
    },
    {
        Name: "Test2",
        Text: "Hello, the second time!",
        Turn: 27
    }
};

CodePudding user response:

While something like this is possible like so:

using System;
                    
public class Program
{
    public static void Main()
    {
        object[] objectArray = new object[]{
            new {
                name = "Test",
                text = "Hello!",
                turn = 25
            },
            new {
                name = "Test2",
                text = "Hello, the second time!",
                turn = 27
            }
        };
        
        foreach (object o in objectArray)
            System.Console.WriteLine(o.ToString());
    }
}

Producing the following output:

{ name = Test, text = Hello!, turn = 25 }
{ name = Test2, text = Hello, the second time!, turn = 27 }

It is not common. You'd usually create a class that defines the Structure of the data you want to handle and make an array out of that like

ClassName[] array = new ClassName[ArraySize];

Read up on classes and inheritance here.

  •  Tags:  
  • c#
  • Related