Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there anyway to reconstruct an object inside itself?

Tags:

c#

.net

I have a simple class that is intended for options of an winforms application. There should be a method that reset options to their default values. I know I can add a separate method to take care of this, but the code will be huge (If I add more options to the class) :

public SensorOptions()
{
    ShowLabelMax = ShowLabelMin = ShowLabelAvr = ShowReceivedTextBox = true;

    ChartMaxValue = 140;
    ChartMinValue = -40;

    ShowChartMinValue = ShowChartMaxValue = ShowChartAvrValue = ShowChartAvrLine = true;

    LogFolder = Environment.SpecialFolder.MyDocuments.ToString();
    LoggingEnabled = true;
}

public void ResetOptions()
{
    this = new SensorOptions(); //can not do. 'this' is read-only
}

I mean I can copy/paste the code from constructor into ResetOptions() method. But is there any smarter ways to achieve this?

like image 715
Saeid Yazdani Avatar asked Dec 24 '22 18:12

Saeid Yazdani


2 Answers

You cannot assign this because you may have references to this instance of your class in your program. If you could re-construct the object by re-assigning this, it would mean that all references to the old instance of the class become invalid.

No matter how many options you have in your class, you initialize each of them one or the other way (because you mention default value in your question - so you need to assign that default value somewhere at least once, probably in the constructor). Therefore, the solution to your problem is simple - move all initializers to the separate method and call it in the constructor, and then also call it every time you need to reset your options to their default values.

If any of your options are not assigned a default value explicitly, and use system default and you don't want to write option=default(optionType) for each option, you can use reflection to enumerate all fields/properties in that class and assign default values to them, like this:

public static object GetDefault(Type type)
{
   if(type.IsValueType) return Activator.CreateInstance(type);
   return null;
}
foreach(var field in this.GetType().GetFields())
    field.SetValue(this, GetDefault(field.FieldType));
foreach(var prop in this.GetType().GetProperties())
    prop.SetValue(this, GetDefault(prop.PropertyType));
like image 98
Denis Yarkovoy Avatar answered Dec 31 '22 14:12

Denis Yarkovoy


Move all of the code from the constructor into the ResetOptions method, then in your constructor call the ResetOptions method. Your initialisiation code is only in one place then.

like image 35
Lee Willis Avatar answered Dec 31 '22 13:12

Lee Willis