views:

175

answers:

4
public class PhotoList : ObservableCollection<ImageFile>
{


    public PhotoList() { }

    **//this is the line that I  dont recognise!!!!!!!!!!**
    public PhotoList(string path) : this(new DirectoryInfo(path)) { }

    public PhotoList(DirectoryInfo directory)
    {
        _directory = directory;
        Update();
    }

    public string Path
    {
        set
        {
            _directory = new DirectoryInfo(value);
            Update();
        }
        get { return _directory.FullName; }
    }

    public DirectoryInfo Directory
    {
        set
        {
            _directory = value;
            Update();
        }
        get { return _directory; }
    }
    private void Update()
    {
        foreach (FileInfo f in _directory.GetFiles("*.jpg"))
        {
            Add(new ImageFile(f.FullName));
        }
    }

    DirectoryInfo _directory;
}
+14  A: 

This is called constructor chaining - constructors can call other constructors within the same type with this syntax (using this for sibling constructors and base for base constructors).

Here is a simple example that shows how it works:

using System;

class Program
{
    static void Main()
    {
     Foo foo = new Foo();
    }
}

class Foo
{
    public Foo() : this("hello")
    {
     Console.WriteLine("world");
    }

    public Foo(String s)
    {
     Console.WriteLine(s);
    }
}

Output:

hello
world

Andrew Hare
Never seen this before either. Initially seems like a poor design choice as the calling code doesn't see the chained constructor? Could be wrong
Nick Allen - Tungle139
@Nick Allen The chaining is considered an internal (implementation) issue of the class, so the caller shouldn't know. You could for instance have two public constructors chaining to a shared private constructor
krosenvold
+1  A: 

It makes the constructor that takes a string parameter invoke the constructor that takes a DirectoryInfo parameter, passing a new DirectoryInfo object (which in turn is using the string as parameter) to it.

I often use this approach to provide simpler constructors to complex classes, letting the class itself initializse properties with default values without having to duplicate intitiallization code.

Fredrik Mörk
+2  A: 

It calls the other constructor in the class that takes a DirectoryInfo as argument.

Lets see how the caller of this class can be used

//The empty ctor()
PhotoList list = new PhotoList();

//The ctor that takes a DirectoryInfo
PhotoList list2 = new PhotoList(new DirectoryInfo("directory")); 

//Would do the same as the code above since this constructor calls another constructor via the this() keyword
PhotoList list3 = new PhotoList("directory");
Kenny Eliasson