I have a class that I would like to instantiate. It contains two fields, one is a String, and the other is a Action.
Within the action statement, I would like to use the string field in my class. However, I do not know how to directly call it while instantiating. Is there any way, or will I have to create a field to contain the instantiated class, and then call text?
public class ExampleClass
{
public string text;
public Action action;
// on class instantiate -> action.Invoke();
}
public class Program
{
static void Main(string[] args)
{
new ExampleClass
{
text = "Hello",
action = () => {
/* use the text element we specified to do something ->
e.g Console.WriteLine(text); */ },
};
Console.ReadLine();
}
}
Trying to just use text
field (like action => ()=> {Console.WriteLine(text);}
) results in error:
CS0103 The name 'text' does not exist in the current context