This course will be retired on June 1, 2025.
Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Preview
Start a free Courses trial
to watch this video
Learn about a feature that makes it easy to initialize objects.
Related Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign upRelated Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign up
So far we've been dealing with
a collection of integers.
0:00
Let's dive in and start dealing with
collections of more complex objects.
0:04
I'm back in workspaces, and
let's start the C# REPL.
0:08
Let's review a nifty feature of the C#
language, object initialization.
0:15
We'll be working with
a birdwatching dataset,
0:21
so we can create a Bird class with
some auto properties to start.
0:24
Public class Bird.
0:28
Public string Name,
0:34
get; set.
0:40
public string, how about a Color,
0:43
get; set; and then let's do an integer,
0:48
let's say public int Sightings.
0:54
So that's how many times
the bird has been sighted.
0:59
And close that.
1:05
Okay, now let's add
some data to work with.
1:10
Earlier you saw how we initialized
a list of integers with some values.
1:13
Let's do the same here,
but using bird objects.
1:17
We can initialize the list and
each bird object within the list.
1:21
List of Bird birds
equals new List of Bird.
1:24
And then a curly brace.
1:34
And we'll give it a new Bird,
1:38
another curly brace,
1:42
Name = Cardinal and the Color is Red, and
1:46
Sightings equals, we'll say 3.
1:52
Okay, so that's our first Bird object,
comman, and then we'll do one more.
1:59
New Bird.
2:04
And its Name will be Dove,
2:07
Color = White and
2:13
Sightings = 2.
2:18
Okay.
2:22
Then one more curly brace,
okay, we've got some birds.
2:23
Now we have a list of birds
that has two Bird objects.
2:31
Well, we can also add more birds to
it with the Add method, birds.Add.
2:34
And using the same convention,
2:41
we can say Add new Bird Name = Robin.
2:46
Color equals, well, they're mostly red.
2:51
And the Sightings = 5.
2:55
Okay, now we've got three birds.
3:02
And the way I did that, that's the same
thing as creating a new bird like this.
3:04
We'll say Bird blueJay = new Bird,
3:09
blueJay.Name = Blue Jay.
3:17
blueJay.Color = Blue.
3:24
And blueJay.Sightings = 1.
3:31
Then we still have to add it,
so birds.Add blueJay.
3:39
Okay, now we should have four
birds in our birds list.
3:44
Let's do a foreach Bird bird in birds,
3:51
then we'll print out
the name to the console.
3:56
Console.WriteLine bird.Name,
4:02
then close that.
4:08
And there's our birds.
4:12
You need to sign up for Treehouse in order to download course files.
Sign upYou need to sign up for Treehouse in order to set up Workspace
Sign up