What is/are the best way to handle primitive type polymorphism in c# ? I'm stumbling on a lot of case where this is a question I have issues to answer in c#. I'm more proficient in java where it's never been an issue. C# offer a lot of possibilities but none seems right in a lot of use case.
I've tried dynamic, but stumbled on some case where the behavior was not the same as expected and it feels a bit dangerous if not completely understood. So I started considering it as a last resort option if none was satisfying.
In a lot of case, the best option i found is to test for each type and perform the cast manually... at least it is the safest option. But this seem to be a bad option in most case. It would not annoy me so much with a low level language but it feels wrong in c#
One examples that annoys me the most is when calling a method that accept multiple types. Here is an example with BitConverter.GetBytes(...) .
/// <summary>
/// assign an object to Int16 registers
/// object must be of type handled by BitConverter
/// BitConverter.GetBytes() is used
/// </summary>
/// <param name="value">value to convert</param>
/// <returns>the value in Int[] registers format</returns>
/// <exception cref="NotSupportedException">type is not supported</exception>
public static Int16[] FromValue(object value)
{
try
{
byte[] bytes = BitConverter.GetBytes(value);
Int16[] registers = FromByteArray(bytes);
return registers;
}
catch (Exception e)
{
throw new NotSupportedException("Provided type is not supported", e);
}
}
This code doesn't work because I need to call GetBytes with the right type. how would you do in this case ? Is there a good general rule regarding this kind of issue ? Is there a must read article about this kind of issue I'm having ?
Edit: Relating to the preferred answer, I think one of my issue is that Generics seems to be more important in c# than in Java and I've not used them a lot. Still wondering about use case were dynamic should be used instead though.