Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cannot initialize type with a collection initializer

Tags:

c#

I have a class Options.

public class Option
{                
    public bool Aggregation { get; set; }
    public PropertyOptions Property { get; set; }
    public bool DoEvent { get; set; }
}

PropertyOptions goes like this..

public enum PropertyOptions
{        
    [EnumMember]
    On = 0,     
    [EnumMember]
    Off = 1,
    [EnumMember]        
    Auto = 2,
}

Now I have a method which return an object of a class Option

Option setOptions()
{
        return new Option()
        {
            Aggregation = true,                
            Property = new PropertyOptions()
            {
                PropertyOptions.Auto,
            },                                       
            DoEvent = true,
       };
}

Here I am getting an error which says "Cannot initialize type PropertyOptions with a collection initializer because it does not implement System.Collection.IEnumerable"

I am not sure about how to set data member 'Property'. It would be helpful if someone can drove my attention to what could be the possible error and how do I correct it?

like image 246
Quick-gun Morgan Avatar asked May 01 '26 05:05

Quick-gun Morgan


2 Answers

You need to use regular assignment.

new Option()
{
    Aggregation = true,                
    Property = PropertyOptions.Auto,                                   
    DoEvent = true
}

The syntax you were attempting to use is for collection initialization. For example:

var list = new List<string>
{
    "apple",
    "banana"
};

Your Property property is not a collection.

like image 88
Timothy Shields Avatar answered May 03 '26 11:05

Timothy Shields


The New Operator is for instantiating objects from Classes. You are using an Enum, which is not a Class.

You should be able to just use an assignment operator.

new Option()
{
    Aggregation = true,                
    Property = PropertyOptions.Auto,                                   
    DoEvent = true
};
like image 20
Eddie Avatar answered May 03 '26 10:05

Eddie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!