Reputation: 132
I certainly want to assign value directly to my class instance (implicitly to one of its properties), but besides overloading assignment operator (which is forbidden?), I found only conversion operator, which is kind of what I need, but it doesn't account the "assignee" instance in any way (instead it creates and assigns new object, with all that it implies).
public class Foo
{
public bool b = true;
public float f = 1f;
public float f2 = 10f;
public float value
{
get => b? f : f2;
set => b? f : f2;
}
public Foo(bool useFirstFloat, float f)
{
this.b = first;
this.value = f;
}
public static implicit operator float(Foo foo) => foo.f;
public static implicit operator Foo(float f) => new Foo(true, f); //bool is always "overwritten"
public float this[bool useInstance] //For ugly workaround example
{
get => value;
set => useInstance? value : new Foo(false, value); //now with false
}
}
Example:
Foo foo = new Foo(false, 100f); //bool must stay "false" after assignment
float f = 5f;
void SomeFunc()
{
foo.value = f; //I want this, but not this way!
foo = f; //Instead I want this to be the same thing as "foo.value = f" (not "foo = new Foo(b, f)"!)
foo[true] = f; //Like this but without index parameter
foo[false] = f; //Not this, again!
}
So in ideal I need something like this:
public static Foo operator =(Foo foo, float f) //Why is this so forbidden?
{
foo.value = f;
return foo;
}
Is there any way to do so? Any thoughts on possibility of this in C#?
Upvotes: 0
Views: 131
Reputation: 132
The simple answer is: NO (use C++). But there's hack to implement similar behaviour (unsafe)!
public class Foo
{
public bool b = true;
public float f = 1f;
public float f2 = 10f;
public static Foo current;
public float value
{
get
{
current = this;
return b? f : f2;
}
set
{
current = this;
if (b) f = value; else f2 = value;
}
}
public static implicit operator float(Foo foo) => foo.f;
public static implicit operator Foo(float f)
{
current.value = f;
return current;
}
}
Unfortunately, at this moment it's not possible in C# by default, and actually forbidden. But no matter what the dogma dicts, there's sudden lack of functional that appears like a snag while everything is fine, so I've opened an issue, for anybody can see what it leds to.
UPD: Issue was merged with some barelated stuff, but there is some discussion.
Upvotes: 0