-
Notifications
You must be signed in to change notification settings - Fork 5.1k
Open
Labels
area-System.ComponentModeluntriagedNew issue has not been triaged by the area ownerNew issue has not been triaged by the area owner
Description
Description
Targeting .NET 8
. When trying out some built-in TypeConverter
classes, we got some unexpected results. E.g. StringConverter and Int32Converter can convert to their own types, but the same is not true for e.g. NullableConverter and DateTimeConverter.
How come the contract differs for built-in type converters? Is this intended behavior or some undocumented feature?
Example
using System.ComponentModel;
namespace TypeConverterTest;
internal class Program
{
static void Main(string[] args)
{
var types = new Type[]
{
typeof(string),
typeof(CultureInfo),
typeof(int),
typeof(int?),
typeof(DateTime),
typeof(DateTime?),
};
foreach (var type in types)
{
string typeName = GetFriendlyName(type);
var conv = TypeDescriptor.GetConverter(type);
bool result = conv.CanConvertTo(null, type);
Console.WriteLine($"{typeName,-20} CanConvertTo() == {result}");
}
}
private static string GetFriendlyName(Type type)
{
if (type.IsGenericType)
{
var namePrefix = type.Name.Split(['`'], StringSplitOptions.RemoveEmptyEntries)[0];
var genericParameters = type.GetGenericArguments().Select(GetFriendlyName);
return namePrefix + "<" + string.Join(", ", genericParameters) + ">";
}
return type.Name;
}
}
Output
String CanConvertTo() == True
CultureInfo CanConvertTo() == False
Int32 CanConvertTo() == True
Nullable<Int32> CanConvertTo() == False
DateTime CanConvertTo() == False
Nullable<DateTime> CanConvertTo() == False
Reproduction Steps
See sample code.
Expected behavior
Some additional documentation needed? Or should all TypeConverters be capable of converting to/from their own types?
Actual behavior
Inconsistent return values for CanConvertTo()
.
Regression?
No response
Known Workarounds
No response
Configuration
No response
Other information
No response
Metadata
Metadata
Assignees
Labels
area-System.ComponentModeluntriagedNew issue has not been triaged by the area ownerNew issue has not been triaged by the area owner