0

I have a method called CreateNode(). All it does is creates an XElement and returns it. I have two objects that called this method: Action and ElseAction:

var x1 = Action.CreateNode();
var x2 = ElseAction.CreateNode();

Both of these objects are of type Action and the CreateNode() method resides within the Action class.

Within the CreateNode() method, I have a line that creates the root XElement:

var xelement = new XElement("actionitem");

What I'd like to do is determine whether Action or ElseAction called the CreateNode() method so I can do the following if the caller is ElseAction:

var xelement = new XElement("elseactionitem");

So, I guess my question is "Can I determine the name of who/what called the CreateNode method?" Can I do something ilke the following?:

if (caller == Action) var xelement = new XElement("actionitem");
if (caller = ElseAction) var xelement = new XElement("elseactionitem");
Kevin
  • 4,798
  • 19
  • 73
  • 120

4 Answers4

1

it is easy to do in .net 4.5

if had a method as follows:

public void doAction([CallerMemberName] string fromWhere ="")
{

}

if you call doAction the string will be populated from the method who called it. callerMemberName

Spook Kruger
  • 367
  • 3
  • 15
1

There are different ways to do this. The best is this:

class Action
{
  public virtual XElement CreateNode() {return new XElement("actionitem");}
};

class ElseAction : Action
{
  public override XElement CreateNode() {return new XElement("elseactionitem");}
};
Marius Bancila
  • 16,053
  • 9
  • 49
  • 91
  • It is only reasonable way, I can imagine code those `else if` statements for `AnotherElseAction` or `NextElseAction` where type system can solve it. – Mateusz Feb 27 '14 at 12:45
0

Here u go: C# 5.0 Caller Information

a-ctor
  • 3,568
  • 27
  • 41
0

You can do a check on the object (Action or ElseAction), and call the appropriate methods by doing the following:

    if (caller is Action) {
        // Logic goes here if the caller is of type 'Action'
        // you can use the item as an 'Action' type like
    (caller as Action).SomeMethodOfAction();
    } else if (caller is ElseAction) {
        // Logic goes here if the caller is of type 'ElseAction'
        (caller as ElseAction).SomeMethodOfElseAction();
    }
Johan Aspeling
  • 765
  • 1
  • 13
  • 38