Based on http://alexreg.wordpress.com/2009/05/03/strongly-typed-csv-reader-in-c/, I created a DLL which can read different file types. I also have unit tests that run successfully. I create a struct and use it as the generic type.
Anyway, when I compile, I get a warning on each of the struct fields. For example: field 'FileReader.Tests.CsvReader.Record.Field1' is never assigned to, and will always have its default value 0
I am in fact setting the value with SetValueDirect() and when I run through the tests or debug the code, I can verify that. Why is it giving me that error then, and how can I avoid or fix it?
Here is some basic code to give you an idea. I'm guessing I haven't provided enough, but hopefully someone has a clue.
public abstract class FileReader<TRecord> : IDisposable where TRecord : struct
{
public TRecord? ReadRecord()
{
List<string> fields;
string rawData;
this.recordNumber++;
while (this.ReadRecord(this.fieldTypeInfoList.Length, out fields, out rawData))
{
try
{
// Insert the current record number to the beginning of the field list
fields.Insert(0, this.recordNumber.ToString(CultureInfo.InvariantCulture));
// Convert each field to its correct type and set the value
TRecord record = new TRecord();
FieldTypeInfo fieldTypeInfo;
object fieldValue;
// Loop through each field
for (int i = 0; i < this.fieldTypeInfoList.Length; i++)
{
fieldTypeInfo = this.fieldTypeInfoList[i];
bool allowNull = fieldTypeInfo.AllowNull == null ? this.AllowNull : fieldTypeInfo.AllowNull.Value;
if (i >= fields.Count && !allowNull)
{
// There are no field values for the current field
throw new ParseException("Field is missing", this.RecordNumber, fieldTypeInfo, rawData);
}
else
{
// Trim the field value
bool trimSpaces = fieldTypeInfo.TrimSpaces == null ? this.TrimSpaces : fieldTypeInfo.TrimSpaces.Value;
if (trimSpaces)
{
fields[i] = fields[i].Trim();
}
if (fields[i].Length == 0 && !allowNull)
{
throw new ParseException("Field is null", this.RecordNumber, fieldTypeInfo, rawData);
}
try
{
fieldValue = fieldTypeInfo.TypeConverter.ConvertFromString(fields[i]);
}
catch (Exception ex)
{
throw new ParseException("Could not convert field value", ex, this.RecordNumber, fieldTypeInfo, rawData);
}
fieldTypeInfo.FieldInfo.SetValueDirect(__makeref(record), fieldValue);
}
}
return record;
}
catch (ParseException ex)
{
ParseErrorAction action = (ex.FieldTypeInfo.ParseError == null) ? DefaultParseErrorAction : ex.FieldTypeInfo.ParseError.Value;
switch (action)
{
case ParseErrorAction.SkipRecord:
continue;
case ParseErrorAction.ThrowException:
throw;
case ParseErrorAction.RaiseEvent:
throw new NotImplementedException("Events are not yet available", ex);
default:
throw new NotImplementedException("Unknown ParseErrorAction", ex);
}
}
}
return null;
}
}