Reputation: 153
When creating objects in Java I'm used to the following syntax:
objectX1 = new ObjectX(some arguments);
While looking over a project in C# I came across the following code:
_createSample = new Func<SampleBase>[]
{
() => new SkeletonMappingSample();
}
I need two things explained to me. First, how does creating an object without the brackets and parameter list and instead using {} with expressions work?
Next, what does the expression between the {} mean?
Upvotes: 0
Views: 164
Reputation: 31202
This code creates an array of Func : _createSample = new Func<SampleBase>[]
Then it instantiates one lambda expression () => new SkeletonMappingSample()
as the sole element in it, using collection initializer (note the braces, and the semicolon is optional):
{
() => new SkeletonMappingSample();
}
This expression will instantiate a new SkeletonMappingSample when called :
var newMappingSample = _createSample[0]();
Upvotes: 1
Reputation: 6220
The code you found:
_createSample = new Func<SampleBase>[]
{
() => new SkeletonMappingSample();
}
Is just a notation for creating an array and then initialising it with values.
Which is effectively the same as:
_createSample = new Func<SampleBase>[1];
_createSample[0] = () => new SkeletonMappingSample();
Except that in the { }
version the bounds are set by the compiler based on how many elements you've added between the { }
For objects:
SomeClass abc = new SomeClass()
{
SomeProperty = "SomeValue",
}
Is just a way of creating an object and then setting some property values, it's effectively the same as:
SomeClass abc = new SomeClass();
abc.SomeProperty = "SomeValue";
Upvotes: 3