|
The use comes from when Linq was introduced; it will be type-safe, based on the type the IDE derives form what you put in there. It can be used both to make code more readable, and to make code harder to read.
I would also like to point out that you can simply use the factory-method on the connection to create a command; and those should not have been "var" typed, but simply the appropriate interfaces.
--edit
MSDN[^] has a better explanation than I do, ofc
Bastard Programmer from Hell
If you can't read my code, try converting it here[^]
modified 16-Sep-15 8:50am.
|
|
|
|
|
When the type is obvious, using var means you don't have to repeat the type:
var someDictionary = new Dictionary<string, List<Expression<Func<IEmployee, bool>>>>(StringComparer.OrdinalIgnoreCase);
Dictionary<string, List<Expression<Func<IEmployee, bool>>>> someDictionary = new Dictionary<string, List<Expression<Func<IEmployee, bool>>>>(StringComparer.OrdinalIgnoreCase);
When the type is not immediately obvious, but isn't integral to understanding the code, then it's a matter of personal preference or style guidelines:
using (var dbReader = dbCommand.ExecuteReader())
using (SqlDataReader dbReader = dbCommand.ExecuteReader())
(In this example, if you change the type of dbCommand , the var sample would just work, but the SqlDataReader would generate a compiler error until you changed the type of dbReader as well.)
In most cases where the type is not obvious, you should try to avoid using var :
var list = GetFoo();
List<Customer> list = GetFoo();
However, proper method and variable names would make the code clearer:
var listOfCustomers = GetListOfCustomers();
And finally, if you're using anonymous types, then you have to use var :
var listOfNames = listOfCustomers.Select(c => new { c.FirstName, c.Surname });
(Anonymous types are the reason var was introduced.)
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Richard Deeming wrote: (In this example, if you change the type of dbCommand , the
var sample would just work, but the SqlDataReader
would generate a compiler error until you changed the type of
dbReader as well.) That must be why we usually program against the base-class, putting the SqlDataReader into variable of type DbDataReader, or against its interface, IDataReader.
Declaring those as "var" means that the type may not what you expect it to be. If it offers no advantage to use var, then it might be wise to be precise.
Bastard Programmer from Hell
If you can't read my code, try converting it here[^]
|
|
|
|
|
Yes, please use the Interfaces.
|
|
|
|
|
It's for use with anonymous types -- where you can't know the type when you write the code.
Don't use it any other time.
|
|
|
|
|
Well said, that man.
Regards,
Rob Philpott.
|
|
|
|
|
PIEBALDconsult wrote: Don't use it any other time.
Absolute rules have absolutely no place in programming.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Good responces to all. Thanks for the feed back. So, when I see something like:
for (var i = 0; i < 10; i++)
{
}
that's just stupid.
|
|
|
|
|
In most cases, var is just a form of laziness but, in this case, replacing a three letter keyword with another three letter keyword really is bonkers (or it's a sign that they haven't customized Resharper which prompts you to change explicit types to use var).
|
|
|
|
|
Hi, I am developing a code to get name and div_id of employee from the user and then add employees name, emp_id, div_id and isTL to a List<IEmployee> where IEmployee is an interface class for Employee class.Now I want to view all the employee details from the list. And I want to edit the isTL detail of the employee which is set to false by default? How do I do? Here is my code.
class Employee
{
int div_Id;
public string Name { get; set; }
public bool IsTL { get; set; }
public Employee(string name, bool isTL, int divid)
{
this.Name = name;
this.IsGR = isTL;
this.div_Id = divid;
}
}
class Batch
{
public int AddEmployee(IEmployee employee)
{
iemplist.Add(employee);
employeeid=0;
foreach (Employee a in iemplist)
{
++employeeid;
}
}
public list<IEmployee> ViewAllEmployees()
{
foreach (Employee i in iemplist)
{
Console.WriteLine("EmployeeName: {0}", i.Name);
Console.WriteLine("IsTL: {0}", i.IsGR);
}
return iemplist;
}
}
class Program
{
static void Main(string[] Args)
{
Batch bat= new Batch();
List<IEmployee> iemplist = new List<IEmployee>();
int EmployeeId;
string name;
bool isTL;
int div_id;
case 2:
{
Console.WriteLine("enter the employee name and div_id");
name = Console.ReadLine();
isTL = false;
div_id = Convert.ToInt32(Console.ReadLine());
Employee emp = new Employee(name, isTL, div_id);
EmployeeId = bat.AddEmployee(emp);
Console.WriteLine("Employee Id = " + EmployeeId);
break;
}
case 3:
{
var s = bat.ViewAllEmployees();
break;
}
}
}
modified 16-Sep-15 3:56am.
|
|
|
|
|
"//is this correct???"
Um... no.
There are a couple of problems with your code here, and the major ones are that you don't seem to have sat down and worked out what you are trying to do before leaping into code, and that you haven't even tried to compile it. It won't compile, by the way - C# is case sensitive, so
public list<IEmployee> ViewAllEmployees() Is not the same as
public List<IEmployee> ViewAllEmployees()
When you add that the Batch class doesn't know what iemplist is because it isn't a member of the class, and that you don't define an interface IEmployee at all, it all starts to fall apart.
What it looks like is that you have grabbed chunks of code at random from the internet and chucked them into a single program and hoped it all works. That's not a good strategy - it's unlikely to work, and will take a lot more effort to bodge into doing something like the task you have been assigned that doing it yourself would have been in the first place. (It's a bit like trying to build a car by grabbing parts at random from a car breakers shelves, and trying to bolt them all together: unless the doors come from the same make and model as the chassis they just aren't going to shut properly without some serious attention from a big hammer. And then the windows won't fit either, so...)
So stop.
Copy that to somewhere safe, and start again. Look at your task, and work out what you need - and I don't think the Batch class is likely to be in that.
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
|
|
|
|
|
I suggest you get a good introductory book on C# and review the "basics." ".NET Book Zero," by Charles Petzold, is an excellent resource; it's free, and available on-line to download here: [^].
The code you show will not compile, and even your description of what the 'Employee class should be is not what it is, now. The rest of the code contains what appear to be "fragments."
You need to divide your task into specific steps, and test your work as you complete each step. Creating a method that returns a list is simple:
public List<Employee> GetEmployeesByDivision(int divisionid, List<Employee> allemployees)
{
List<Employee> empByDiv = new List<Employee>();
foreach(var employee in allemployees)
{
if(employee.div_Id == divisionid) empByDiv.Add(employeed);
}
return empByDiv;
} And, it's even easier to do using Linq, but that's for the future.
«I want to stay as close to the edge as I can without going over. Out on the edge you see all kinds of things you can't see from the center» Kurt Vonnegut.
|
|
|
|
|
I just want to know why the USB port still reads my mouse even if the USB ports are disabled in the registry editor and how can I completely disable it.
|
|
|
|
|
What does this have to do with C#?
|
|
|
|
|
Because i want to make a code using C# but i didn't know how to totally disable the usb port.
|
|
|
|
|
Your question still has nothing to do with C#. You might want to paint them red, but that doesn't mean your question would have any place in a painting forum.
|
|
|
|
|
And what does this have to do with C#?
And why the heck would you want to?
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
|
|
|
|
|
i want to make a code using C# but i don't know how to totally disable the usb port.
|
|
|
|
|
You can completely disable it by applying superglue.
Bastard Programmer from Hell
If you can't read my code, try converting it here[^]
|
|
|
|
|
Hi!
I am creating ErrorProvider objects with new in my code (and calling SetError(...)) while validating a form. It is also added to a List<errorprovider> Later on I call Clear() and remove the reference in the List. Will the object be garbage collected after that or am I piling up a lot of never-used ErrorProvider objects?
ErrorProvider errProvider;
List<ErrorProvider> errProviderLst = new List<ErrorProvider>();
...
errProvider = new ErrorProvider();
errProviderLst.Add(errProvider);
errProvider.SetError(c, "Ange ett heltal");
...
errProviderLst[i].Clear();
errProviderLst.RemoveAt[i];
|
|
|
|
|
If there are no other references to the object, then yes, when it loses scope. Implement IDisposible and have it write something to the debug output-window to verify
Bastard Programmer from Hell
If you can't read my code, try converting it here[^]
|
|
|
|
|
Hi,
I want to know that what is get and set Property in C#,
and what is difference between them???And if i want to use only get Property then how can i do this in code???
Can any one help???
What is the use of get and set property,and why we have to use get and set property and which condition???
modified 18-Sep-15 3:19am.
|
|
|
|
|
|
Property get lets you retrieve the value of the property by calling a method to evaluate the property's current value, with syntactic sugar to make it look like a variable.
Property set does the same thing, but it allows you to set the value.
For example, your class may store the user information as "first name" and "second name" internally, and provide a Property FullName:
private string firstName = "";
private string lastName = "";
public string FullName
{
get { return string.Format("{0} {1}", firstName, lastName); }
set
{
string[] parts = value.Split(' ');
if (parts.Length != 2) throw new ArgumentException("Full name requires a first and last name: " + value);
firstName = parts[0];
lastName = parts[1];
}
} To provide a getter only is easy - there are two ways:
public string MyProperty { get { return "Hello"; }}
Requires no setter.
Or you could have a private setter:
private string _MyProperty = "Hello";
public string MyProperty
{
get { return _MyProperty; }
private set { _MyProperty = value; }
} This allows your class to set the value, but the outside world can only see the getter.
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
|
|
|
|
|
a small example on top of the previous answers.
Think of a car, it has properties like color, max speed, current speed, number of wheels, ...
A car can also do stuff like accelerate, turn, ...
If you would put this in the code, the properties would be put in variables and exposed via properties (get/set). Accelerate and turn are actions that are translated into methods.
Some properties can only be set when instantiating the class, eg number of wheels and maxspeed. Some can be changed from outside: You can repaint the car eg. Some can never be changed (number of wheels) and some can only be changed by using a method. (Accelerate will change the current speed and a check will prevent it from becoming higher than the max speed property).
The inner workings of properties and methods are never exposed. eg. the check where the current speed is never higher than the max speed could reside in the accelerate method or in the current speed property itself.
Read up on "encapsulation" for more info.
Hope this helps.
|
|
|
|
|