I'm working on ASP.NET and I have 2 ways to get an item in database:
- The first:
public Post Get(string postId)
=> !string.IsNullOrEmpty(postId)
? _dbContext.Posts.SingleOrDefault(x => x.Id == postId) : null;
Usage:
var post = Get("someid");
if (post != null)
{
// do stuff...
}
- The second:
public bool TryGetPost(string postId, out Post post)
{
if (!string.IsNullOrEmpty(postId))
{
post = _dbContext.Posts.SingleOrDefault(x => x.Id == postId);
return post != null;
}
post = null;
return false;
}
Usage:
if (TryGetPost("someid", out Post post))
{
// do stuff...
}
Could you please teach me when to use the first/second?
Is there another way which is better than them?