Question

I want to pass an extension method that returns void as a parameter to another extension method that returns dynamic.

public static void AddTo(this Object entity, Object parent)
{
    parent.GetCollectionOf(entity).Add(entity);
}
public static dynamic And(this Object entity, Action method)
{
    entity.method(parent);
    return entity;
}

I'd like to use it something like this,

dynamic parent = MakeNew(parentType);    
dynamic entity = MakeNew(type).And(AddTo(parent));

I like to pass any void method into And() but still return the object it extended. I hope the dynamic return type is not problematic.

What is the syntax for this kind of thing?

Was it helpful?

Solution

Could you perhaps do it like this?

myObjects
        .Where(d => d.true == true && d.Value == 77)
        .Update(e => { e.Value = 1; e.true = false; } );

Use my linq carefully, it could explode at any moment ;-)

    /// <summary>
    /// Used to modify properties of an object returned from a LINQ query
    /// </summary>
    /// <typeparam name="TSource">The type of the source.</typeparam>
    /// <param name="input">The source</param>
    /// <param name="updater">The action to perform.</param>
    public static TSource Update<TSource>(this TSource input, Action<TSource> updater)
    {
        if (!updater.IsNull() && !input.IsNull())
        {
            updater(input);
        }
        return input;
    }

To explain this fully:

    public DataRow DoSomething(DataRow dataRow)
    {
        //DoSomething
        return dataRow;
    }

    var query = from dataRow in myDataTable.Rows.Cast<DataRow>()
                where
                    Double.TryParse(dataRow["Distance"].ToString(), out distance)
                    && distance > (11) && distance <= 99
                select dataRow.Update(f => DoSomething(f));

OTHER TIPS

Have I got your question right?

dynamic entity = MakeNew(type).And(() => 
{
  AddTo(parent); 
}); 

I think that C# is not yet "dynamic" enough to do the thing I think you want.

The And method won't work, since the entity parameter is of type object, so entity.method(parent) will not work. Even if you define entity to be of type dynamic, C# will try to find a method called "method" to call. You can do this in your example:

public static dynamic And(this Object entity, Action method, object parameter) 
{     
      method(entity, parameter);     
      return entity; 
}

and

dynamic entity = MakeNew(type).And(AddTo, parameter); 

I suspect you actually want this:

public static void AddTo(this Object entity, Object parent)
{
    parent.GetCollectionOf(entity).Add(entity);
}

public static dynamic And(this Object entity, Action<object> method)
{
    method(entity);
    return entity;
}

dynamic entity = MakeNew(type).And(entity => entity.AddTo(parent));

Having said that, it's still not clear where parent is coming from to start with...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top