What does a constructor do with an empty body and syntax like inheritance?

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;
}
+3
source share
3 answers

This is called a chaining constructor — constructors can call other constructors of the same type with this syntax (using sibling constructors and basic constructors). this base

Here is a simple example showing 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

+19
source

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

Let's see how you can use the caller of this class

//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");
+2
source

, , , DirectoryInfo, DirectoryInfo (, , ).

I often use this approach to provide simpler constructors for complex classes, allowing the class itself to initialize properties with default values ​​without the need to duplicate intitiallization code.

+1
source

Source: https://habr.com/ru/post/1708481/


All Articles