C# shortcut or shorthand getter setter

C#Visual Studio-2010Shortcut

C# Problem Overview


Is there a short way to create the getter and setter in c#?

public string fname {get; set;} 

Is there short hand to generate {get; set;}?

C# Solutions


Solution 1 - C#

yea type prop and press TAB. Visual Studio has a snippet for automatic property.

For property with public get and private set, you can use propg and press TAB.

For complete non auto property you can use propfull and press TAB.

Solution 2 - C#

If you just want the getter and setter, as orignally asked for, you could also create a custom snippet:

<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
    <CodeSnippet Format="1.0.0">
        <Header>
            <Title>GetSet</Title>
			<Description>Inserts getter/setter shorthand code</Description>
			<Shortcut>gs</Shortcut>
        </Header>
        <Snippet>
            <Code Language="CSharp">
                <![CDATA[{ get; set; }$end$]]>
            </Code>
        </Snippet>
    </CodeSnippet>
</CodeSnippets>

Save the above as a .snippet in your snippets folder. Typing 'gs' and pressing Tab will insert { get; set;} and move to the end of the line.


Edit

In VS Code, this would be a custom user snippet in your csharp.json file:

"Getter Setter": {
	"prefix": "gs",
	"body": [
		"\\{ get; set; \\}",
		"$1"
	],
	"description": "Insert shorthand autoproperties"
}

Either of these examples could easily be modified/duplicated to also do { get; } (use a readonly backing field) or { get; private set; }

Solution 3 - C#

The shortcut is the trigger "prop":

prop<tab><tab>int<tab>Id<tab>

and you end up with:

public int Id { get; set; }

Solution 4 - C#

When I type prop & TAB I get:

    public int MyProperty
    {
        get; set;
    }

Is there a way to set it up so it's all on one line so it looks like:

public int MyProperty { get; set;}

UPDATE!!! I figured it out.

Tools --> Options --> Text Editor --> C# --> Code Style --> Formatting --> Wrapping --> Put a checkmark in the "Leave block on a single line" option. It even uses the "get; set;" as an example. Setting Get;Set; to one line.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionYogurt The WiseView Question on Stackoverflow
Solution 1 - C#Muhammad Hasan KhanView Answer on Stackoverflow
Solution 2 - C#brichinsView Answer on Stackoverflow
Solution 3 - C#Glory RajView Answer on Stackoverflow
Solution 4 - C#John WaclawskiView Answer on Stackoverflow