C # object constructor overloads

I am trying to create an overloaded constructor for a class. I think this should be pretty simple, however I cannot get it to work.

Any ideas?

    public SaveFile(string location)
    {
        // Constructor logic here
        //TODO: Implement save event.
        this.Save(location);
    }

    public SaveFile()
    {
        string location = Environment.GetFolderPath(Environment.SpecialFolder.Personal) + "\\SaveFile.DAT";
        SaveFile(location);
    }

This does not compile correctly, and I cannot figure out how to do this.

+3
source share
3 answers

You have the wrong syntax for invoking an overloaded constructor from the default constructor.
To invoke an overloaded constructor in the same class, use this syntax:

public ClassName(parameters) : this(otherParameters)
{
   // logic
}

If you want to call the constructor in the base class, you should use the keyword baseinstead this. In your case, the code will read:

public SaveFile() : this(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "SaveFile.DAT") {}
public SaveFile(string location)
{
    this.Save(location);
}
+6
source
 public SaveFile() 
   : this(Environment.GetFolderPath(Environment.SpecialFolder.Personal) + "\\SaveFile.DAT")
    { 
    } 

:

 public SaveFile() 
   : this(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal),"SaveFile.DAT"))
    { 
    } 
+2

public SaveFile(string location)
{
    // Constructor logic here
    //TODO: Implement save event.
    this.Save(location);
}

public SaveFile(): this(Environment.GetFolderPath(Environment.SpecialFolder.Personal) + "\\SaveFile.DAT")
{
}
+1

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


All Articles