Is the following use of 'dynamic', in the method IsUnixNewline, good or bad?
using System;
class Program
{
static void Main()
{
byte[] bytes = { 32, 32, 32, 10 };
string text = "hello\n";
for (int i = 0; i < bytes.Length; ++i) {
if (IsUnixNewline(bytes, i)) {
Console.WriteLine("Found Unix newline in 'bytes'.");
break;
}
}
for (int i = 0; i < text.Length; ++i) {
if (IsUnixNewline(text, i)) {
Console.WriteLine("Found Unix newline in 'text'.");
break;
}
}
}
static bool IsUnixNewline(dynamic array, int index)
{
return array[index] == '\n' && (index == 0 || array[index - 1] != '\r');
}
}
I would say "yes" - dynamic
is not required here, and adds a lot of uncertainty about what it will do at runtime (and, of course, throws away static compiler checking); better to just use a few overloads in this case, IMO:
static bool IsUnixNewline(char[] array, int index)
{
return array[index] == '\n' && (index == 0 || array[index - 1] != '\r');
}
static bool IsUnixNewline(byte[] array, int index)
{
return array[index] == '\n' && (index == 0 || array[index - 1] != '\r');
}
static bool IsUnixNewline(string array, int index)
{
return array[index] == '\n' && (index == 0 || array[index - 1] != '\r');
}
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