majk86
majk86

Reputation: 125

Initialize a new instance of the class through its method

Got this class with lots of properties. There`s constructor which sets properties to its default values and Clear method. (Clear method here is just an example)

public class Person
{
    public string A;
    public string B;
    public string C;
    ...
    public string Z;

    public Person()
    {
        this.A = "Default value for A";
        this.B = "Default value for B";
        this.C = "Default value for C";
        ...
        this.Z = "Default value for Z";
    }

    public void Clear()
    {
        this = new Person(); // Something like this ???
    }
}

How can I reinitialize class through Clear method?

I mean:

Person p = new Person();

p.A = "Smething goes here for A";
p.B = "Smething goes here for B";
...
// Here do stuff with p
...

p.Clear(); // Here I would like to reinitialize p through the Clear() instead of use p = new Person();

I know I could write a function with all the default values settings and use it in constructor and in Clear method. But... is there a "proper" way instead of workarounds?

Upvotes: 2

Views: 176

Answers (2)

user1967122
user1967122

Reputation: 63

I don't know what you want , but I would do it like this :

   public class Person
{
    public string A;
    public string B;
    public string C;
    ...
    public string Z;

    public Person()
    {
        ResetToDefault();
    }

    public void ResetToDefault()
    {
        this.A = "Default value for A";
        this.B = "Default value for B";
        this.C = "Default value for C";
        ...
        this.Z = "Default value for Z";
    }
}

well , at some point you must give the parameters their values.

When you want to reset it to default.. just do this :

Person person = new Person();
//do your stuff here .....
//when reset it:
person.ResetToDefault();

Upvotes: 1

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186688

I'd rather implement initializer:

public class Person
{
    public string A;
    public string B;
    public string C;
    ...
    public string Z;

    private void Ininialize() {
      this.A = "Default value for A";
      this.B = "Default value for B";
      this.C = "Default value for C";
      ...
      this.Z = "Default value for Z";
    }

    public Person()
    {
       Ininialize();
    }

    public void Clear()
    {
       Ininialize();
    }
}

....

Person p = new Person();
...
p.A = "Something goes here for A";
p.B = "Something goes here for B";
...
p.Clear(); // <- return A, B..Z properties to their default values

Upvotes: 5

Related Questions