1

How do I pass an object from one method to another? From the code below, I would like to pass newEvent from xmlReader() to outputData()

public class Event
{
    public int ID {get; set;}
}


public void xmlReader()
{
    Event newEvent = new Event;

    newEvent.ID = 56;

    outputData(newEvent);
}


public void outputData(object theEvent)
{
    MainContainerDiv.InnerHtml = theEvent.ID;
}

Thank you, Jordan

1
  • The suggestions worked. Thanks everyone for the quick and helpful responses! Commented Feb 16, 2011 at 17:28

4 Answers 4

7

You're already passing it, but the only problem you're having is this:

public void outputData(object theEvent)
{
    MainContainerDiv.InnerHtml = ((Event)theEvent).ID;
}

or

public void outputData(Event theEvent)
{
    MainContainerDiv.InnerHtml = theEvent.ID;
}

You have to either cast the object to a particular type (first solution) or set a particular type to your parameter (second solution). It is of course a bigger problem if the same method is called by many different callers. A more robust approach in this case would be to check parameter type:

public void outputData(object theEvent)
{
    if (theEvent is Event)
    {
        MainContainerDiv.InnerHtml = (theEvent as Evenet).ID;
    }
    // process others as necessary
}
Sign up to request clarification or add additional context in comments.

Comments

1

change

public void outputData(object theEvent)

to

public void outputData(Event theEvent)

Comments

1

What I think you mean is "how do I turn theEvent from object back into an Event", in which case:

public void outputData(object theEvent)
{
    MainContainerDiv.InnerHtml = ((Event)theEvent).ID;
}

The better option would be to change the method signature for outputData, so that it takes an Event parameter, rather than an object parameter:

public void outputData(Event theEvent)
{
    MainContainerDiv.InnerHtml = theEvent.ID;
}

If, for some reason, you need to pass theEvent as object, but you may need to use it multiple times within outputData, there's a variation on the first method:

public void outputData(object theEvent)
{
    var event = (Event)theEvent;
    MainContainerDiv.InnerHtml = event.ID;
    //
    // You can now use "event" as a strongly typed Event object for any further
    // required lines of code
}

Comments

0

You are passing the object correctly but passing is by up casting....

If the OutputData will only going to accept Object of type events then the defination of the object will b

public void outputData (Event theEvent) {
  ......
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.