Rex M
Rex M

Reputation: 144122

ambiguous/conflicting constructors in generic class

I've got a generic class:

public class BaseFieldValue<T>
{
    public BaseFieldValue()
    {
        //...
    }

    public BaseFieldValue(string value)
    {
        //...
    }

    public BaseFieldValue(T value)
    {
        //...
    }
}

Fine. Except...

var myValue = new BaseFieldValue<string>("hello");

Oops. The undesired constructor is called. There's a number of ways to address the problem. What's the best solution?

Upvotes: 2

Views: 1010

Answers (5)

rick schott
rick schott

Reputation: 21117

Couldn't make Type Contraints do what I wanted, so my workaround is removing the ambiguous constructor while retaining the special case for string:

public class BaseFieldValue<T>
{
    public BaseFieldValue()
    {
        //...
    } 

    public BaseFieldValue(T value) 
    {
        //however many things you need to test for here
        if (typeof(T) == typeof(string))
        {
            SpecialBaseFieldValue(value.ToString());
        }
        else
        {
            //everything else
        }
        //...
    }

    private void SpecialBaseFieldValue(string value)
    {
        //...
    }

}

Upvotes: 1

Amit
Amit

Reputation: 1057

May be you can try thi:

var myValue = new BaseFieldValue<Object>("hello" as Object);  

Upvotes: 0

LukeH
LukeH

Reputation: 269418

A nasty hack, but probably no worse than any of the alternatives:

public class BaseFieldValue<T>
{
    public BaseFieldValue()
    {
        // ...
    }

    public BaseFieldValue(StringWrapper value)
    {
        // ...
    }

    public BaseFieldValue(T value)
    {
        // ...
    }

    public class StringWrapper
    {
        private string _value;

        public static implicit operator string(StringWrapper sw)
        {
            return sw._value;
        }

        public static implicit operator StringWrapper(string s)
        {
            return new StringWrapper { _value = s };
        }
    }
}

And now it can be used as you need:

// call the generic constructor
var myValue = new BaseFieldValue<string>("hello");

// call the string constructor
var myValue = new BaseFieldValue<int>("hello");

Upvotes: 0

ChrisW
ChrisW

Reputation: 56113

You could do the following:

public class BaseFieldValue<T>
{
    public struct Special
    {
        internal string m_value;
        public Special(string value)
        {
            m_value = value;
        }
    }

    public BaseFieldValue()
    {
        //...
    }

    public BaseFieldValue(Special value)
    {
        //...
    }

    public BaseFieldValue(T value)
    {
        //...
    }
}

... or, you could add an extra ignored boolean parameter to your special constructor, just to disambiguate it.

Upvotes: 2

Joshua Flanagan
Joshua Flanagan

Reputation: 8557

I would probably make one of the overloads into a factory method:

public static BaseFieldValue<T> Parse(string value){}

Upvotes: 7

Related Questions