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 } };        
2
  • Possible duplicate of Initializing an Array of Structs in C# Commented Mar 18, 2011 at 14:14
  • Oh I've forgotten names: RemoteDetector oneDetector = new RemoteDetector() { Host = "emin", Port = 999 }; RemoteDetector[] remoteDetectors = { new RemoteDetector() { Host = "emin", Port = 999 } }; Commented Mar 18, 2011 at 14:15

2 Answers 2

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) };
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.