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.

3
  • "This doesn't compile correctly" what error are you getting? Commented Feb 11, 2010 at 1:01
  • 2
    Others have addressed the specific issue of chaining constructors. What I would like to add is a design critique. It feels very wrong to be calling a Save() method from a constructor. Constructors should really do as little as possible other than initializing the object. Commented Feb 11, 2010 at 1:08
  • Sorry I didn't specify earlier. The Class is named SaveFile. It's just a serializable form of the data structure. Commented Feb 11, 2010 at 1:20

3 Answers 3

6

You have the wrong syntax for calling an overloaded constructor from within the default constructor.
To call an overloaded constructor in the same class, 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);
}
Sign up to request clarification or add additional context in comments.

1 Comment

See! I knew it was something simple that I was missing!
2
 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"))
    { 
    } 

Comments

1

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")
{
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.