jtlowe
jtlowe

Reputation: 13

ASP.NET C# pass object to method

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

Upvotes: 1

Views: 1610

Answers (4)

Robert Koritnik
Robert Koritnik

Reputation: 105009

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
}

Upvotes: 7

S M Kamran
S M Kamran

Reputation: 4503

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) {
  ......
}

Upvotes: 0

Rob
Rob

Reputation: 45761

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
}

Upvotes: 1

asawyer
asawyer

Reputation: 17808

change

public void outputData(object theEvent)

to

public void outputData(Event theEvent)

Upvotes: 1

Related Questions