Ticker

6/recent/ticker-posts

Code Sharing in .NET Core

Code Sharing in .NET Core


Introduction: Code sharing in .NET Core allows developers to reuse code across different platforms, such as Windows, macOS, and Linux. With the use of .NET Standard and Portable Class Libraries (PCL), developers can write code once and use it in various .NET platforms.

  1. .NET Standard: .NET Standard is a formal specification of APIs that are common across different .NET implementations. It defines a set of base class libraries and APIs that must be available in all .NET platforms supporting that specific version of .NET Standard.

Example:

csharp
// .NET Standard class library public class MyStandardLibrary { public string GetMessage() { return "Hello from .NET Standard!"; } }
  1. Portable Class Libraries (PCL): Portable Class Libraries provide a way to create libraries that can be used across different .NET platforms. PCLs allow developers to target a specific set of platforms, and the library can be used in any project that supports those platforms.

Example:

csharp
// Portable Class Library public class MyPortableLibrary { public string GetMessage() { return "Hello from Portable Class Library!"; } }
  1. Sharing Code using NuGet Packages: NuGet is a package manager for .NET that allows developers to create and share packages containing libraries, tools, and other assets. By creating and publishing NuGet packages, developers can easily share code across different projects and platforms.

Example:

csharp
// NuGet package public class MyNuGetPackage { public string GetMessage() { return "Hello from NuGet package!"; } }
  1. Multi-targeting in .NET Core: Multi-targeting is a feature in .NET Core that allows developers to target multiple frameworks within a single project file. This enables code sharing across different platforms and versions of .NET Core.

Example:

xml
<!-- .NET Core project file --> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFrameworks>netstandard2.0;netcoreapp3.1</TargetFrameworks> </PropertyGroup> </Project>

Conclusion: Code sharing in .NET Core through .NET Standard, Portable Class Libraries, NuGet packages, and multi-targeting allows developers to maximize code reuse and improve development efficiency across different platforms and versions of .NET Core. This promotes modular and scalable software development practices.

Post a Comment

0 Comments