The requested page is not available for the requested platform. You are viewing the content for Default platform.

Name Anonymous Type

Purpose

Replaces the selected anonymous type with a newly-declared type.

Availability

Available when the cursor is on an anonymous type.

Notes

  • This refactoring constructs the code for a class that matches the selected anonymous type. The anonymous type reference is replaced with the newly declared type's constructor.
  • This refactoring scans the entire project and replaces all matching anonymous types with the new class.

How to Use

  1. Configure the Name Anonymous Type refactoring in the Editor | C# (Visual Basic) | Code Actions | Name Anonymous Type Settings options page.

Settings

For example, choose Include the [DebuggerDisplay] attribute, Generate Equals() and GetHashCode() methods, and Generate the ToString() method options and click OK to close this options page.

  1. Switch to code. Place the caret in an anonymous type.
Note

The blinking cursor shows the caret's position where the Refactoring is available.

public class TestClass {
    public void TestMethod() {
        var employee1 =  new { id = 1, name = "Nick Johnson" };
    }
}
  1. Use the Ctrl + . or Ctrl + ~ shortcut to invoke the Code Actions Menu

Invoke

  1. Select Name Anonymous Type from the menu.

After execution, the Refactoring replaces the anonymous type with a newly-declared type.


public class TestClass {
    public void TestMethod() {
        var employee1 = new Employee1 { id = 1, name = "Nick Johnson" };
    }
}


[System.Diagnostics.DebuggerDisplay("\\{ id = {id}, name = {name} \\}")]
sealed class Employee1 {
    public int id { get; set; }
    public string name { get; set; }

    public override bool Equals(object obj) {
        if (obj is Employee1)
        {
            return Equals((Employee1)obj);
        }

        return base.Equals(obj);
    }

    public bool Equals(Employee1 other) {
        if (ReferenceEquals(null, other))
        {
            return false;
        }

        if (ReferenceEquals(this, other))
        {
            return true;
        }

        return id.Equals(other.id) && Equals(name, other.name);
    }

    public override int GetHashCode() {
        unchecked
        {
            int hashCode = 47;
            hashCode = (hashCode * 53) ^ id.GetHashCode();
            if (name != null)
            {
                hashCode = (hashCode * 53) ^ EqualityComparer<string>.Default.GetHashCode(name);
            }

            return hashCode;
        }
    }

    public override string ToString()
    {
        return String.Format("{{ id = {0}, name = {1} }}", id, name);
    }
}