Reputation: 16959
I have an object with 100 properties. Is there a feature in Resharper or Visual Studio 2017 that generates the code for all the properties of the object. e.g.
var myObject = new ObjectWithMultipleProps
{
Prop1 = "",
Prop2 = 0,
Prop3 = "",
...etch
}
I am creating unit tests and it would speed up things if this would be possible.
Upvotes: 0
Views: 73
Reputation: 11760
type this much:
var myObject = new ObjectWithMultipleProps {
Then press Ctrl+J, Tab. The next unused field or Property will get auto completed for you. You can press Ctrl+J again and it will pop up the type of the field so you can choose an appropriate value. Or you can start typing new
then press Ctrl+J and it will auto-complete the type for you.
Then type a comma, and repeat the process for each field. Fields that you have already specified will not appear in the list. If you do not want to set a value for a field, then omit it from the initializer list, and it will get its default value.
Upvotes: 1
Reputation: 37095
You seem to have a misunderstanding on what creating an instance means. There´s no way for an instantiated object (this is when you called new ...
) to have no value for any of your members. All those members are initialized from the runtime to the default-type for the type of that member. In particular you can´t partly initialize your object, that is set only some members to an initial-value, whilst not setting others. Creating an instance is an all-or-nothing-operation.
So if you simply write this:
var myObject = new ObjectWithMultipleProps();
all properties within myObject
will have their defualt-value. You can even print them:
Console.WriteLine(myObject.Prop2); // this will print 0
You coul of course write all those assignments into the class´ constructor:
class ObjectWithMultipleProps
{
public ObjectWithMultipleProps()
{
Prop1 = null;
Prop2 = 0;
}
}
This however has the exact same effect.
What may happen anyway is, that you get a NullReferenceException
. This is because all reference-types default to null
, making any call to those members yield to that exception, as shown in the following code:
var a = myObject.Prop1.SubsString(0, 1);
As Prop1
is initialized to null
once the instance is completely created, you get a NullReferenceException
, because you can´t call any member on null
.
If you want other default-values for your members, you have to create the constructor and set the values there.
Upvotes: 0