Hi,

I came across this code snippet:

new { genre = genreName }

I am not sure what is the name of this thing and how this thing works?

Thanks

Recommended Answers

All 2 Replies

Hi,

I came across this code snippet:

new { genre = genreName }

I am not sure what is the name of this thing and how this thing works?

Thanks

Hmmm, not sure i f this is enough to go on, although I think the code snippet should be

Genre myGenre = new Genre{ genre = genreName };

This would instantiate an object of Genre and set the property genre to genreName. It seems to be called anonymous constructor alot but is also known as Object Initializer. It allows access to the properties without an overloaded constructor.

In the Genre example

public class Genre
    {
        string genre { get; set; }
        string description { get; set; }
        public Genre()
        {
            //empty constructor, never do this :P
        }
    }

Instead of doing this

Genre myGenre = new Genre();
myGenre.genre = SomeGenre;
mygenre.description = SomeDescrioption;

I can do this

Genre myGenre = new Genre {genre = SomeGenre, description = SomeDescription};
Genre myOtherGenre = new Genre {genre = SomeOtherGenre};

anonymous constructor AKA Object Initializer gives a nice example.

commented: Very likely exactly what's going on. Good example :) +1

>what is the purpose of anonymous constructor?

That is called Anonymous Types not an anonymous constructor. Read this thread.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.