Using implicit type syntax when returning a method

It’s not entirely accurate what to call this question, so I hope the title will work.

The question is, can I use something similar to implicit type syntax when calling a method. For example, this is the syntax of an implicit type, which I mean:

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 do not want to do:

x.Foo = "Bar";
x.Id = 1;
...

Note that CreateItem returns a dynamic type. The CreateItem method and its class cannot be changed.

I would agree to something like statement C in VB.

Thanks in advance.

UPDATE: Attempting to solve Mark Brackett gave 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;
    }

}

, System._ComObject, : System._ComObject ' ' _ '.

+3
3

" " , - ( , , new).

, , , Action ( Builder):

MyItem CreateItem(Action<MyItem> afterCreate) {
   var i = new MyItem();
   if (afterCreate != null) afterCreate(i);
   return i;
}

var x = Builder.CreateItem(i => { i.Foo = "Bar"; i.Id = 1; });

JavaScripty Builder, , :

public static T _<T>(this T o, Action<T> initialize) where T : class {
    initialize(o);
    return o;
}

var x = Builder.CreateItem()._(i => { i.Foo = "Bar"; i.Id = 1; });

. CreateItem()

, dynamic . object, , dynamic T object. Action<dynamic> .

object CreateItem() {
    return (object)Builder.CreateItem();
}

public static dynamic __(this object o, Action<dynamic> initialize) {
    initialize(o);
    return o;
}

var x = CreateItem().__(i => { i.Foo = "Bar"; i.Id = 1; });
+2

factory:

public static Y Builder.CreateItem(string foo = "", int bar = 0)
{
    return new Y() {Foo = foo, Bar = bar};
}

// called like so:
var x = Builder.CreateItem(Foo: "Bar", Id: 1);
+1

You can specify "public properties" in the constructor of the class, but you cannot do this using methods

because

  • These rules apply only to member properties, which is not possible using methods

  • You cannot publish modofier in fields in a method, so there is no atall option

When you do

var a = new MyClass{Foo="",Id=""};

You define the class properties of this constructor MyClass ()

You cannot do this using the static or instance method

0
source

All Articles