Why doesn't this extension method set the value it's applied to?
public static byte ExtSetBits(this byte original, byte value, byte bitSize)
{
unchecked { original &= (byte)~bitSize; }
original |= (byte)(value & bitSize);
return original;
}
This is the call ( selectedIndex = 13 ):
byte test = 0xFF;
test.ExtSetBits(selectedIndex, 0x1F);
Console.WriteLine("test:" + test.ToString("X").PadLeft(2,'0'));
Writes "test: FF" to the console.
If I do this it works:
byte test = 0xFF;
test = test.ExtSetBits(selectedIndex, 0x1F);
Console.WriteLine("test:" + test.ToString("X").PadLeft(2,'0'));
Writes "test: ED" to the console. I shouldn't have to reassign the variable right? I've written many other extensions.
Am I missing something?
Yes - you're not using the return value of the method in your first snippet. All you need is to set the return value, just as you're doing in the working case (your second code snippet). Changing the value of the parameter makes no difference, because it's a by-value parameter. The fact that you're using an extension method is irrelevant here.
Imagine your code was actually just:
ExtensionClass.ExtSetBits(test, selectedIndex, 0x1F);
After all, that's what the compiler is converting your code to. If you ignore the fact that it's an extension method (which you should, as it's irrelevant here) would you expect that to change the value of test
? To do that, you'd need to pass it by reference (with ref
) - but an extension method's first parameter isn't allowed to have the ref
modifier.
You might want to read my article about parameter passing for a bit more background, along with my article about value types and reference types.
byte
is a value type. test
and original
are both distinct values, modifying one does not modify the other.
You are not modifying the value of the test in your function. The parameter is a copy of your variable, you are changing it's value and then returning it. If you want to manipulate the variable then you should use ref
modifier but the first parameter of extension method can't be declared as ref
.