1

How would you create an extension method which enables me to do the following (warning: exteme pseudo-code)...

class FooBar
{
    Int32 Foo { get; set; }
    String Bar { get; set; }
}

new FooBar().With(fb => new Func<FooBar, Object>(instance =>
{
    // VB With magic
    // NOTE: The instance parameter HAS to be by reference
    instance.Foo = 10;
    instance.Bar;

    return new Object();
}));

If you could specify anonymous functions without a return type (void), the above would look much cleaner...

new FooBar().With(fb => new Func<FooBar, void>(instance =>
{
    instance.Foo = 10;
    instance.Bar;
}));

This is pseudo-code of the worst kind. But I hope you get the idea.

0

4 Answers 4

4

To specify anonymous methods without return type, use Action<T> instead of Func<T, TResult>:

new FooBar().With(new Action<FooBar>(instance =>
{
    instance.Foo = 10;
    instance.Bar;
}));

(I don't quite see the point in this particular case, but I take your word on the pseudo code part...)

Update
Full example for being complete:

The extension method:

public static void With<T>(this T input, Action<T> action)
{
    action(input);
}

Sample usage

new FooBar().With(fb =>
{
    fb.Foo = 10;
    fb.Bar = "some string";
});

Note that you don't need to explicitly declare the Action<FooBar>, the compiler figures that out. Should you wish to, for clarity, the call would look like this:

new FooBar().With<FooBar>(new Action<FooBar>(fb =>
{
    fb.Foo = 10;
    fb.Bar = "some string";
}));
Sign up to request clarification or add additional context in comments.

1 Comment

How would the extension method look like?
2

Maybe this will help:

new FooBar().With( fb=> {
    fb.Foo = 10;
    fb.Bar = fb.Foo.ToString();
} );

// ... somewhere else ...
public static void With<T>( this T target, Action<T> action ) {
    action( target );
}

4 Comments

oh snap! you got there first.
So fb is by reference, and not by value, yes?
@roosteronacid - assuming T is a class then yes. If you want to enforce this put a constraint on the method where T : class. See answer below.
Awesome! Exactly what I was looking for!
2

As you asked how to write the extension, here goes

public static void With<T>(this T target, Action<T> action) where T : class
{
   action(target);
}

Personally dont see what benefit this has, but fill yer boots!

Comments

1

How about just

return new FooBar{ Foo=10; };

2 Comments

Updated my question. I need the instance by reference.
To who ever did, it's a bit harsh to vote my answer down when it prompted an update in the question. It may not be relevant now with more information but at the time it was.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.