tags:

views:

151

answers:

3

I'm trying to have an overloaded constructor for a class. I think this should be fairly simple, however I can't seem to make it 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 doesn't compile correctly, and I can't figure out how to do make it work.

+6  A: 

You have the wrong syntax for calling an overloaded constructor from within the default contructor. To call an overloaded contructor contained in the same class definition use this syntax:

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

If you wanted to call a constructor in the base class, then you would use the base keyword instead of this. In your case the code would read:

public SaveFile() : this(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "SaveFile.DAT") {}
public SaveFile(string location)
{
    this.Save(location);
}
Qua
See! I knew it was something simple that I was missing!
WedTM
+1  A: 

Try this

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

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

However that really should be:

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