Skip to content

[API Proposal]: Generic math Assign operators #60536

@msedi

Description

@msedi

Background and motivation

Currently C# implements the += the same way as a a regular +. Which is OK for simple value types. But if the objects are getting large an intermediate copy needs to be created, although the intention is to reuse the existing object. Assume you have a dataset A with 50GB and another B with 50GB, then the operations

var C = A +B;
var A += B;

are the same. First of all it would be benefial to allow += as a seperate operator. Additionally the new generic math ideas could also add AddAssign, etc. Originally the workaround was to implement this yourself, but when this is already under consideration it would be good to also take a look at this topic.

Interestingly Expression already has AddAssign, etc. But if honestly have never tested if there is a different code generation.

API Proposal

namespace System
{
    public interface IFloatingPoint<T> 
    {
        public T AddAssign(T item);
        public T SubtractAssign(T item);
        public T DivideAssign(T item);
        public T MulAssign(T item);
    }
}

API Usage

var A = new Volume(2048, 2048, 1000);
var B = new Volume(2048, 2048, 1000);

A.AddAssign(B);

// Of course it would be nice if this would also work.
A += B;

Alternative Designs

No response

Risks

One problem is that I already needed this implementations and did it myself. While this works for my purposes I found the problem with very long running operations (e.f. +) that there is not way to cancel the process (for example with a CancellationToken).

I assume that you don't want to do this, and honestly I would do neither in this case. I just wanted to mention this because I stumbled across this problem.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions