tags:

views:

76

answers:

3
+1  Q: 

Generics syntax

Here is some code that I can't seem to understand how it works. I know it is using generics but what does the "new" in the where clause mean?

public class MediaPresenter<T>
    where T : Media, new()
{
    public MediaPresenter(string mediaPath, params string[] extensions)
    {
        _mediaPath = mediaPath;
        _fileExtensions = extensions;
    }

    private void LoadMedia()
    {
        if(string.IsNullOrEmpty(_mediaPath)) return;

        _media = new ObservableCollection<Media>();
        DirectoryInfo directoryInfo = new DirectoryInfo(_mediaPath);

        foreach(string extension in _fileExtensions)
        {
            FileInfo[] pictureFiles = directoryInfo.GetFiles(
                extension,
                SearchOption.AllDirectories
                );

            foreach(FileInfo fileInfo in pictureFiles)
            {
                if(_media.Count == 50) break;

                T media = new T();
                media.SetFile(fileInfo);
                _media.Add(media);
            }
        }
    }
}

I also don't understand in the LoadMedia method how the T is used? Can the T get referenced anywhere in the class?

+1  A: 

new() means that T needs to have a parameterless constructor. (In this case it also needs to inherit the Media class)

Jeroen Landheer
+6  A: 

Here is some code that I can't seem to understand how it works. I know it is using generics but what does the "new" in the where clause mean?

The new() in the where clause means that T must be of a type that can be instantiated. If T does not have a parameterless constructor, T is not a valid type to pass to this class as a type parameter.

See http://msdn.microsoft.com/en-us/library/sd2w2ew5.aspx.

I also don't understand in the LoadMedia method how the T is used? Can the T get referenced anywhere in the class?

Yes. T is a type parameter of the class, so the whole class knows about it. It would also be valid to have a field in the class that was of type T, or a method that returned T, for example.

sassafrass
A: 

T is the specific type used when this class is instantiated. For instance if you were to declare

MediaPresenter<Media> myMediaPresenter = new MediaPresenter<Media>();

Then the T would become Media and the line you inquire about would get translated at run-time into something like

Media media = new Media();

because when we declared the class above we made the generic type argument equal to Media.

Hope that helps

Jeffrey Cameron