Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this an abuse of 'dynamic'?

Tags:

c#

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');
    }
}
like image 857
Tom Avatar asked Aug 25 '11 07:08

Tom


1 Answers

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');
    }
like image 102
Marc Gravell Avatar answered Oct 29 '22 22:10

Marc Gravell