Reputation: 8398
I am getting a code analysis warning that seems to be a false-positive.
CA1812 : Microsoft.Performance : 'MyClass.MyPrivateClass' is an internal class that is apparently never instantiated. If so, remove the code from the assembly. If this class is intended to contain only static methods, consider adding a private constructor to prevent the compiler from generating a default constructor.
How do I get rid of this warning? I prefer to not suppress warnings unless I am sure I couldn't avoid it otherwise.
The classes look like this:
namespace Some.Namespace
{
public class MyClass
{
private class MyPrivateClass
{
public int Id { get; set; }
public ModelObject { get; set; }
}
}
}
I use it like this:
private IQueryable<MyPrivateClass> GetMyPrivateClasses()
{
return this.Repository().All()
.Select(m => new MyPrivateClass { Id = m.Id, ModelObject = m };
}
Does this usage not count as instantiation?
Upvotes: 17
Views: 12489
Reputation: 891
The only thing that worked for me was adding propertygroup and nowarn to the project in question:
<PropertyGroup>
<NoWarn>CA1812</NoWarn>
</PropertyGroup>
Upvotes: 0
Reputation: 21
FYI there is a new documentation page for this warning:
https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca1812
Instantiation of classes is not always recognized by analyzers.
Suppress this warning, if justified:
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses", Justification = "generic/late bound/reflection")]
Happens especially in Net.Core.
Upvotes: 1
Reputation: 440
Change your class to internal or public, that solves the problem. Anyway, you can extract your inner class from the outer class...
Upvotes: -1
Reputation: 1062895
I guess it is examining the IL; and genuinely - that IL does not ever contain a new MyPrivateClass
instruction - because that statement is presumably running against IQueryable<T>
, hence that lambda is an expression tree. It will contain some Expression.New
, and some typeof(MyPrivateClass)
- but no new MyPrivateClass
.
In this case, the error is misleading. Simply suppress it.
Upvotes: 22