-
Notifications
You must be signed in to change notification settings - Fork 8
[Installation] Using a Shared Project
This guide shows you how to use the Nullable package with a shared project.
Using the attributes with a shared projects requires you to manually copy&paste the C# file which means that this approach should only be a last resort if none of the other guides work for you. Futhermore, you cannot use multi-targeting as easily as with the package.
This guide requires an installation of Visual Studio 2019 which supports Nullable Reference Types. This can easily be done by updating to the latest version and ensuring that the .NET Core 3.0 SDK is installed.
Create a new .NET Core Console Application using C# 8.0. The target framework does not matter. In addition, create a new Shared Project and reference it from the Console Application. The final structure should look like this:
Copy or download the newest version of the attribute file(s) from this GitHub repository. Afterwards, add it to the shared project.
Placing the file(s) in a shared project has two advantages:
- If updates to the file(s) happen, you will only have to do it in one place.
- The attributes can be kept as
internal
classes and will still be compiled into each project that references the shared project. This is important for libraries, because this will avoid later name conflicts.
You should now be able to use the attributes in projects referencing the shared project.
Go ahead and try it out by replacing Program.cs
with this code:
#nullable enable
namespace NullableDemo
{
using System;
using System.Diagnostics.CodeAnalysis;
public class Program
{
[AllowNull]
public static string AllowsNull { get; set; } = "Hello";
public static string DoesntAllowNull { get; set; } = "Hello";
public static void Main()
{
AllowsNull = null;
DoesntAllowNull = null; // Should warn.
}
}
}
#nullable restore
If you have done everything correctly, you can now build your project and use these attributes. Furthermore, the code above should produce a compiler warning at the line with the comment.
To ensure that the attribute code file(s) really got added to your project, feel free to
put your cursor on [AllowNull]
in the code and press F12
afterwards. The file should now be
opened and you can see the code that will be compiled together with your project.