Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

False CA1812 warning : "internal class that is apparently never instantiated..."

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?

like image 399
Niel de Wet Avatar asked Aug 14 '13 08:08

Niel de Wet


People also ask

Is an internal class that is apparently never instantiated?

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 ignore warnings in C#?

Use a #pragma warning (C#) or Disable (Visual Basic) directive to suppress the warning for only a specific line of code.


1 Answers

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.

like image 172
Marc Gravell Avatar answered Sep 18 '22 14:09

Marc Gravell