Reputation: 8099
I'm trying to implement some implicit cast for an object. Currently I'm doing this:
public class PathSelector
{
private string _path = null;
public string Path
{
get { return _path; }
set
{
if (value != _path)
{
_path = value;
OnPropertyChanged("Path");
}
}
}
static public implicit operator string(PathSelector pathSelector)
{
return pathSelector.Path;
}
static public implicit operator PathSelector(string path)
{
return new PathSelector() { Path = path };
}
}
As you can see in the cast from String
to PathSelector
I'm generating a new PathSelector
object.
I use it like this:
public PathSelector PluginPathSelector { get; set; } = new PathSelector();
public string PluginPath
{
get
{
return PluginPathSelector;
}
set
{
PluginPathSelector = value;
}
}
What I don't like about this solution is, that I always create a new object when I assign a string to a PathSelector
object. This also means, that in the PathSelector
property a set
section is needed. I would like to assign the string
to the object, that is already created. Is there a way to implement this?
Upvotes: 3
Views: 2345
Reputation: 575
For the sake of completeness and as a hacking way, you can handle that by using the ugly way of:
Upvotes: 1
Reputation: 391704
I finally understood what you wanted to do.
You wanted this:
x.PluginPathSelector = "some string";
To directly change the Path property of the existing object inside x.PluginPathSelector
, instead of constructing a new PathSelector
instance and assigning to x.PluginPathSelector
.
In other words, you want this:
x.PluginPathSelector = "some string";
to be silently handled as though you wrote:
x.PluginPathSelector.Path = "some string";
But from within the static conversion operator:
static public implicit operator PathSelector(string path)
And no, this cannot be done, because this is a conversion operator.
This statement:
x.PluginPathSelector = "some string";
is handled this way:
"some string"
into a PathSelector
(through the conversion operator)The conversion operator implementation have no way to reach or know about the target of the object it returns, be it a property or a variable or whatever.
So no. This cannot be done.
You will have to manually do the change yourself if you want to avoid constructing new instances all the time.
x.PluginPathSelector.Path = "some string";
Upvotes: 2