954,514 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

what is the purpose of anonymous constructor?

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

johndoe444
Posting Whiz in Training
214 posts since Feb 2008
Reputation Points: 11
Solved Threads: 0
 

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.

Venjense
Light Poster
31 posts since Oct 2003
Reputation Points: 13
Solved Threads: 5
 

>what is the purpose of anonymous constructor?

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

__avd
Posting Genius (adatapost)
Moderator
8,648 posts since Oct 2008
Reputation Points: 2,136
Solved Threads: 1,241
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You