Daniel Neel Daniel Neel - 1 month ago 13
C# Question

Is it possible to increment/decrement a value in a DataRow using C#'s operators?

It looks like it's only possible to increment a value by saying:

DataRow someRow = GetRow();
someRow[0] = someRow[0] + 10;


Is there any way to perform this operation in C#? I can't seem to find anything...I'm assuming this is because a DataRow.Item returns an object.

DataRow someRow = GetRow();
someRow[0] += 10;
someRow[0] -= 10;
someRow[0] *= 5;

Answer

Is there any way to perform this operation in C#?

No, you have first to cast or convert the someRow[0] to the corresponding type and then you can use addition, multiplication, etc.

The following would result in a compilation error:

someRow[0] = someRow[0] + 10;

since someRow[0]'s type is Object while 10 is an integer literal.

The correct approach would be something like the following:

someRow[0] = (int)someRow[0] + 10;
Comments