views:

84

answers:

1

I have a property of type IEnumerable<SomeClassIWrote> in a user control. When I use this control in a GUI, the .Designer.cs file contains the line:

theObject.TheProperty = new SomeClassIWrote[0];

Which for some reason causes a compiler warning:

Object of type 'SomeClassIWrote[]' cannot be converted to type
'System.Collections.Generic.IEnumerable`1[SomeClassIWrote]'.

Which is a mystery to me because I pass arrays as IEnumerables all the time, and the compiler has never complained.

For what it's worth, I have a default value of null specified for the property, but I got the same error before I set a default value.

How can I fix this so Visual Studio doesn't complain and ask me to ignore and continue every time I pull up the designer?


Code for the property:

[DefaultValue(null)]
public IEnumerable<SomeClassIWrote> TheProperty {
    get { 
        return _theProperty; 
    }
    set {
        if (value == null) {
            _theProperty = new SomeClassIWrote[] { };
        }
        else {
            _theProperty = value;
        }
    }
}
+4  A: 

First up, do you WANT to be able to set it in the designer?

If not, add the following attributes:

    [Browsable(false)]
    [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]

If you DO want to set in the designer, I'd start out by trying your class as a SomeClassIWrote[], to see if that works.

That aside, is it that important to use an IEnumerable here? As you say, you can pass arrays as IEnumerables.

I suspect there's probably some restrictions inside the designer, which wiser people than me know about...

And if you really DO want an IEnumerable property, you can expose your array as an IEnumerable, but keep your array as a designer-friendly backing field.

Benjol
IEnumerable is propably a bad idea, come to think of it, but when I tried to use ReadOnlyCollection<SomeClassIWrote>, Visual Studio blew up in a series of neverending dialogs warning me that code generation failed and I had to kill the process.
Daniel Straight
Exactly. IEnumerable<T> is an immutable class, which means the visual designer *cannot* support it. If you have an immutable property, you almost certainly don't want it showing up in the designer, so just hide it.
Aaronaught
Fast enough with the comment, too slow with an answer
Arthur