Define an array of structure with values

Is it possible to define a struct / class array with values ​​similar 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 have to use variable names up to the values:

    RemoteDetector oneDetector = new RemoteDetector() { Host = "localhost", Port = 999 };
    RemoteDetector[] remoteDetectors = { new RemoteDetector() { Host = "localhost", Port = 999 } };        
+3
source share
2 answers

You can do this, but it is not recommended, as your structure will be volatile. You must strive for the immutability of your structures. Thus, the values ​​for the set must be passed through the constructor, which is also quite simple to initialize the array.

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) };
+7
source

You want to use the C # object and collection initializer syntax as follows:

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
            }
        };
    }
}

: , . # , , .

+3

All Articles