Reputation: 8285
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
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
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
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
Reputation: 3137
Your method can return a object, but you must convert for the object you want when you call it.
Upvotes: 0
Reputation: 150243
object
it's the highest class.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
Reputation: 1388
If your method returns an Object you can return any object you want.
Upvotes: 0