title: Struct containing reference types
body: <p>A struct is a value type, so if I assign a struct to another struct, its fields will be copied in the second struct. But, what happens if some fields of the struct are a reference type?</p>
  
  <pre><code>public struct MyIPEndPoint
  {
      public String IP;
      public UInt16 Port;
  
      public MyIPEndPoint(String ipAddress, UInt16 portNumber)
      {
          IP = ipAddress;
          Port = portNumber;
      }
  
      public override string ToString()
      {
          return IP+":"+Port;
      }
  }
  
  ...
  
  static int Main(string[] args)
  {
      MyIPEndPoint address1 = new MyIPEndPoint("127.0.0.1", 8080);
      MyIPEndPoint address2 = address1;
  
      address2.IP = "255.255.255.255";
      address2.Port = 9090;
  
      Console.WriteLine(address1);
      Console.WriteLine(address2);
  }
  </code></pre>
  
  <p>The output is:</p>
  
  <pre><code>127.0.0.1:8080
  255.255.255.255:9090
  </code></pre>
  
  <p>Why the <code>IP</code> (a string, that is a reference type) of <code>address1</code> does not change?
  The same behavior occurs if I replace <code>string</code> with <code>IPAddress</code> to represent the IP within <code>MyIPEndPoint</code>: although <code>IPAddress</code> is a class (that is a reference type), it does not behave as a reference type. Why?</p>
  
  <p>Indeed, if I wrap the <code>string</code> which represent the IP using a new simple class <code>MyIP</code>, the behavior changes.</p>
  
  <pre><code>public class MyIP
  {
      public string IpAsString;
  
      public MyIP(string s)
      {
          IpAsString = s;
      }
      public override string ToString()
      {
          return IpAsString;
      }
  }
  </code></pre>
  
  <p>Of course you should also adjust the <code>MyIPEndPoint</code> struct in the following way:</p>
  
  <pre><code>public struct MyIPEndPoint
  {
      public MyIP IP;   // modification
      public UInt16 Port;
  
      public MyIPEndPoint(String ipAddress, UInt16 portNumber)
      {
          IP = new MyIP(ipAddress);   // modification
          Port = portNumber;
      }
  
      public override string ToString()
      {
          return IP+":"+Port;
      }
  }
  </code></pre>
  
  <p>Finally in the <code>Main</code> I changed only a statement:</p>
  
  <pre><code>MyIPEndPoint address1 = new MyIPEndPoint("127.0.0.1", 8080);
  MyIPEndPoint address2 = address1;
  
  address2.IP.IpAsString = "255.255.255.255";   // modification
  address2.Port = 9090;
  
  Console.WriteLine(address1);
  Console.WriteLine(address2);
  </code></pre>
  
  <p>Now the output is:</p>
  
  <pre><code>255.255.255.255:8080
  255.255.255.255:9090
  </code></pre>
  
  <p>I was expecting this output in the first case.
  Why in the first case does the reference not behave <em>as expected</em>?</p>