0

This question is connected (but NOT duplicate) of this one. Consider that I am fairly new to C#. I would like, if possible, to take the handle of a member of an object that has not been instantiated jet, in order to use it later on. Following previous question, I would like to do something like

List<Action<YourClass>> lst = new List<Action<YourClass>>;

lst.Add(x => x.Member1);
lst.Add(x => x.Member2);

Member1 and Member2 are not supposed to be static member, as their value depend on the state of the object they are member of. Basically I want the handle of their "name", so that I can use it later on when the objects are instantiated. I was thinking about an approach based on string which value is the member name, but maybe there is a better way? Thanks.

Vaaal88
  • 591
  • 1
  • 7
  • 25

2 Answers2

0

I'm not sure if i understand you right. At first you need to create an instance from your list.

List<Action<YourClass>> lst = new List<Action<YourClass>>;

Else your Add will broke with NullReference-Exception. What you are using in your Add is called anonymus function because the handle isn't saved. If you would like to store this you need a delegate. On this delegate you can call the Invoke-Methode to call it. You are allowed to create your on delegates as well as using predefined like Action.

Here is a small example without any sence, but maybe clarify:

    var action = new Action<string>(x => x = x.Substring(1, 1));
    //Do some other stuff
    action.Invoke("Hallo");

Note that the used var keyword. It detects the result of new Action and take the type of this. In this case it holds Action.

Further note that Action is a predefined delegate. An other would be Func which got one return value. If you need other behaviour you easily can create your own delegates. For this you should read the link.

Sebi
  • 3,879
  • 2
  • 35
  • 62
0

I found the solution thanks to Henk comment:

Func<myObj, Vector> getVect = new Func<myObj, Vector> 
getVect= (myObj => myObj.objVector);

where objVector is NOT a method, but a member of the myObj. I call getVect in this way:

Vector a= getVect(someObj)
Vaaal88
  • 591
  • 1
  • 7
  • 25