Start New Discussion within our Software Development Community

In the code below I can't understand the line

List<Surface> sfcStars = new List<Surface>();
What's going on here, and what are "<>" those doing in the code, I've never seen the before.
I got this code from http://www.tuxradar.com/beginnerscode

using System;
using SdlDotNet.Graphics;
using System.Collections.Generic;
using System.Drawing;

namespace TroutWars
{
	
	
	class Starfield
	{
		List<Surface> sfcStars = new List<Surface>();
		
		public Starfield()
		{
			sfcStars.Add(new Surface("content/stardark.bmp"));
			sfcStars.Add(new Surface("content/starmedium.bmp"));
			sfcStars.Add(new Surface("content/starbright.bmp"));
		}

}
}

List<T> is a strongly-typed collection of objects of type T. In your example, you have a collection of Surface objects.

List<int> ints;
List<string> strings;
List<double> doubles; 
List<Foo> foos;

It is a "generic" collection. Generics were introduced to C# and .NET in the 2.0 release. Prior to that, you might have an ArrayList to hold a collection of objects, but the collection would not be strongly typed. As a result, you could put anything in it. While that might certainly be nice, it's not convenient when you want to only work with objects of a single type. Also, the contents are stored in an ArrayList as type object , so there would be boxing and unboxing anytime you added to or accessed from the collection. With a List<T>, you can only put elements of type T in the list. There's no boxing or worries about anything being in there that should not be. For your example code, the only thing that can go in there are objects of type Surface.

For more information on List<T>, see this link. http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx

For more on generics, go here. http://msdn.microsoft.com/en-us/library/0sbxh9x2(v=VS.90).aspx

This article has been dead for over six months. Start a new discussion instead.