Skip to content

Commit

Permalink
Introduction of LanguageTypeConverter.
Browse files Browse the repository at this point in the history
  • Loading branch information
Corniel committed Jun 17, 2024
1 parent 0843ca7 commit 91cd053
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 2 deletions.
21 changes: 21 additions & 0 deletions src/CodeAnalysis.TestTools/Conversion/LanguageTypeConverter.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
using System.ComponentModel;

namespace CodeAnalysis.TestTools.Conversion;

/// <summary>Implements a <see cref="TypeConverter"/> for <see cref="Language"/>.</summary>
internal sealed class LanguageTypeConverter : TypeConverter
{
/// <inheritdoc />
[Pure]
public override bool CanConvertFrom(ITypeDescriptorContext? context, Type sourceType)
=> sourceType == typeof(string) || base.CanConvertFrom(context, sourceType);

/// <inheritdoc />
[Pure]
public override object? ConvertFrom(ITypeDescriptorContext? context, CultureInfo? culture, object value) => value switch
{
null => Language.None,
string str => Language.Parse(str),
_ => base.ConvertFrom(context, culture, value),
};
}
7 changes: 5 additions & 2 deletions src/CodeAnalysis.TestTools/Language.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
namespace CodeAnalysis.TestTools;
using System.ComponentModel;

namespace CodeAnalysis.TestTools;

/// <summary>Represents a (code) language.</summary>
[TypeConverter(typeof(Conversion.LanguageTypeConverter))]
public readonly struct Language : IEquatable<Language>
{
/// <summary>None.</summary>
Expand Down Expand Up @@ -77,7 +80,7 @@ public static Language Parse(string? str)
{
"" or null => None,
"CSHARP" or "CS" or "C#" or ".CS" => CSharp,
"VB" or "VBNET" or "VISUALBASIC" or ".VB" => VisualBasic,
"VB" or "VB.NET" or "VBNET" or "VISUALBASIC" or ".VB" => VisualBasic,
"FSHARP" or "FS" or "F#" or ".FS" => FSharp,
"XML" or "EXTENSIBLEMARKUPLANGUAGE" or ".XML" => XML,
_ => throw new FormatException(Messages.Language_InvalidFormat),
Expand Down

0 comments on commit 91cd053

Please sign in to comment.