Search code examples
c#resharpernullablenotnull

How can I prevent a "Possible 'null' assignment to entity marked with 'NotNull' attribute" when dynamically adding a column to a DataTable?


I've got this code:

dtAddrInfo.Columns.Add(new DataColumn("Address", Type.GetType("System.String")));

...which Resharper barks about, saying, "Possible 'null' assignment to entity marked with 'NotNull' attribute"

What is wrong with the code?

Even when I let Resharper adjust the code with its various suggestions:

dtAddrInfo.Columns.Add(new DataColumn("Address", dataType: System.Type.GetType("System.String")));
dtAddrInfo.Columns.Add(new DataColumn("City", System.Type.GetType("System.String")));
dtAddrInfo.Columns.Add(column: new DataColumn("State", Type.GetType("System.String")));

...it still bitterly complains about the same thing in the same way on each of those lines.

It doesn't prevent compilation, but I still like to be Mr. Clean where possible.


Solution

  • This:

    System.Type.GetType("System.String")
    

    can return null, because you are doing a String lookup of a Type that may not exist, you should use:

    typeof(System.String)
    

    Then it ought to stop complaining.