Reputation: 796
Been looking for a way (either built-in, or through a plugin), to automate the properties and defaults when instantiating a class. For example, if I have the following:
public class MyClass
{
string MyPropertyString { get; set; }
int MyPropertyIntWithDefault { get; set; } = 5,
decimal? MyPropertyDecimalWithNoDefault { get; set; }
}
I'd love to be able to say MyClass MyClassImplemented = new MyClass {
, hit a button or click an option, and have it automatically finish my code as:
MyClass MyClassImplemented = new MyClass {
MyPropertyString = "",
MyPropertyIntWithDefault = 5,
MyPropertyDecimalWithNoDefault = null
};
I'm guessing I could write an extension or tool myself using reflection, but if anyone has any suggestions that have already been implemented, I'd love to hear them. Thanks!
* EDIT *
To be clear, what I'm looking for is a way to automate the generation of that stub so that I can then change the ones I want to change, instead of having to either type them in manually or copy-paste them from the definition. I know that I can set default values so that I can generate the class with those values automatically.
Upvotes: 0
Views: 439
Reputation: 39946
All that you need is just creating a new instance of your class, then this new instance has all of the properties filled by their default value:
MyClass MyClassImplemented = new MyClass();
You just need to change your class a bit to set the properties a default value (don't forget to use ;
after properties, however this works in C#6+):
public class MyClass
{
public string MyPropertyString { get; set; } = "";
public int MyPropertyIntWithDefault { get; set; } = 5;
public decimal? MyPropertyDecimalWithNoDefault { get; set; }
}
Based on your update, it seems what you are looking for, is a way to create a code snippet, so that you would be able to append the properties of the class by hitting some button, in this case you can create a code snippet in Visual Studio, you can go through this tutorial https://learn.microsoft.com/en-us/visualstudio/ide/walkthrough-creating-a-code-snippet?view=vs-2019
Upvotes: 1