Miguel Moura
Miguel Moura

Reputation: 39374

Get object from action

I have a class that takes a Action on its constructor. I want the class field _options value to become the value of that action.

I tried to use:

_options = options;

But this does not compile. The full code is:

public class PortableObjectTemplate {

  private PortableObjectTemplateOptions _options { get; set; }

  public PortableObjectTemplate(Action<PortableObjectTemplateOptions> options) {
    _options = options;
  }
}

I am trying to be able to use this class as:

PortableObjectTemplate pot = new PortableObjectTemplate(x => {
  x.SearchPath = "/";
  x.BlackList = "*.cs";
});

How can I do this?

Upvotes: 2

Views: 2757

Answers (2)

Gokulnath
Gokulnath

Reputation: 1256

Try this. Create a new instance and pass it to Invoke, which will set all the properties.

public PortableObjectTemplate(Action<PortableObjectTemplateOptions> options) {

     var newOptions = new PortableObjectTemplateOptions();
    _options = options.Invoke(newOptions);

OR

     options.Invoke(_options);
  }

Upvotes: 3

MakePeaceGreatAgain
MakePeaceGreatAgain

Reputation: 37000

As mentioned in the comment an Action is a delegate returning nothing at all (or void). When you want your delegate to return anything you should use a Func<T> instead and execute it:

public PortableObjectTemplate(Func<PortableObjectTemplateOptions> options) {
    _options = options();
}

Of course you should check if options isn´t null before executing it (C#6 upwards):

_options = options?.Invoke();

or alternativly:

options = options == null ? default(PortableObjectTemplate) : options();

Upvotes: 5

Related Questions