Reputation: 9546
Let's say I have an class Activity
whose constructor's sole purpose is to assign the passed arguments to the properties for this instance:
class Activity
{
string name;
int participantCount;
bool inProgress;
public Activity(string name,int participantCount,bool inProgress)
{
this.name=name;
this.participantCount=participantCount;
this.inProgress=inProgress;
}
}
I use this pattern of constructor very frequently in my applications, so, assuming that this is an acceptable programming practice, I'm wondering if there is some kind of shortcut in Visual Studio for generating it, or a way of accomplishing the same effect with less code.
Upvotes: 3
Views: 232
Reputation: 52725
Visual Studio does not have any shortcuts for this, but Resharper does (if you are programming .NET and not using R#, you are wasting a lot of time)
When you generate a constructor using R#, you'll be asked to specify properties that should be initialized by it.
See http://www.jetbrains.com/resharper/webhelp/Code_Generation__Type_Constructors.html
Upvotes: 3
Reputation: 20445
I agree, it would be very helpful to have a shortcut for this. TypeScript does, and it's very nice. Unfortunately, C# 5.0 doesn't have anything like this. Fortunately, it's coming - or something like it - in C# 6.0.
The current proposed syntax looks something like this:
public class Point(int x, int y) {
public int x, y;
}
I'm not sure I like that syntax - I'd prefer something like how TS does it:
public class Point(public int x, private int y) { }
But what I want is probably irrelevant :-).
See http://damieng.com/blog/2013/12/09/probable-c-6-0-features-illustrated.
Upvotes: 4