0

Lets say I have the class:

class Foo
{
    public Foo(int value)
    {
        this.Value = value;
    }
    public int Value { get; private set; }        
}

I will like to do the following:

var f = new Foo(1);
f = 5; // How can I do this? In here I want to change => f.Value
var x = f.Value; // I will like x to equal to 5 in here
Tono Nam
  • 34,064
  • 78
  • 298
  • 470

2 Answers2

6

In C# you can't override the assign operator (=).

What you can do is defines implicit conversions:

class Foo
{
    public Foo(int value)
    {
        this.Value = value;
    }
    public int Value { get; private set; }

    public static implicit operator Foo(int value)
    {
        return new Foo(value);
    }
}

This allows you implicitly convert from int to Foo:

Foo f = 5;

Here is a list of overloadable Operators in C#.

Arturo Menchaca
  • 15,783
  • 1
  • 29
  • 53
1

From what I understood from your question, if you really need to change the value of Value, why don't you make the setter of Value public, so that you can just use, f.Value = 5

user836846
  • 74
  • 2