Search code examples
c#castingimplicit-conversion

Implicit conversion in C# without creating new object


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 Stringto 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?


Solution

  • 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:

    1. First convert "some string" into a PathSelector (through the conversion operator)
    2. Assign the new object to the property

    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";