3

Can I define struct/class array with values -like below- and how?

   struct RemoteDetector
    {
        public string Host;
        public int Port;
    }

    RemoteDetector oneDetector = new RemoteDetector() { "localhost", 999 };
    RemoteDetector[] remoteDetectors = {new RemoteDetector(){"localhost",999}};        

Edit: I should use variable names before the values:

    RemoteDetector oneDetector = new RemoteDetector() { Host = "localhost", Port = 999 };
    RemoteDetector[] remoteDetectors = { new RemoteDetector() { Host = "localhost", Port = 999 } };        
Nime Cloud
  • 6,162
  • 14
  • 43
  • 75
  • Possible duplicate of [Initializing an Array of Structs in C#](http://stackoverflow.com/questions/309496/initializing-an-array-of-structs-in-c) – Frédéric Hamidi Mar 18 '11 at 14:14
  • Oh I've forgotten names: RemoteDetector oneDetector = new RemoteDetector() { Host = "emin", Port = 999 }; RemoteDetector[] remoteDetectors = { new RemoteDetector() { Host = "emin", Port = 999 } }; – Nime Cloud Mar 18 '11 at 14:15

2 Answers2

7

You can do that, but it is not recommended as your struct would be mutable. You should strive for immutability with your structs. As such, values to set should be passed through a constructor, which is also simple enough to do in an array initialization.

struct Foo
{
   public int Bar { get; private set; }
   public int Baz { get; private set; }

   public Foo(int bar, int baz) : this() 
   {
       Bar = bar;
       Baz = baz;
   }
}

...

Foo[] foos = new Foo[] { new Foo(1,2), new Foo(3,4) };
Anthony Pegram
  • 123,721
  • 27
  • 225
  • 246
3

You want to use C#'s object and collection initializer syntax like this:

struct RemoteDetector
{
    public string Host;
    public int Port;
}

class Program
{
    static void Main()
    {
        var oneDetector = new RemoteDetector
        {
            Host = "localhost",
            Port = 999
        };

        var remoteDetectors = new[]
        {
            new RemoteDetector 
            { 
                Host = "localhost", 
                Port = 999
            }
        };
    }
}

Edit: It's really important that you follow Anthony's advice and make this struct immutable. I am showing some of C#'s syntax here but the best practice when using structs is to make them immutable.

Community
  • 1
  • 1
Andrew Hare
  • 344,730
  • 71
  • 640
  • 635