Name Anonymous Type
- 3 minutes to read
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
- Configure the Name Anonymous Type refactoring in the Editor | C# (Visual Basic) | Code Actions | Name Anonymous Type Settings options page.
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.
- 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" };
}
}
- Use the Ctrl + . or Ctrl + ~ shortcut to invoke the Code Actions Menu
- 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);
}
}