T
tshad
I am curious as to why to use var in place of an Object Type?
If you have the following program that I found online - var is used:
*************************************
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TomsTestApp
{
class Order
{
private int _OrderID;
private int _CustomerID;
private double _Cost;
public int OrderID
{
get { return _OrderID; }
set { _OrderID = value; }
}
public int CustomerID
{
get { return _CustomerID; }
set { _CustomerID = value; }
}
public double Cost
{
get { return _Cost; }
set { _Cost = value; }
}
}
class Program
{
static void Main(string[] args)
{
// Set up some test orders.
var Orders = new List<Order> { // Change var to
List<Order>
new Order {
OrderID = 1,
CustomerID = 84,
Cost = 159.12
},
new Order {
OrderID = 2,
CustomerID = 7,
Cost = 18.50
},
new Order {
OrderID = 3,
CustomerID = 84,
Cost = 2.89
}
};
// Linq query.
Console.WriteLine(Orders.GetType());
var Found = from o in Orders
where o.CustomerID == 84
select o.Cost;
// Display results.
foreach (var Result in Found)
Console.WriteLine("Cost: " + Result.ToString());
Console.Read();
}
}
}
************************************
If I change the "var" above to List<Order>, the program works equally well.
So why would you use var?
Thanks,
Tom
If you have the following program that I found online - var is used:
*************************************
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TomsTestApp
{
class Order
{
private int _OrderID;
private int _CustomerID;
private double _Cost;
public int OrderID
{
get { return _OrderID; }
set { _OrderID = value; }
}
public int CustomerID
{
get { return _CustomerID; }
set { _CustomerID = value; }
}
public double Cost
{
get { return _Cost; }
set { _Cost = value; }
}
}
class Program
{
static void Main(string[] args)
{
// Set up some test orders.
var Orders = new List<Order> { // Change var to
List<Order>
new Order {
OrderID = 1,
CustomerID = 84,
Cost = 159.12
},
new Order {
OrderID = 2,
CustomerID = 7,
Cost = 18.50
},
new Order {
OrderID = 3,
CustomerID = 84,
Cost = 2.89
}
};
// Linq query.
Console.WriteLine(Orders.GetType());
var Found = from o in Orders
where o.CustomerID == 84
select o.Cost;
// Display results.
foreach (var Result in Found)
Console.WriteLine("Cost: " + Result.ToString());
Console.Read();
}
}
}
************************************
If I change the "var" above to List<Order>, the program works equally well.
So why would you use var?
Thanks,
Tom