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;
}
views:
175answers:
4This 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
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.
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");