Skip to content

Commit

Permalink
Added CLS compliant constructor. Added unit test.
Browse files Browse the repository at this point in the history
  • Loading branch information
JoshClose committed Oct 11, 2022
1 parent d714192 commit d2f66a7
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 6 deletions.
11 changes: 9 additions & 2 deletions src/CsvHelper/Configuration/Attributes/TypeConverterAttribute.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,15 @@ public class TypeConverterAttribute : Attribute, IMemberMapper, IParameterMapper
/// Specifies the <see cref="TypeConverter"/> to use
/// when converting the member to and from a CSV field.
/// </summary>
/// <param name="typeConverterType"></param>
/// <param name="constructorArgs"></param>
/// <param name="typeConverterType">The type of the <see cref="ITypeConverter"/>.</param>
public TypeConverterAttribute(Type typeConverterType) : this(typeConverterType, new object[0]) { }

/// <summary>
/// Specifies the <see cref="TypeConverter"/> to use
/// when converting the member to and from a CSV field.
/// </summary>
/// <param name="typeConverterType">The type of the <see cref="ITypeConverter"/>.</param>
/// <param name="constructorArgs">Type constructor arguments for the type converter.</param>
public TypeConverterAttribute(Type typeConverterType, params object[] constructorArgs)
{
if (typeConverterType == null)
Expand Down
26 changes: 22 additions & 4 deletions tests/CsvHelper.Tests/Mappings/Attribute/TypeConverterTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,14 @@ public void TypeConverterOnStructReferenceTest()
}
}

[Fact]
public void Constructor_TypeConverterWithConstructorArgs_Creates()
{
var attribute = new TypeConverterAttribute(typeof(TypeConverterWithConstructorArgs), 2);
Assert.IsType<TypeConverterWithConstructorArgs>(attribute.TypeConverter);
Assert.Equal(2, ((TypeConverterWithConstructorArgs)attribute.TypeConverter).Value);
}

private class TypeConverterClass
{
public int Id { get; set; }
Expand All @@ -86,22 +94,32 @@ public string ConvertToString(object value, IWriterRow row, MemberMapData member
}
}

public class AClass
private class AClass
{
public int Id { get; set; }
[TypeConverter(typeof(StringTypeConverter))]
public BClass Name { get; set; }
}

public class BClass { }
private class BClass { }

public class AStruct
private class AStruct
{
public int Id { get; set; }
[TypeConverter(typeof(StringTypeConverter))]
public BStruct Name { get; set; }
}

public class BStruct { }
private class BStruct { }

private class TypeConverterWithConstructorArgs : DefaultTypeConverter
{
public int Value { get; private set; }

public TypeConverterWithConstructorArgs(int value)
{
Value = value;
}
}
}
}

0 comments on commit d2f66a7

Please sign in to comment.