Why is the Tags
property of Book
empty after this code runs?
class Program
{
static void Main(string[] args)
{
List<Book> books = new List<Book>();
List<String> tags = new List<String> {"tag1", "tag2", "tag3"};
String title = "a title";
books.Add(new Book
{
Title = title,
Author = "an author",
Tags = tags
});
Console.WriteLine("(" + title + ")");
Console.WriteLine((books[0]).Tags.Count());
title = String.Empty;
tags.Clear();
Console.WriteLine("(" + title + ")");
Console.WriteLine((books[0]).Tags.Count());
}
}
The code for Book
:
public class Book
{
public String Title { get; set; }
public String Author { get; set; }
public List<String> Tags { get; set; }
}
Running this code outputs
("a title")
3
()
0
Are tags
and title
being passed by reference here? Renaming the respective properties produces the same output.
EDIT:
I just realised that I meant for every Console.WriteLine
statement to refer to the object, not just the tags one. I meant this:
Book aBook = books[0];
Console.WriteLine("(" + aBook.Title + ")");
Console.WriteLine(aBook.Tags.Count());
title = String.Empty;
tags.Clear();
Console.WriteLine("(" + aBook.Title + ")");
Console.WriteLine(aBook.Tags.Count());
which as expected, outputs:
("a title")
3
("a title")
0
but since I made a mistake in my initial question, I'm leaving it as is since the parts of the answers that refer to title
are referencing the original code.