CA1903: Use only API from targeted framework
TypeName |
UseOnlyApiFromTargetedFramework |
CheckId |
CA1903 |
Category |
Microsoft.Portability |
Breaking Change |
Breaking - when fired against the signature of an externally visible member or type. Non breaking - when fired in the body of a method. |
Cause
A member or type is using a member or type that was introduced in a service pack that was not included with the project's targeted framework.
Rule Description
New members and types were included in .NET Framework 2.0 Service Pack 1 and 2, .NET Framework 3.0 Service Pack 1 and 2, and .NET Framework 3.5 Service Pack 1. Projects that target the major versions of the .NET Framework can unintentionally take dependencies on these new APIs. To prevent this dependency, this rule fires on usages of any new members and types that were not included by default with the project's target framework.
Target Framework and Service Pack Dependencies
When target framework is |
Fires on usages of members introduced in |
.NET Framework 2.0 |
.NET Framework 2.0 SP1, .NET Framework 2.0 SP2 |
.NET Framework 3.0 |
.NET Framework 2.0 SP1, .NET Framework 2.0 SP2, .NET Framework 3.0 SP1, .NET Framework 3.0 SP2 |
.NET Framework 3.5 |
.NET Framework 3.5 SP1 |
.NET Framework 4 |
N/A |
To change a project's target framework, see Targeting a Specific .NET Framework Version or Profile.
How to Fix Violations
To remove the dependency on the service pack, remove all usages of the new member or type. If this is a deliberate dependency, either suppress the warning or turn this rule off.
When to Suppress Warnings
Do not suppress a warning from this rule if this was not a deliberate dependency on the specified service pack. In this situation, your application might fail to run on systems without this service pack installed. Suppress the warning or turn this rule off if this was a deliberate dependency.
Example
The following example shows a class that uses the type DateTimeOffset that is only available in .NET 2.0 Service Pack 1. This example requires that .NET Framework 2.0 has been selected in the Target Framework drop-down list in the Project properties.
using System;
namespace Samples
{
public class LibraryBook
{
private readonly string _Title;
private DateTimeOffset _CheckoutDate; // Violates this rule
public LibraryBook(string title)
{
_Title = title;
}
public string Title
{
get { return _Title; }
}
public DateTimeOffset CheckoutDate // Violates this rule
{
get { return _CheckoutDate; }
set { _CheckoutDate = value; }
}
}
}
The following example fixes the previously described violation by replacing usages of the DateTimeOffset type with the DateTime type.
using System;
namespace Samples
{
public class LibraryBook
{
private readonly string _Title;
private DateTime _CheckoutDate;
public LibraryBook(string title)
{
_Title = title;
}
public string Title
{
get { return _Title; }
}
public DateTime CheckoutDate
{
get { return _CheckoutDate; }
set { _CheckoutDate = value; }
}
}
}