Reputation: 97
I has some method, for example:
public VAR GetAllPosts()
{
var post = from p in _db.Posts select p;
return post;
}
How return var-type variable?
Upvotes: 2
Views: 1825
Reputation: 1714
Based on your code, you know it's going to be a enumeration of Posts, so return
public IEnumerable<Posts> GetAllPosts()
{
var post = from p in _db.Posts select p;
return post;
}
or
public IEnumerable<Posts> GetAllPosts()
{
return from p in _db.Posts select p;
}
If you want to go hardcore you could use something like this, this is a generic type of T, you have to call the method with the desired type and inside it validate the type and do what you like.
public List<T> GetData<T>()
{
//Validate the type and do something
if (typeof(T) == typeof(MyClass))
{
List<MyClass> lst = new List<MyClass>();
lst.Add(new MyClass { ClassProperty = "Value" });
return lst as List<T>;
}
else // do something else
{
return null;
}
}
To call this method you pass the correct type
List<MyClass> list = GetData<MyClass>();
Hope it helps.
Upvotes: 6
Reputation: 62248
var
is not a type, so can not be returned.
If you are uncertain about return type, return object
(like Daniel suggests), if it can be more then one type, return thier base type, if any.
In your concrete case, seems, that you are trying to return IEnumerable<T>
of the objects in _db.Posts
Upvotes: 5
Reputation: 190897
You can have it object
, however you still will have to cast it to use it appropriately. dynamic
is another option, but might be more trouble than its worth.
I think what you might want is IQueryable<T>
where T
is the type of Posts
.
Upvotes: 9