Phil
Phil

Reputation: 627

How to constrain a copy constructor in C#?

For a simple example, I have this copy constructor in C#:

            public Vector2D(Vector2D v)
            {
                m_x = v.m_x;
                m_y = v.m_y;
            }

Because I want to constrain the argument to not be modified by mistake, I tried adding 'const' after '('.

For example, I would like something like this:

            public Vector2D(const Vector2D v)
            {
                // v.m_x++;  Can't do this mistake anymore
                m_x = v.m_x;
                m_y = v.m_y;
            }

However, I noticed in C# it does not allow this. If you can imagine methods being very large as I have seen in C++, this makes sense to have this constraint option.

What is the alternative?

Upvotes: 0

Views: 365

Answers (2)

amin
amin

Reputation: 581

you can not use const for method parameter in C#. const can be used for local variables and fields. but if you want limit change value you should limit setter in properties.you can create interface and limit setter and implement interface in your class .

Look at this Code:

public interface ISampleInterface
{
    string Value1 { get; }
    string Value2 { get; }
}
public class Sample : ISampleInterface
{
    private string _Value1;
    public string Value1
    {
        get { return _Value1; }
        set { _Value1 = value; }
    }

    private string _Value2;
    public string Value2
    {
        get { return _Value2; }
        set { _Value2 = value; }
    }

    public Sample()
    {

    }
    public Sample(ISampleInterface sample)
    {
        //sample.Value1 = 14; not possible
        this.Value1 = sample.Value1;
        this.Value2 = sample.Value2;

    }
}

Upvotes: 1

Vikhram
Vikhram

Reputation: 4404

First off, the const keyword does not work the same way in C++ and C#. In C#, there is no direct equivalent of the behavior you expect. In fact, we cannot stop any method from modifying the object passed in as an argument, unless the object is immutable with respect to that method.

Let's assume that the Vector2D is a class (reference type) as opposed to a struct (value type). In such cases, unless you make the class immutable, there is no way to way to prevent them from being modified.

A very simple implementation of such class would be

class Vector2D {
    readonly int x_, y_;

    public int X { get { return x_; } }
    public int Y { get { return y_; } }

    public Vector2D(int x, int y) {
        x_ = x;
        y_ = y;
    }

    public Vector2D Clone(Vector2D vector) {
        return new Vector2D(vector.X, vector.Y);
    }
}

Usually in such classes, you would end up overriding the Equals, GetHashcode and the comparison operators == and !=

Upvotes: 4

Related Questions