Wesley Skeen
Wesley Skeen

Reputation: 8285

Return any type of object from a function

Is there any way of returning an object from a function. The tricky part is the object can be of any type. I want a function to handle returning objects from session. So the object i want to return could be a product one minute but then i might want to return a customer the next minute. Is it possible or will I have to do a function to return each type.

Upvotes: 0

Views: 5201

Answers (6)

Alex
Alex

Reputation: 35399

Yes, you can return Type object. Though, you'll need to cast the result in the caller to use anything remotely useful.

static object CarFactory (){
    return new Car();
}

static void Main(){

    Car car = (Car)CarFactory();

    /* do stuff with car */
    car.Crash();
}

Note It is a standard to use generics as it provides the desired level of abstraction with Type safety...

Upvotes: 5

Dave Bish
Dave Bish

Reputation: 19636

In this kind of scenario, you're better off wrapping up your session class via some kind of Service/Api.

For example:

public static class SessionAccess
{
    public static Something SomethingSession
    {
        get
        {
            return Session["Something"] as Something;
        }

        set
        {
            Session["Something"] = value;
        }
    }
}

It's important to have a consistent session-access mechanism, as to avoid accidentally stepping-over the same session key, and to ensure it's always the same underlying datatype.

Upvotes: 1

Raf
Raf

Reputation: 683

Depending on your use cade, instead of using object maybe you could use generics for that?

Have a class Session<T> with a method

T GetResult()

You could the make instances like this:

var x = new Session<Product>();
var y = new Session<Customer>();

This way you get some nice type safety.

Upvotes: 1

gabsferreira
gabsferreira

Reputation: 3137

Your method can return a object, but you must convert for the object you want when you call it.

Upvotes: 0

gdoron
gdoron

Reputation: 150243

  1. Return object it's the highest class.
  2. Make the Method generic.
  3. Return dynamic (thanks to @AustinSalonen)

public T Foo<T>(T obj)
{
    var variable = GetTFromFooElse();
    return variable; 
}

public dynamic Foo()
{
    var variable = GetSomethingFromFooElse();
    return variable;
}

Upvotes: 6

Manuel Amstutz
Manuel Amstutz

Reputation: 1388

If your method returns an Object you can return any object you want.

Upvotes: 0

Related Questions