Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define struct array with values

Tags:

c#

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 } };        
like image 740
Nime Cloud Avatar asked Jun 26 '26 17:06

Nime Cloud


2 Answers

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) };
like image 116
Anthony Pegram Avatar answered Jun 29 '26 07:06

Anthony Pegram


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.

like image 31
Andrew Hare Avatar answered Jun 29 '26 06:06

Andrew Hare



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!