C# Method shorthand with anonymous delegate

Question:

Please tell me how to implement Here is the source code

vm.RegisterCommand('+', v => Inc(v));
private static void Inc(IVirtualMachine v)
{
    if (v.Memory[v.MemoryPointer] == (char)255)
        v.Memory[v.MemoryPointer] = (char)0;
    else
        v.Memory[v.MemoryPointer]++;
}

I want to replace it with something like

vm.RegisterCommand('+', b => (b.Memory[b.MemoryPointer] == 255) ? 1 : 2 );

at 1:2, ignore this to shorten the code

Answer:

Well, you essentially have modulo addition, so instead of if you can write something like v.Memory[v.MemoryPointer] = (char)((v.Memory[v.MemoryPointer] + 1) % 256) , well, respectively, in the form of a lambda:

vm.RegisterCommand('+', v =>
    v.Memory[v.MemoryPointer] = (char)((v.Memory[v.MemoryPointer] + 1) % 256));

If IVirtualMachine.Memory is really a byte array, then the code can be shortened:

vm.RegisterCommand('+', v => v.Memory[v.MemoryPointer]++));

If you want to rewrite your method verbatim, then it would look like this:

vm.RegisterCommand('+', v =>
{
    if (v.Memory[v.MemoryPointer] == (char)255)
        v.Memory[v.MemoryPointer] = (char)0;
    else
        v.Memory[v.MemoryPointer]++;
});

But this does not improve readability, but rather the opposite.

And using the ternary operator, for example, like this:

vm.RegisterCommand('+', v =>
    v.Memory[v.MemoryPointer] = (char)(v.Memory[v.MemoryPointer] == 255
                                       ? 0
                                       : (v.Memory[v.MemoryPointer] + 1)
                                      ));
Scroll to Top