Search code examples
c#.netvisual-studiofilehelpers

How to avoid warning CS0649 while using FileHelpers Module


I am using the FileHelpers nuget to read the files. It works as excepted but it throws me a warning when I tried to debug in Visual Studio.

How to get rid of warning CS0649: Field 'Orders.Freight' is never assigned to, and will always have its default value null ?

 class Orders : INotifyRead
{
    [FieldFixedLength(10)]
    public string Freight;
    public void BeforeRead(BeforeReadEventArgs e)
    {
        if (e.RecordLine.StartsWith("Machine"))
            // ||
            // e.RecordLine.StartsWith("-"))
            e.SkipThisRecord = true;
    }
    public void AfterRead(AfterReadEventArgs e)
    {
        //  we want to drop all records with no freight
        if (Freight == "_raw")
            e.SkipThisRecord = true;
    }
}

Solution

  • No, do not explicitly assign a default value to Freight.

    The warning is legitimate, because you never really assign a value to the field.

    You do not assign a value, because the field gets populated by magic. (Incidentally, that's why I do not like magic; but that's a different story altogether.)

    So, the best approach is to acknowledge the fact that the warning is legitimate but accounted for, and to explicitly suppress it.

    So, take a look at the documentation of the #pragma warn directive: https://msdn.microsoft.com/en-us/library/441722ys.aspx