Not exactly how sure how to title this question, so I hope the title works.
The question is, can I use something similar to implicit type syntax on method calls. For example, this is the implicit type syntax I am referring to:
var x = new Y(){Foo = "Bar", Id = 1};
And I want to do something like this:
var x = myInstance.CreateItem(){Foo = "Bar", Id = 1};
Is there anything in C# that supports something like this? I don’t want to do:
x.Foo = "Bar";
x.Id = 1;
...
Please note that CreateItem returns a dynamic type. The CreateItem method and its class cannot be modified.
I would settle for something similar to the With statement in VB.
Thanks in advance.
UPDATE: Attempting Mark Brackett’s solution yielded this code:
TaskItem item = outlook.CreateItem(OlItemType.olTaskItem)._((Action<dynamic>)(i =>
{
i.Subject = "New Task";
i.StartDate = DateTime.Now;
i.DueDate = DateTime.Now.AddDays(1);
i.ReminderSet = false;
i.Categories = "@Work";
i.Sensitivity = OlSensitivity.olPrivate;
i.Display = true;
}));
…
public static class Extension
{
public static T _<T>(this T o, System.Action<dynamic> initialize) where T : class
{
initialize(o);
return o;
}
}
The only problem now is that the extension method doesn’t seem to be binding to System._ComObject because I get this error: System._ComObject’ does not contain a definition for ‘_’.
It’s called an “object initializer”, and no – it’s not available for return values (or really, anytime other than with a
newstatement).Syntax wise, about the closest I can think of would be to use an
Actiondelegate (which requires changes to theBuilder):If you’re in a JavaScripty mood for short method names for commonly used functions, and can’t change the
Builder, I guess an extension method would also work:Contrary to my comment,
dynamicdoes require a few changes. You need to cast toobjector the lambda will complain, and then you need to specifydynamicasTor it’ll be inferred asobject. Or, create your extension method withAction<dynamic>and no type arguments.