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:
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:
Now, we are presented with the dialog asking us which properties to initialize. Let’s pick all of them.
And after pressing Finish, our class ends up with a generated constructor:
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:
Choosing the option to generate both the equality operators (==
and !=
) as well as an implementation of IEquatable<T>
, ReSharper generates the following code:
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 choose Formatting members from the menu, pick the properties we want to appear in ToString()
, and voila - ReSharper generates the following implementation: