I would like to switch the type of generic parameter and I have found one way to do it that works and pass the test (*1) (Edited: this approach doesn't work for string, check @dbc's comment):
public static string HelpWithThis<T>(this DummyClass<T> _)
=>
(T)default! switch // <- Code smell (in my opinion)
{
DateOnly => "This day",
TimeOnly => "This hour",
int or float => "This number",
_ => "This",
};
However, I am not fond of using type casting for default!.
Could someone kindly guide me on how to rewrite this function in a more elegant syntax?
Test
(*1) I paste here the whole test and instructions to reproduce:
dotnet new xunit -o gentyp
cd gentyp
dotnet add package FluentAssertions
// UnitTest1.cs
using FluentAssertions;
namespace gentyp;
public class DummyClass<T>{}
public static class DummyExtensions
{
public static string HelpWithThis<T>(this DummyClass<T> _)
=>
(T)default! switch
{
DateOnly => "This day",
TimeOnly => "This hour",
int or float => "This number",
_ => "This",
};
}
public class UnitTest1
{
[Fact]
public void Test1()
=>
new DummyClass<int>()
.HelpWithThis()
.Should()
.Be("This number");
}
As an alternative to overloaded methods you could go old-school and use a static lookup table to convert a type into a string:
static readonly Dictionary<Type, string> _lookup = new ()
{
[typeof(DateOnly)] = "This day",
[typeof(TimeOnly)] = "This time",
[typeof(int)] = "This number",
[typeof(float)] = "This number"
};
public static string HelpWithThis<T>(this DummyClass<T> _)
{
return _lookup.TryGetValue(typeof(T), out var result)
? result
: "This";
}
I personally prefer your original solution (as long as it's not being used with large structs!) but you might prefer this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With