0

I've got an issue with changing attribute at runtime.

I'm using https://www.filehelpers.net/ to handle csv but I think this problem is similar for any other custom attributes.

There is a class representing entity:

[DelimitedRecord("\t")]
public class FileHelper
{
    [FieldNotEmpty]
    public string Id = "1";
    public string Name = "Product1"
}

This class is used as generic parameter for file reading engine. What I want to do is to change DelimitedRecord("\t") to a runtime value eg. semicolon .

I know that I can use below code to get attributes but only read.

DelimitedRecordAttribute[] attributes = (DelimitedRecordAttribute[]) typeof(FileHelper).GetCustomAttributes(typeof(DelimitedRecordAttribute), false);

Is there option to change attribute value or remove it and add new attribute new value?

chalwa
  • 82
  • 9
  • No (ignoring the TypeDescriptor stuff). Look for a different way of configuring your CSV library, or use a common one such as CsvHelper. – canton7 Apr 16 '20 at 12:39
  • @canton7 it would be easy in new application, but there is ton of legacy code. I'm fixing hardcoded value in DelimitedRecord – chalwa Apr 16 '20 at 12:43
  • Does this answer your question? [Change Attribute's parameter at runtime](https://stackoverflow.com/questions/51269/change-attributes-parameter-at-runtime) – jason.kaisersmith Apr 16 '20 at 12:50
  • @jason.kaisersmith I was reading this post. "attributes" variable above is similar. but instead of "MyData" used in example, Delimiter property is ReadOnly, so line below won't compile. attributes[0].Separator = ";"; – chalwa Apr 16 '20 at 12:58
  • Second option I consider is to remove with typeof(FileHelper).GetCustomAttributesData().RemoveAt(0); an then add new with typeof(FileHelperDeviceCsv).GetCustomAttributesData(). But I don't know how to make an instance of CustomAttributeData – chalwa Apr 16 '20 at 13:15
  • 2
    @chalwa You cannot edit the attributes on a type. You can't do it. Just as you can't add types to an assembly at runtime, or remove types, or add methods to types, etc etc. – canton7 Apr 16 '20 at 13:26
  • @canton7 Thank you for answer. I need to find solution somewhere else in code. – chalwa Apr 16 '20 at 13:30

0 Answers0