Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return multiple values in static class

How do I return FirstName and Surname in the following class?

public static string GetAccount(int AccountId)
{        
    LinqSqlDataContext contextLoad = new LinqSqlDataContext();

    var q = (from p in contextLoad.MyAccounts
             where p.AccountId == AccountId
             select new { Name = p.FirstName, Surname = p.Surname }).Single();

    return ??;
} 
like image 876
Gurizao Avatar asked Sep 22 '26 02:09

Gurizao


2 Answers

You can return a strongly typed class, dynamic object or a tuple. I prefer to return a strongly typed class.

The problem using the dynamic type is that you dont get intellisense and exceptions only at runtime.

The problem with a tuple is that it does not show you what you return. You or other developers have to read the method to know whats the Name and whats the Surname.

Sample

public class MyResult
{
    public string Name { get; set; }
    public string Surname { get; set; }
}

public static MyResult GetAccount(int AccountId)
{        
    LinqSqlDataContext contextLoad = new LinqSqlDataContext();

    var q = (from p in contextLoad.MyAccounts
             where p.AccountId == AccountId
             select new MyResult{ Name = p.FirstName, Surname = p.Surname }).Single();

    return q;
} 

Update

I suggest to use SingleOrDefault instead of Single. This will make sure you get a null result if the Account does not exist instead of throw a exception.

//
select new MyResult{ Name = p.FirstName, Surname = p.Surname }).SingleOrDefault();
//
like image 154
dknaack Avatar answered Sep 24 '26 15:09

dknaack


If you don't want to define a new object for your return type, you can use Tuple<string, string>.

like image 40
Ade Stringer Avatar answered Sep 24 '26 15:09

Ade Stringer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!