i got few line of code where configure method is calling and passing just the string value but ConfigureWith function expect delegate. can anyone help me to understand how ConfigureWith() method will work. thanks
MailTemplate
.ConfigureWith(mt => mt.MailBody = "hello world")
.ConfigureWith(mt => mt.MailFrom = "rdingwall@gmail.com")
.DoSomeOtherStuff()
.Build();
The implementation for this would be:
public class MailTemplate
{
// regular auto properties
public string MailFrom { get; set; }
public string MailBody { get; set; }
public MailTemplate ConfigureWith(Action<MailTemplate> func)
{
func(this);
return this;
}
}
I see that the example above is from an answer to a different question you asked earlier. I’m still not entirely sure what you’re trying to do, and as Ian Mercer suggested, it’s pretty pointless as written. But if you’re just trying to understand what it does, then let’s first get a working example:
This is as pointless as before, but it builds. What’s happening when you’re calling .ConfigureWith() is that instead of passing a normal value, you’re passing it a function. In the example above, I’m actually declaring the functions as parameters that get passed into the BuildMailTemplate() method, and which in turn get executed when the template is being built and configured. You can get a feel for how it works by stepping through the code, line-by-line (e.g., F11 in Visual Studio), and setting breakpoints in the lambda expressions themselves, and then looking at the call stack.
If you’re confused about the syntax for lambdas – arrow syntax is indeed a bit complex when you’re first getting used to it – then feel free to check out the MSDN article on it, or just Google “c# lambdas” to your heart’s delight.