I have various derived objects that I would like the user to be able to use object initializers with. I have an "Initializing" property that I want to be true as those fields are being set and then I want the Initializing property to be set to false afterward.
How can I tell when the object initializer is done to be able to do this?
class Foo
{
Public Foo(string p1, string p2)
{
Initializing = true;
Property1 = p1;
Property2 = p2;
Initializing = false;
}
bool Initializing;
string _property1;
string Property1
{
get { return _property1; }
set { _property1 = value; DoSomething(); }
}
string Property2 { get; set; }
public void DoSomething()
{
if(Initializing) return; // Don't want to continue if initializing
// Do something here
}
}
In the above example, it works fine if you use the constructor. How to make it work the same way with an object initializer is the problem though.
EDIT: For all you naysayers, here's someone else looking for exactly what I'm after - http://blogs.clariusconsulting.net/kzu/how-to-make-object-initializers-more-useful/
Unfortunately it does look likes it's an impossibility though.
If you really need to track initialization of your object then you need to implement that logic manually. One approach is to copy that used by the WinForms code generator. Where objects expose the ISupportInitialize interface when they want properties to be updated in a batch. So usage would be something like...
var x = new Foo();
x.BeginInit();
x.Property1 = 1;
x.Property2 = 2;
x.EndInit();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With