ReSharper 2016.1 Help

Quickly create a type

In this tutorial, we create a type with a standard set of methods.

Creating types or entities in C# can be quite difficult. After all, how many of us remember by hand the correct implementation of Equals()? Luckily, ReSharper is there to help. Let’s take a look.

First, let’s define the simplest possible entity class called Person, which will store a person’s name and age:

public class Person { public string Name { get; set; } public int Age { get; set; } }

1. Generate constructor

As it stands, initialization of this class is painful because it has no constructor. Let’s make one by using the Generate Code command (Alt+Insert). First, let’s fire it up over the class and choose Constructor:

Generating type constructor

Now, we are presented with the dialog asking us which properties to initialize. Let’s pick all of them.

Generating type constructor

And after pressing Finish, our class ends up with a generated constructor:

public Person(string name, int age) { Name = name; Age = age; }

2. Generate equality members

Say we want to keep Person instances in a HashSet<Person> collection. To do this, we need to implement Equals() and GetHashCode(). Once again, ReSharper helps us with this – we invoke the Generate command once again, and choose Equality members. The following dialog shows up:

Generating equality members

Choosing the option to generate both the equality operators (== and !=) as well as an implementation of IEquatable<T>, ReSharper generates the following code:

public bool Equals(Person other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return string.Equals(Name, other.Name) && Age == other.Age; } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != this.GetType()) return false; return Equals((Person) obj); } public override int GetHashCode() { unchecked { return ((Name != null ? Name.GetHashCode() : 0)*397) ^ Age; } } public static bool operator ==(Person left, Person right) { return Equals(left, right); } public static bool operator !=(Person left, Person right) { return !Equals(left, right); }

3. Generate formatting members

Now, we would also like to get an implementation of the ToString() method for some logging and debugging. Once again, the Generate menu is here. We simply choose Formatting members from the menu, pick the properties we want to appear in ToString(), and voila - ReSharper generates the following implementation:

public override string ToString() { return string.Format("Name: {0}, Age: {1}", Name, Age) }

See Also

Last modified: 19 August 2016