C#: Representation of an Anonymous Type: Listing 1

This code is similar to the code created by the compiler for anonymous types. The compiler creates a generic type in order to reuse some code. Also, the compiler generates names that are illegal for handwritten code to avoid collisions with user-defined types.

internal sealed class AnonymousOne
{
    // Fields
    private readonly int xField;
    private readonly int yField;

    // Methods
    public AnonymousOne(int x, int y)
    {
     this.xField = x;
     this.yField = y;
    }

    public override bool Equals(object value)
    {
     var type = value as AnonymousOne;
     return (((type != null) &&
      EqualityComparer<int>.Default.Equals(this.xField, 
          type.xField)) &&
      EqualityComparer<int>.Default.Equals(this.yField, 
           type.yField));
   }

   public override int GetHashCode()
   {
        uint num = 0xdd9cb371;
        num = (0xa5555529 * num) +

(uint)EqualityComparer<int>.Default.GetHashCode(
         this.xField);
     return (int)((0xa5555529 * num) + 

(uint)EqualityComparer<int>.Default.GetHashCode(
         this.yField));
   }

   public override string ToString()
   {
      StringBuilder builder = new StringBuilder();
      builder.Append("{ x = ");
      builder.Append(this.xField);
      builder.Append(", y = ");
      builder.Append(this.yField);
      builder.Append(" }");
      return builder.ToString();
   }

   // Properties
   public int x
   {
      get { return this.xField; }
   }

   public int y
   {
      get { return this.yField; }
   }
}
comments powered by Disqus
Upcoming Events

.NET Insight

Sign up for our newsletter.

I agree to this site's Privacy Policy.