Object and collection initializes.

R

Rene

It seems simple enough to use objects initializers to initialize object
properties and collection intitializers to initialize collection, what I
have not been able to figure out is a way to initialize object properties
and collections at the same time.

By the way, I don't have a need to do that, I am simply curious if that is
doable or not. See snippet below.

Thank you.

class Program
{
static void Main(string[] args)
{
// Initialize property no problem.
var col2 = new MyCollection() { SomeProp = 123 };

// Initialize collection no problem.
var col1 = new MyCollection() { 1, 2, 4 };

// Initialize proerty and collection how????
//var p = new Pupu() {{ X = 123 }{1,2,3}};
}
}

class MyCollection : System.Collections.IEnumerable
{
private int m_SomeProp;
public int SomeProp
{
get { return m_SomeProp; }
set { m_SomeProp = value; }
}

internal void Add(object i)
{
}

System.Collections.IEnumerator
System.Collections.IEnumerable.GetEnumerator()
{
// Prevent compiler error.
return null;
}
}
 
J

Jeroen Mostert

Rene said:
It seems simple enough to use objects initializers to initialize object
properties and collection intitializers to initialize collection, what I
have not been able to figure out is a way to initialize object
properties and collections at the same time.
Bottom line: you can't combine them. If the collection is itself a settable
property you can initialize and assign one, but if it's a read-only property
or the object you're initializing is itself a collection you'll have to do
it the hard way.

It's not a bad idea to give a collection type a constructor that takes an
IEnumerable<> of values to add, and an .AddRange() to do the same after
construction. Some (but not all) standard collection types have this. Using
this you *can* combine collection initialization and property assignment, if
not through an actual collection initializer.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top