13

I have a class with more than 8 properties, and I often want to instantiate it in some method, but it is super tedious to have to write the properties one by one to assign them the value.

Is there any way to insert a kind of "code fragment" with a keyboard shortcut, which allows me to insert the instance of the class, and I just modify the values ​​to add?.

I do not want to use constructors because I want the instance to be readable for the reader of my code and because the constructors do not work in LinQ to SQL.

I Use Visual Studio 2015, C#, Resharper.

Thank you very much.

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
HenryGuillen17
  • 370
  • 1
  • 3
  • 13

4 Answers4

12

If you are initialising like this:

  var example = new Example()
    {
        ...
    };

Then you can use Ctrl-Space and it will keep offering you properties left for auto complete that you have yet to set.

Ben Hall
  • 1,353
  • 10
  • 19
  • 7
    Yes, I know that, but I wanted to know if there is a shortcut for you to put them all automatically, the values ​​of those properties may be filled with default values, It is that it becomes tedious when we need to instantiate a class with too many properties. – HenryGuillen17 Jan 26 '18 at 15:49
  • Not without some work with macros in ReSharper then I'd guess sorry. – Ben Hall Jan 26 '18 at 15:52
  • @HenryGuillen17 did you every find solution to instancing class object with all properties implemented with defaults??? – Adam Cox Aug 13 '20 at 03:27
  • No, but I think that it's easy. – HenryGuillen17 Aug 17 '20 at 22:33
11

I've created the Generate an initializer for a new object with names of public properties and fields command for the Visual Commander extension. Call it after entering the class name and it will generate an initializer:

enter image description here

Sergey Vlasov
  • 26,641
  • 3
  • 64
  • 66
  • It looks very good, but excuse the ignorance: It works for VS 2015? How do I install it in VS2015? Thank you. – HenryGuillen17 Feb 01 '18 at 13:11
  • 1. Install Visual Commander. 2. Add new command (VCmd - Commands - Add). 3. Select C# language, copy&paste References, copy&paste Code. 4. Click Save. – Sergey Vlasov Feb 01 '18 at 17:42
  • I'm still struggling to use this, do I need to setup a shortcut key? Also this doesn't seems to include properties from the parent class. – PLopes Nov 15 '19 at 13:47
  • 1
    @PLopes You can assign a shortcut key or call the command from the VCmd menu. In GetMembersForInitialization I use type.GetMembers() that doesn't include parent. Probably calling GetMembers(BindingFlags.FlattenHierarchy) to the call will include them. – Sergey Vlasov Nov 15 '19 at 20:10
  • Hey Sergey, not sure if you're still following this thread, but when trying to use your command, I get the following exception: `(108,16): error CS0012: The type 'System.IEquatable'1' is defined in an assembly that is not referenced. You must add a reference to assembly 'netstandard, Version=2.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51'.` I'm running .NET Core 3.1, do you know if there's any way I can change the command to work with my setup? – Kiran Ramaswamy Apr 03 '20 at 16:44
  • @KiranRamaswamy Just add netstandard to the command references (the new line with text netstandard in the References dialog). – Sergey Vlasov Apr 04 '20 at 04:10
  • @SergeyVlasov I get this error in 2019: `(41,62): error CS0246: The type or namespace name 'T' could not be found (are you missing a using directive or an assembly reference?) (49,32): error CS0305: Using the generic type 'System.Collections.Generic.List' requires 1 type arguments` – RichC Apr 02 '21 at 16:31
  • 1
    @RichC I've fixed unescaped angle brackets in code on the site. – Sergey Vlasov Apr 03 '21 at 08:41
  • Thank you! Thank you so much for your contribution! – AbdulG Aug 09 '22 at 18:06
  • HAH that worked beautifully. Thank you so much. – Marz Aug 29 '22 at 02:24
  • Now I just need it to drill down in and create the child objects too. – Marz Aug 29 '22 at 02:29
  • @Mary If I understand correctly the meaning of child objects, you can try to replace case TypeKind.Class: return "null"; with something like case TypeKind.Class: return $“new {type.Name}” + CreateInitializer(GetMembersForInitialization(type)); (I haven’t tested it.) – Sergey Vlasov Aug 29 '22 at 19:30
0

You can create custom code snippet the format is like following:

<?xml version="1.0" encoding="utf-8" ?> <CodeSnippet Format="1.0.0" xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet"> <Header> <Title>Create instance of my class</Title> <Author>Author</Author> <Shortcut>ShortCut (then press tab tab)</Shortcut> <-- Put your snippet <Description>Description</Description> <SnippetTypes> <SnippetType>SurroundsWith</SnippetType> <SnippetType>Expansion</SnippetType> </SnippetTypes> </Header> <Snippet> <Declarations> <Literal> <ID>message</ID> <Default>my function</Default> </Literal> </Declarations> <Code Language="CSharp"> <![CDATA[ var myclass = new MyClass() { Property1 = 1, Property2 = 2 }; ]]> </Code> </Snippet> </CodeSnippet>

You can save this in Nodepad and the you have to save this file with .snippet extension. Look for folder ..Visual Studio 2017\Code Snippets\Visual C#\My Code Snippets
When you are ready open VS and go in Tools -> Code Snippet Manager and choose Language CSharp then select your snippet from My Code Snippets folder and you should be ready to use it

Ivan Ruski
  • 1,123
  • 1
  • 13
  • 19
  • The idea is very good, but something that detects the object is possible and it will map all the properties and assign them a default value: example: example: `var object = new Object {Id = 0, Value = "", otherObject = null }` – HenryGuillen17 Jan 26 '18 at 16:05
-1

As far as I know, there's not a built in way to generate an instantiator with all the properties of the object. Generally when you have to do this, you would go through a constructor so you know that the object is getting created correctly.

You could create some type of code snippet in Visual Studio, but you'd have to make it yourself and it would only really work for that object....

You can view this post as well since it's pretty close to what you're looking for but it doesn't sound like they found a great way to do this either: Is there a way, at design time, to initialize an object with all properties in Visual Studio 2010?

Bacskay
  • 396
  • 4
  • 12
  • Then I would have to make a macro for VS that allows me to insert that object. The ideal way would be that it could be supported for all objects. – HenryGuillen17 Jan 26 '18 at 16:02
  • Indeed, it honestly kind of sucks to have to do that for every single object. I think that's why most people either use an instantiator and fill in the fields they need or make a constructor for the object that takes in all the fields that are needed. – Bacskay Jan 26 '18 at 16:09
  • I have to resign myself to do it manually, it's just that I can not use a constructor with Linq To SQL; also thanks for your help – HenryGuillen17 Jan 26 '18 at 16:13
  • While I can't speak for the "general" case, I can say that this object instantiation syntax certainly has valid use cases where a constructor would not be necessary. – James Hurley Apr 05 '23 at 12:59