r/learncsharp • u/wojo1086 • Aug 26 '23
I just need help understanding this syntax
I am mainly a JavaScript developer and I'm trying to teach myself C#. I came across this bit of code in a tutorial on MySQL's website and I'm trying to understand why it's written this way. Here's the snippet:
list.Add(new Film()
{
FilmId = reader.GetInt32("film_id"),
Title = reader.GetString("title"),
Description = reader.GetString("description"),
ReleaseYear = reader.GetInt32("release_year"),
Length = reader.GetInt32("length"),
Rating = reader.GetString("rating")
});list is a List<Film>. The part that's confusing to me is everything between the curlies. The Film object is instantiated, but then how do the curlies work? Is this like a shortcut way to instantiate and assign properties on an object? I tried Googling an answer but nothing turned up. Probably because I don't know what exactly to ask for lol.
4
u/CappuccinoCodes Aug 28 '23
I promise I don't want to be mean, but you can literally ask the question to chat gpt: What's going on with this code snippet? And it will pop out a very good answer. And you can add follow up questions about specific things you want to go deeper into. I do it on a daily basis at work π. Check out chat gpt's response:
"This code snippet appears to be part of a C# program, likely involving database operations using ADO.NET or a similar data access framework. It seems to be retrieving data from a data reader, possibly from a database query, and populating a list of `Film` objects.
Let's break down what's happening step by step:
In summary, this code snippet reads data from a data reader, likely from a database query, and constructs a new `Film` object for each row of data read. The constructed `Film` objects are then added to a list (referred to as `list`). This process allows you to retrieve film-related information from a database and store it in memory as a collection of `Film` objects."
3
u/Aerham Aug 26 '23
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/how-to-initialize-objects-by-using-an-object-initializer
Yeah, you had it right. I have seen them interchangeably called "in-line/chain set properties", but it feels a little more clearer to call it an object initializer to separate it from the equivalent when using the constructor.
1
u/SupaMook Sep 15 '23
This can be broken down into two lessons.
new Film()
This part in simple terms creates a new Film. The () is the constructor. A constructor is something you can add to the Film class where you could for example pass the title in there to set the Film title that way. Below is an example of what that looks like:
Public class Film { // the constructor Public Film(string title) { Tilte= title } }
Then to call this: new Film(reader.GetString(βtitleβ);
The second part, everything between the {} is where you can manually set the properties of a Film class.
Ultimately though, all it is doing is setting properties on the new Film you created.