That's right, after learning from the defendants, a short answer to the question "Is there a way to use the extension method in the object initializer block in C #?" " No. "
The way I ended up solving the problem I came across (similar, but more complicated, that the toy problem I asked here) was a hybrid approach, as follows:
I created a subclass like
public class SubClassedDataObject : BaseDataObject { public int Bar { get { return (int)GetData("bar"); } set { SetData("bar", value); } } }
Which works great in LINQ, the initialization block looks like
SubClassedDataObject testSub = new SubClassedDataObject { SomeValue = 3, SomeOtherValue = 4, Bar = 5 };
But the reason I did not like this approach, first of all, is that these objects are placed in XML and returned as BaseDataObject, and discarding will be annoying, an unnecessary copy of the data and put two copies of the same object in the game.
In the rest of the code, I ignored subclasses and applied extension methods:
public static void SetBar(this BaseDataObject dataObject, int barValue) { dataObject.SetData("bar", barValue); } public static int GetBar(this BaseDataObject dataObject) { return (int)dataObject.GetData("bar"); }
And it works well.
Anthony
source share