Visual Studio Code For C#



For more of MY VIDEOS!!!🔥 As an Amazon Associate I earn from qualifying purchases.👍 Patreon: https://www.patreon.com/hamradiocq?. How to Setup C# in Visual Studio Code Full SetupDownload the full source code of application here:https://codingshiksha.com/blogs/android/firebase-phone-auth.

Visual Studio Code can be a great companion to Unity for editing and debugging C# files. All of the C# features are supported and more. In the screen below, you can see code colorization, bracket matching, IntelliSense, CodeLens and that's just the start.

Read on to find out how to configure Unity and your project to get the best possible experience.

Visual Studio Code For C#

Prerequisites

From Using .NET Core in Visual Studio Code:

  1. Install the .NET Core SDK, which includes the Runtime and the dotnet command.

  2. [Windows only] Logout or restart Windows to allow changes to %PATH% to take effect.

  3. [macOS only] To avoid seeing 'Some projects have trouble loading. Please review the output for more details', make sure to install the latest stable Mono release.

    Note: This version of Mono, which is installed into your system, will not interfere with the version of MonoDevelop that is installed by Unity.

  4. Install the C# extension from the VS Code Marketplace.

Setup VS Code as Unity Script Editor

Open up Unity Preferences, External Tools, then browse for the Visual Studio Code executable as External Script Editor.

The Visual Studio Code executable can be found at /Applications/Visual Studio Code.app on macOS, %localappdata%ProgramsMicrosoft VS CodeCode.exe on Windows by default.

Unity has built-in support for opening scripts in Visual Studio Code as an external script editor on Windows and macOS. Unity will detect when Visual Studio Code is selected as an external script editor and pass the correct arguments to it when opening scripts from Unity. Unity will also set up a default .vscode/settings.json with file excludes, if it does not already exist (from Unity 5.5 Release notes).

Unity version 2019.2 or above

Since 2019.2, it is required to use the Visual Studio Code editor package. The built-in support for opening scripts from Unity and getting csproj and sln files generated has been removed.

Editing Evolved

With the solution file selected, you are now ready to start editing with VS Code. Here is a list of some of the things you can expect:

  • Syntax Highlighting
  • Bracket matching
  • IntelliSense
  • Snippets
  • CodeLens
  • Peek
  • Go-to Definition
  • Code Actions/Lightbulbs
  • Go to symbol
  • Hover

Two topics that will help you are Basic Editing and C#. In the image below, you can see VS Code showing hover context, peeking references and more.

Unity Extensions

The community is continually developing more and more valuable extensions for Unity. Here are some popular extensions that you might find useful. You can search for more extensions in the VS Code Extension Marketplace.

Visual Studio Code For C# Development

The extensions shown above are dynamically queried. Select an extension tile above to read the description and reviews to decide which extension is best for you. See more in the Marketplace.

Enabling code completion (For recent versions of Unity)

If you are installing VS Code for the first time, you might be missing targeting packs required for Unity's code-completion (IntelliSense) in VS Code.

Targeting pack download links:

Steps:

  1. Stop VS Code or Unity running.
  2. Download and install the targeting pack for your targeted framework version / preferred version from one of the above links.
  3. Start Unity.
  4. Create and/or open an existing script in VS Code, through Unity, and you should now see code completions.

Visual Studio Code C# Project

Enabling Unity warnings

Unity has a set of custom C# warnings, called analyzers, that check for common issues with your source code. These analyzers ship out of the box with Visual Studio but need to be set up manually in Visual Studio Code.

Due to how Unity handles its .csproj files, it does not seem possible to install packages automatically. You will need to download the analyzers from the NuGet website manually. When you're done, open the package file using a tool such as 7zip and extract Microsoft.Unity.Analyzers.dll onto your project's root folder. You can place it inside a folder named NuGet, for example. Do not place it inside Assets or Packages, as that will cause Unity to try to process the .dll, which will make it output an error in the console.

Next, create an omnisharp.json file at the root folder of your project, as explained here. Analyzer support in OmniSharp is experimental at the moment, so we need to enable it explicitly. We also need to point it to the .dll file we just extracted.

Studio

Your omnisharp.json file should end up looking like this:

where './NuGet/microsoft.unity.analyzers.1.9.0' is a relative path pointing to the folder containing the .dll file. Depending on where you placed it, your path may look different.

The Unity analyzers should now be working in your project. You can test them by creating an empty FixedUpdate() method inside one of your MonoBehavior classes, which should trigger a The Unity message 'FixedUpdate' is empty warning (UNT0001).

Note that while it is possible to activate these analyzers, the suppressors they ship with the package (that turn off other C# warnings that may conflict with these custom ones) may not be picked up by OmniSharp at the moment, according to this thread. You can still turn off specific rules manually by following these steps:

  1. Create a .editorconfig file in your project's root folder (next to Unity's .csproj files).
  2. Add the following contents to the file:

root=true tells OmniSharp that this is your project root and it should stop looking for parent .editorconfig files outside of this folder.

dotnet_diagnostic.IDE0051.severity = none is an example of turning off the analyzer with ID IDE0051 by setting its severity level to none. You can read more about these settings in the Analyzer overview. You can add as many of these rules as you wish to this file.

[*.cs] indicates that our custom rules should apply to all C# scripts (files with the .cs extension).

You are now ready to code in Visual Studio Code, while getting the same warnings as you would when using Visual Studio!

Next steps

Read on to learn more about:

  • Basic Editing - Learn about the powerful VS Code editor.
  • Code Navigation - Move quickly through your source code.
  • Debugging - how to use the debugger with your project
  • C# - learn about the C# support in VS Code

Common questions

I don't have IntelliSense

You need to ensure that your solution is open in VS Code (not just a single file). Open the folder with your solution and you usually will not need to do anything else. If for some reason VS Code has not selected the right solution context, you can change the selected project by clicking on the OmniSharp flame icon on the status bar.

Choose the -CSharp version of the solution file and VS Code will light up.

How can I change the file exclusions?

Unity creates a number of additional files that can clutter your workspace in VS Code. You can easily hide these so that you can focus on the files you actually want to edit.

To do this, add the following JSON to your workspace settings.

As you can see below this will clean things up a lot...

BeforeAfter

How can I debug Unity?

Install the Debugger for Unity extension. And check out Debugging with VS Code to learn more about VS Code debugging support.

5/2/2017
-->

.NET compiler platform (Roslyn) analyzers inspect your C# or Visual Basic code for code quality and style issues. Starting in .NET 5.0, these analyzers are included with the .NET SDK and you don't need to install them separately. If your project targets .NET 5 or later, code analysis is enabled by default. If your project targets a different .NET implementation, for example, .NET Core, .NET Standard, or .NET Framework, you must manually enable code analysis by setting the EnableNETAnalyzers property to true.

If you don't want to move to the .NET 5+ SDK, have a non-SDK-style .NET Framework project, or prefer a NuGet package-based model, the analyzers are also available in the Microsoft.CodeAnalysis.NetAnalyzers NuGet package. You might prefer a package-based model for on-demand version updates.

Note

Visual studio code for c# development

.NET analyzers are target-framework agnostic. That is, your project does not need to target a specific .NET implementation. The analyzers work for projects that target net5.0 as well as earlier .NET versions, such as netcoreapp3.1 and net472. However, to enable code analysis using the EnableNETAnalyzers property, your project must reference a project SDK.

If rule violations are found by an analyzer, they're reported as a suggestion, warning, or error, depending on how each rule is configured. Code analysis violations appear with the prefix 'CA' or 'IDE' to differentiate them from compiler errors.

Code quality analysis

Code quality analysis ('CAxxxx') rules inspect your C# or Visual Basic code for security, performance, design and other issues. Analysis is enabled, by default, for projects that target .NET 5.0 or later. You can enable code analysis on projects that target earlier .NET versions by setting the EnableNETAnalyzers property to true. You can also disable code analysis for your project by setting EnableNETAnalyzers to false.

Free Visual Basic Code Examples

Tip

If you're using Visual Studio:

  • Many analyzer rules have associated code fixes that you can apply to correct the problem. Code fixes are shown in the light bulb icon menu.
  • You can enable or disable code analysis by right-clicking on a project in Solution Explorer and selecting Properties > Code Analysis tab > Enable .NET analyzers.

Enabled rules

The following rules are enabled, by default, in .NET 5.0.

Diagnostic IDCategorySeverityDescription
CA1416InteroperabilityWarningPlatform compatibility analyzer
CA1417InteroperabilityWarningDo not use OutAttribute on string parameters for P/Invokes
CA1831PerformanceWarningUse AsSpan instead of range-based indexers for string when appropriate
CA2013ReliabilityWarningDo not use ReferenceEquals with value types
CA2014ReliabilityWarningDo not use stackalloc in loops
CA2015ReliabilityWarningDo not define finalizers for types derived from MemoryManager<T>
CA2200UsageWarningRethrow to preserve stack details
CA2247UsageWarningArgument passed to TaskCompletionSource constructor should be TaskCreationOptions enum instead of TaskContinuationOptions

You can change the severity of these rules to disable them or elevate them to errors. You can also enable more rules.

  • For a list of rules that are included with each .NET SDK version, see Analyzer releases.
  • For a list of all the code quality rules, see Code quality rules.

Enable additional rules

Analysis mode refers to a predefined code analysis configuration where none, some, or all rules are enabled. In the default analysis mode, only a small number of rules are enabled as build warnings. You can change the analysis mode for your project by setting the <AnalysisMode> property in the project file. The allowable values are:

ValueDescription
AllDisabledByDefaultThis is the most conservative mode. All rules are disabled by default. You can selectively opt into individual rules to enable them.
<AnalysisMode>AllDisabledByDefault</AnalysisMode>
AllEnabledByDefaultThis is the most aggressive mode. All rules are enabled as build warnings. You can selectively opt out of individual rules to disable them.
<AnalysisMode>AllEnabledByDefault</AnalysisMode>
DefaultThe default mode, where a handful of rules are enabled as warnings, others are enabled only as Visual Studio IDE suggestions with corresponding code fixes, and the rest are disabled completely. You can selectively opt into or out of individual rules to disable them.
<AnalysisMode>Default</AnalysisMode>

To find the default severity for each available rule and whether or not the rule is enabled in the default analysis mode, see the full list of rules.

Treat warnings as errors

If you use the -warnaserror flag when you build your projects, all code analysis warnings are also treated as errors. If you do not want code quality warnings (CAxxxx) to be treated as errors in presence of -warnaserror, you can set the CodeAnalysisTreatWarningsAsErrors MSBuild property to false in your project file.

You'll still see any code analysis warnings, but they won't break your build.

Latest updates

By default, you'll get the latest code analysis rules and default rule severities as you upgrade to newer versions of the .NET SDK. If you don't want this behavior, for example, if you want to ensure that no new rules are enabled or disabled, you can override it in one of the following ways:

  • Set the AnalysisLevel MSBuild property to a specific value to lock the warnings to that set. When you upgrade to a newer SDK, you'll still get bug fixes for those warnings, but no new warnings will be enabled and no existing warnings will be disabled. For example, to lock the set of rules to those that ship with version 5.0 of the .NET SDK, add the following entry to your project file.

    Tip

    The default value for the AnalysisLevel property is latest, which means you always get the latest code analysis rules as you move to newer versions of the .NET SDK.

    For more information, and to see a list of possible values, see AnalysisLevel.

  • Install the Microsoft.CodeAnalysis.NetAnalyzers NuGet package to decouple rule updates from .NET SDK updates. For projects that target .NET 5+, installing the package turns off the built-in SDK analyzers. You'll get a build warning if the SDK contains a newer analyzer assembly version than that of the NuGet package. To disable the warning, set the _SkipUpgradeNetAnalyzersNuGetWarning property to true.

    Note

    If you install the Microsoft.CodeAnalysis.NetAnalyzers NuGet package, you should not add the EnableNETAnalyzers property to either your project file or a Directory.Build.props file. When the NuGet package is installed and the EnableNETAnalyzers property is set to true, a build warning is generated.

Code-style analysis

Code-style analysis ('IDExxxx') rules enable you to define and maintain consistent code style in your codebase. The default enablement settings are:

  • Command-line build: Code-style analysis is disabled, by default, for all .NET projects on command-line builds.

    Starting in .NET 5.0, you can enable code-style analysis on build, both at the command line and inside Visual Studio. Code style violations appear as warnings or errors with an 'IDE' prefix. This enables you to enforce consistent code styles at build time.

  • Visual Studio: Code-style analysis is enabled, by default, for all .NET projects inside Visual Studio as code refactoring quick actions.

For a full list of code-style analysis rules, see Code style rules.

Enable on build

Visual

With the .NET 5.0 SDK and later versions, you can enable code-style analysis when building from the command-line and in Visual Studio. (However, for performance reasons, a handful of code-style rules will still apply only in the Visual Studio IDE.)

Follow these steps to enable code-style analysis on build:

  1. Set the MSBuild property EnforceCodeStyleInBuild to true.

  2. In an .editorconfig file, configure each 'IDE' code style rule that you wish to run on build as a warning or an error. For example:

    Alternatively, you can configure an entire category to be a warning or error, by default, and then selectively turn off rules in that category that you don't want to run on build. For example:

Note

The code-style analysis feature is experimental and may change between the .NET 5 and .NET 6 releases.

Suppress a warning

One way to suppress a rule violation is to set the severity option for that rule ID to none in an EditorConfig file. For example:

For more information and other ways to suppress warnings, see How to suppress code analysis warnings.

Third-party analyzers

In addition to the official .NET analyzers, you can also install third party analyzers, such as StyleCop, Roslynator, XUnit Analyzers, and Sonar Analyzer.

See also