How to find difference for two time values in string? - c#

I am working on a new project in c#, i have no experience with date and time.
Here i need to find the difference between two time values which is in string format
string pointavalue = comboBox1.Text + ":" + comboBox2.Text + ":" + comboBox5.Text;
string pointbvalue = comboBox3.Text + ":" + comboBox4.Text + ":" + comboBox6.Text;
string pointcvalue = comboBox7.Text + ":" + comboBox8.Text + ":" + comboBox9.Text;
DateTime pointa = DateTime.Parse(pointavalue, System.Globalization.CultureInfo.CurrentCulture);
DateTime pointb = DateTime.Parse(pointbvalue, System.Globalization.CultureInfo.CurrentCulture);
DateTime pointc = DateTime.Parse(pointcvalue, System.Globalization.CultureInfo.CurrentCulture);
string time1 = pointa.ToString("HH:mm:ss");
string time2 = pointb.ToString("HH:mm:ss");
string time3 = pointc.ToString("HH:mm:ss");
There is three Values pointavalue, pointbvalue. pointcvalue.
They are combined string values of comboboxes.
Now how do i subtract pointbvalues from pointavalues?
I know they are in string format so operations cannot be performed.
the code you are looking is not mine, someone helped me but its working as a expected.
I am learning C# so bear with me.
ok i think figure out something, but still i can't solve it.
Here is my recent work with the code
DateTime inputa = DateTime.Parse(label21.Text, System.Globalization.CultureInfo.CurrentCulture);
DateTime inputb = DateTime.Parse(label23.Text, System.Globalization.CultureInfo.CurrentCulture);
if (pointa < pointb)
{
TimeSpan diff1 = pointb.Subtract(pointa);
DateTime d1=Convert.ToDateTime(diff1);
if (d1 < inputa)
{
label34.Text = "fail";
}
else
{
label34.Text = "pass";
}
Here i want to check the condition of the time diff1 and inputa, that's it that's all i need to finish this project.

The reason why you can't solve this problem is that you are trying to compare two different data types, Timespan and Datetime are not same
Either convert all your string to "Timespan" (That is better option).
Datetime will give you the present date, but it seems you don't need that.
Last but not least learn some basics before you ask these questions.

One more simple example:
void Main()
{
DateTime now = DateTime.Now;
DateTime yesterday = now.AddDays(-1);
TimeSpan difference = yesterday - now;
Console.WriteLine (difference.GetType().Name);
Console.WriteLine (difference.TotalSeconds); // expecting -86400
}
running this will print
TimeSpan
-86400

Take a look at the DateTime.Substract method:
TimeSpan abdiff = pointb.Substract(pointa);
TimeSpan bcdiff = pointc.Substract(pointb);
Alternatively, you can use the - operator, you get back a Timespan which contains the differences:
TimeSpan abdiff = pointb - pointa;
TimeSpan bcdiff = pointc - pointb;

Assuming that your combo boxes contain the hour, minute, and second then you could do the following.
TimeSpan pointa = new TimeSpan(int.Parse(comboBox1.Text), int.Parse(comboBox2.Text), int.Parse(comboBox5.Text));
TimeSpan pointb = new TimeSpan(int.Parse(comboBox3.Text), int.Parse(comboBox4.Text), int.Parse(comboBox6.Text));
TimeSpan pointc = new TimeSpan(int.Parse(comboBox7.Text), int.Parse(comboBox8.Text), int.Parse(comboBox9.Text));
TimeSpan aTob = pointa > pointb
? pointa - pointb
: (pointa + TimeSpan.FromDays(1)) - pointb;
Basically this assumes that your combo boxes only have valid hour (0-23), minute (0-59), and second (0-59) values. Then you just need to determine if your times are on the same day or not. If you assume that pointa is latter than pointb then checking if it is greater than pointb means you can do a straight subtraction. If not then it must be the time for the next day and you just add 1 day to it before subtracting pointb.
This is based on your assertion that 01:00 - 23:00 should be 2 hours and not -22. Thought it would be best if there where a date included so you would know for sure if the times are on the same day or the next day or from completely different years.

Related

C# Time Subtraction With a Discord Bot

I'm making a funny discord bot that finds the next 4:20 on the clock, whether it's AM or PM, and tells you how long until 4:20. My code is working perfectly until an hour before 4:20 and then it skips ahead and tells how long until the next 4:20 instead of showing "0 hours 59 minutes". I'm thinking that there may be an issue with how I'm formatting the time output but I'm very new to C# and how no idea how to fix it. I have included my code and also a screenshot of the current output. In the screenshot the bot is also a minute off but I've since then figured out how to fix that. I know the code isn't the most efficient or clean but again, I'm very new to programming.
//Finds next 4:20 on the clock
[Command("420")]
public async Task WeedMinute()
{
DateTime currentTime = DateTime.Now; //Current time
DateTime weedMinuteMorning = Convert.ToDateTime("4:21:00"); //4:20am
DateTime weedMinuteEvening = Convert.ToDateTime("16:21:00"); //4:20pm
string weedMinutePM = "16:21:00"; //These variables are used in subtraction
string weedMinuteAM = "4:21:00";
if (currentTime <= weedMinuteEvening)
{
//chooseMorningEvening is the output time string
DateTime chooseMorningEvening = (DateTime.Parse(weedMinutePM).Subtract(currentTime.TimeOfDay));
await Context.Channel.SendMessageAsync("The next weed minute will happen in " + chooseMorningEvening.ToString(#"hh") + " hours " + chooseMorningEvening.ToString(#"mm") + " minutes.");
}
else if (currentTime >= weedMinuteMorning)
{
//chooseMorningEvening is the output time string
DateTime chooseMorningEvening = (DateTime.Parse(weedMinuteAM).Subtract(currentTime.TimeOfDay));
await Context.Channel.SendMessageAsync("The next weed minute will happen in " + chooseMorningEvening.ToString(#"hh") + " hours " + chooseMorningEvening.ToString(#"mm") + " minutes.");
}
}
The problem with your code is that it does not handle all the cases that can occur (there are three):
time is between 00:00:00 and 04:20:00 => calculate time to 04:20:00
time is between 04:20:00 and 16:20:00 => calculate time to 16:20:00
time is after 16:20:00 => calculate time to 04:20:00, next day.
You can simplify this a little if you observe that the time till your next toke should always be between 0 and 12 hours. So, if you just take the time until 16:20, if it is greater than 12 hours then you must be up before 04:20 and you can subtract 12 hours. If the time is less than 0 (that is, negative) then you must be later than 16:20 so you just add 12 hours. In code this looks like this:
public static TimeSpan CalculateTimeToWeed(DateTime from)
{
DateTime weedTime = Convert.ToDateTime("16:20:00");
TimeSpan twelveHours = TimeSpan.FromHours(12.0);
TimeSpan timeToWeed = weedTime - from;
double totalHours = timeToWeed.TotalHours;
if (totalHours > 12.0)
{
timeToWeed -= twelveHours;
}
else if (totalHours < 0.0)
{
timeToWeed += twelveHours;
}
return timeToWeed;
}
and you would integrate it into your Discord bot as follows:
[Command("420")]
public async Task WeedMinute()
{
DateTime currentTime = DateTime.Now;
TimeSpan timeToWeed = CalculateTimeToWeed(currentTime);
string message = "The next weed minute will happen in " + timeToWeed.ToString("hh' hours 'mm' minutes.'");
await Context.Channel.SendMessageAsync(message);
}
You could cut down the number of lines in this, but having these temporary variable makes thing easier to debug. You can check while stepping through with a debugger that currentTime is what you expect and timeToWeed makes sense and so on.
Breaking the code into two functions also has a number of advantages:
You can test the time calculation independent of the bot
The code is much clearer, you are not mixing up communication code with calculation code.
Hope this helps.
There's a DateTime.Compare function which can be used here to fix the error as below
//DateTime currentTime = DateTime.Now; //Current time
DateTime currentTime = Convert.ToDateTime("3:22:00"); // An example time for 0 hours and 59 mins
DateTime weedMinuteMorning = Convert.ToDateTime("4:21:00"); //4:20am
DateTime weedMinuteEvening = Convert.ToDateTime("16:21:00"); //4:20pm
string weedMinutePM = "16:21:00"; //These variables are used in subtraction
string weedMinuteAM = "4:21:00";
if(currentTime.CompareTo(weedMinuteMorning) < 1) //less than or same as Morning 4:20 am
{
var chooseMorningEvening = weedMinuteMorning - currentTime;
string m = "The next weed minute will happen in " + chooseMorningEvening.Hours + " hours " + chooseMorningEvening.Minutes + " minutes.";
}
else
{
var chooseMorningEvening = weedMinuteEvening - currentTime;
string m = "The next weed minute will happen in " + chooseMorningEvening.Hours + " hours " + chooseMorningEvening.Minutes + " minutes.";
}
Your formatting the time output seem ok, just for better formats see Custom TimeSpan format strings.
Your code have three problem:
1. If Conditions
if (currentTime <= weedMinuteEvening)
{
//this condition is true from 00:00:00 to 16:21:01 so for dates less than 4:21:00
//you get incorrect output, and next condition execute just for dates greater than 16:21:00.
...
}
else if (currentTime >= weedMinuteMorning)
{
//This code execute only for dates greater than 16:21:00.
...
}
As Adam suggested you must remove .TimeOfDay from currentTime but this not enough.
You must handle dates grater than 16:21:00
So i hope this code work for you:
[Command("420")]
public async Task WeedMinute()
{
DateTime currentTime = DateTime.Now; //Current time
DateTime weedMinuteMorning = Convert.ToDateTime("4:21:00"); //4:20am
DateTime weedMinuteEvening = Convert.ToDateTime("16:21:00"); //4:20pm
//I removed These variables, Don't need to parse same DateTime again. change it as you wish
//string weedMinutePM = "16:21:00";
//string weedMinuteAM = "4:21:00";
if (currentTime <= weedMinuteMorning)
{
TimeSpan timeSpan = weedMinuteMorning.Subtract(currentTime);
await Context.Channel.SendMessageAsync("The next weed minute will happen in " + timeSpan.ToString("hh' hours 'mm' minutes.'"));
}
else if (currentTime <= weedMinuteEvening)
{
TimeSpan timeSpan = weedMinuteEvening.Subtract(currentTime);
await Context.Channel.SendMessageAsync("The next weed minute will happen in " + timeSpan.ToString("hh' hours 'mm' minutes.'"));
}
else
{
//To handle dates greater than 16:21:00, we must calculate hours
//remaining until 4:20 next day.
weedMinuteMorning = weedMinuteMorning.AddDays(1);
TimeSpan timeSpan = weedMinuteMorning.Subtract(currentTime);
await Context.Channel.SendMessageAsync("The next weed minute will happen in " + timeSpan.ToString("hh' hours 'mm' minutes.'"));
}
}

c# formatting data write to csv files

My C# is very limited and my english too. I need your help. I need to edit the data from the barcode reader. Incoming data like this.
1-) 12345678 (Barcode)
2-) 310319 (Date d m y format)
3-) 174252 (Hour minute second)
4-) 123 (Barcode)
5-) 010419 (Date d m y format)
6-) 153020 (Hour minute second)
7-) 3873 (Code)
Ok this is my data from the barcode reader. I want to format this data as follows.
the final output is sample like this. Sorry for my bad english can you help me please
1-) 12345678 (Barcode not change)
2-) 2 and 3 lines to timestamp ( 310319 + 174252) ? to timestamp
3-) 123 (Barcode not change)
4-) 5 and 6 lines to timestamp (010419 + 153020) ? to timesatamp
5-) 3873 (not change)
string name = lvw.SubItems[1].Text = Splt[0];
string filePath = #"C:\Temp\data.csv";
var one = lvw.SubItems[1].Text = Splt[0];
var two = lvw.SubItems[1].Text = Splt[1];
var three = lvw.SubItems[1].Text = Splt[2];
var four = lvw.SubItems[1].Text = Splt[3];
var five = lvw.SubItems[1].Text = Splt[4];
var six = lvw.SubItems[1].Text = Splt[5];
var seven = lvw.SubItems[1].Text = Splt[6];
var data = one +";" + two + ";" + three + ";"
+ four + ";" + five + ";" + six + ";" + seven + Environment.NewLine;
File.AppendAllText(filePath, data);
variable two + three combine to timestamp this is my problem ?
#Henk Holtermans answer works pretty well with the question you asked, since you didn't determine what a timestamp is in your case.
I'm just gonna answer to add some DateTime usage, since it may be useful for you in the future.
First, convert the strings to a DateTime object:
string date = "310319";
string time = "174252";
DateTime dt;
string timestamp;
bool correct = DateTime.TryParseExact(date + time,
"ddMMyyHHmmss",
CultureInfo.InvariantCulture,
DateTimeStyles.AdjustToUniversal,
out dt);
if(correct){
timestamp = dt.ToString("yyyyMMddHHmmssffff");
}
TryParse lets you get a boolean result of your conversion, meaning that you don't need to check for errors, just ifthe result is true.
TryParseExact lets you tell the function exaclty how is your string formed
Here you can see a list os custom format strings
out dt is where the converted datetime is gonna get stored
After that I'm checking if the result boolean and if the conversion was successful I'm getting a timestamp string of the DateTime object.
"yyyyMMddHHmmssffff" is the output format of the string, where yyyy is the year in 4 chars, MM the month in 2 chars and so on. You have every possible custom string in the link I already provided.
string date = "310319";
string time = "174252";
DateTime dt;
bool correct = DateTime.TryParseExact(date + time,
"ddMMyyHHmmss",
CultureInfo.InvariantCulture,
DateTimeStyles.AdjustToUniversal,
out dt);
Console.WriteLine(dt);
DateTimeOffset dto = new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero);
dto = new DateTimeOffset(dt, TimeSpan.Zero);
long y = dto.ToUnixTimeSeconds();
Console.WriteLine(y); // output 1554054172
thank you to everyone. That's how I solved my problem.

Minute give wrong values on substract

I want to subtract minutes and get the difference. below is my code
double diff = currBlock.EndTime.Subtract(currBlock.StartTime).TotalMinutes;
In given code (currBlock.StartTime = 23:30:00) and (currBlock.EndTime= 00:20:00)
here starttime is time of today i.e.(09/26/2016 23:30:00), night time which will be consider as 11:30 PM and endtime is time of tomorrow i.e.(09/27/2016 00:20:00), morning time which will be consider as 12:20 Am. In my code i am getting values in minus which is -1390 and it is incorrect. So please help me to solve this.
Here i have attach image of data for further reference.
please explain me properly, how do i use it? it is just a time block for different shift so there is no date include in it
There is a date included in it. You're telling us that EndTime is something like 09/27/2016 00:20:00, while StartTime is something like 09/26/2016 23:30:00. The problem is that that knowledge is in your head and not in your code. If you subtract the values as TimeSpans, then you're literally saying: what is 30 minutes minus 23 hours and 30 minutes. The answer, of course is -23 hours. To get the real difference, you must include the dates, which means utilizing a DateTime or DateTimeOffset type for both StartTime and EndTime, so you can encode that whole date and time. Then, when you do the subtraction, it will return the right value.
Below Code works for me. Thanks friends for your support and help.
string strCurrDate = (DateTime.Now.Date + currBlock.EndTime).ToString();
DateTime dtYourDate = DateTime.Parse((DateTime.Now.AddDays(-1).Date + currBlock.StartTime).ToString());
string strYourDate = dtYourDate.ToShortDateString() + " " + dtYourDate.ToLongTimeString();
string strTotalMinsElapsed = TotalMinutesElapsed(dtYourDate).ToString();
private long TotalMinutesElapsed(DateTime dtYourDate)
{
long lTotalMinutesElapsed = 0;
//Find Current Date and Time
DateTime dtCurrent = DateTime.Now;
//Find Time Difference details between current date and your given date
TimeSpan tsDiff = dtCurrent.Subtract(dtYourDate);
//Add Total Minutes for Days difference
lTotalMinutesElapsed = lTotalMinutesElapsed + tsDiff.Days * (24 * 60);
//Add Total Minutes for Hour difference
lTotalMinutesElapsed = lTotalMinutesElapsed + tsDiff.Hours * 60;
//Add Minutes
lTotalMinutesElapsed = lTotalMinutesElapsed + tsDiff.Minutes;
return lTotalMinutesElapsed;
}

Compare to dates [duplicate]

I am retrieving two date time values from the database. Once the value is retrieved, I need the difference between the two values.
For that, I create a timespan variable to store the difference of the 2 date values.
TimeSpan? variable = datevalue1 - datevalue2;
Now i need to show the difference which is stored in the Timespan variable in terms of number of hours.
I referred to TimeSpan.TotalHours but couldn't apply the same for some reason.
How do I do that?
I am using C# on a MVC project. I simple need to show the difference value in hours?
EDIT:
Since timespan was nullable, i couldn't use the total hours property. Now I can use it by doing TimeSpanVal.Value.TotalHours;
you may also want to look at
var hours = (datevalue1 - datevalue2).TotalHours;
I think you're confused because you haven't declared a TimeSpan you've declared a TimeSpan? which is a nullable TimeSpan. Either remove the question mark if you don't need it to be nullable or use variable.Value.TotalHours.
In the sample, we are creating two datetime objects, one with current time and another one with 75 seconds added to the current time. Then we will call the method .Subtract() on the second DateTime object. This will return a TimeSpan object.
Once we get the TimeSpan object, we can use the properties of TimeSpan to get the actual Hours, Minutes and Seconds.
DateTime startTime = DateTime.Now;
DateTime endTime = DateTime.Now.AddSeconds( 75 );
TimeSpan span = endTime.Subtract ( startTime );
Console.WriteLine( "Time Difference (seconds): " + span.Seconds );
Console.WriteLine( "Time Difference (minutes): " + span.Minutes );
Console.WriteLine( "Time Difference (hours): " + span.Hours );
Console.WriteLine( "Time Difference (days): " + span.Days );
Result:
Time Difference (seconds): 15
Time Difference (minutes): 1
Time Difference (hours): 0
Time Difference (days): 0
Is there a reason you're using Nullable?
If you want to use Nullable then you can write variable.Value.TotalHours.
Or you can just write: (datevalue1 - datevalue2).TotalHours.
Here is another example of subtracting two dates in C# ...
if ( DateTime.Now.Subtract(Convert.ToDateTime(objDateValueFromDatabase.CreatedOn)).TotalHours > 24 )
{
...
}
a more precise way for employee paid hours or other precision requirement::
decimal DeterminePreciseHours(DateTime startTimestamp, DateTime stopTimestamp)
{
var span = (stopTimestamp - startTimestamp).Value;
decimal total = (decimal)span.TotalMilliseconds / 60 / 60 / 1000;
return Math.Round(total, PRECISION_CONSTANT);
}
https://dotnetfiddle.net/tVIoVJ
var startTime = new TimeSpan(6, 0, 0); // 6:00 AM
var endTime = new TimeSpan(5, 30, 0); // 5:30 AM
var hours24 = new TimeSpan(24, 0, 0);
var difference = endTime.Subtract(startTime); // (-00:30:00)
difference = (difference.Duration() != difference) ? hours24.Subtract(difference.Duration()) : difference; // (23:30:00)
can also add difference between the dates if we compare two different dates
new TimeSpan(24 * days, 0, 0)
WOW, I gotta say: keep it simple:
MessageBox.Show("Result: " + (DateTime.Now.AddDays(10) > DateTime.Now));
Result: True
and:
MessageBox.Show("Result: " + DateTime.Now.AddDays(10).Subtract(DateTime.Now));
Result: 10.00:00:00
The DateTime object has all the builtin logic to handle the Boolean result.

C#: how do I subtract two dates?

Here's my code:
DateTime date1 = new DateTime(byear, bmonth, bday, 0, 0, 0);
DateTime datenow = DateTime.Now;
DateTime date2 = datenow - date1
On the last line I am getting this error:
Error 1 Cannot implicitly convert type 'System.TimeSpan' to 'System.DateTime'
How do I subtract two dates?
Well the point is that if you think of it, subtracting a date to another should not yield a date, it should yield a time span. And that is what happens when you use DateTime.Subtract().
TimeSpan timeSpan = datenow - date1; //timespan between `datenow` and `date1`
This will make your current code work.
If on the other hand you want to subtract, let's say, one year from your date, you can use:
DateTime oneYearBefore = DateTime.Now.AddYears(-1); //that is, subtracts one year
As already mentioned, date - date gives you a TimeSpan, not a DateTime. If you want a DateTime, use AddDays(-1) as in:
DateTime subtractedDate = date1.AddDays(-1);
The result of a date comparison is a TimeSpan, not a DateTime value.
You want to do this:
TimeSpan result = datenow - date1;
.Subtract has two overloads. One accepts a DateTime and returns a TimeSpan, the other accepts a TimeSpan and returns a DateTime.
In other words, if you subtract a date from a date, you get the timespan difference. Otherwise, if you subtract a timespan from a date, you get a new date.
Can you clarify what you are trying calculate? The difference between any two dates in C# or real life is a time span. If you are trying to calculate age then what you want is the timespan since their birth. Change Date2 to to
Timespan age = datenow - date1;
You are correctly subtracting two dates in your code. What's going on is that you expect the difference between the two dates to be another date, and that's not the case.
As other posters have noticed, you get a TimeSpan. From your variable names I get the sense you're trying to find out someone's age.
Age is not a date, it's a duration. Read up on the TimeSpan object and you will find that it correctly expresses the idea you are looking for.
I'm not 0029-01-01 years old, I'm 29 years old. (Today is not my birthday, but assume it is for easy math.)
If you're trying to show someone's age in a control and that control wants a DateTime you are probably using the wrong control to do it.
Try using ticks...?
DateTime date1 = new DateTime(1986, 3, 16, 0, 0, 0);
DateTime datenow = DateTime.Now;
DateTime date2 = new DateTime(datenow.Subtract(date1).Ticks);
You are expecting the difference of two dates to be a date which is not. That being said, if you need to subtract a certain number of days or months, it can easily be done using the built in methods of the DateTime object such as .AddDays(-1), note that I used a negative number to substract, you can apply the opposite. Here is a quick example.
DateTime now = DateTime.Now;
// Get the date 7 days ago
DateTime sevenDaysAgo = now.AddDays(-7);
// Bulk: Get the date 7 days and two hours ago
DateTime sevenDaysAndtwoHoursAgo = now.Add(-(new TimeSpan(7, 2, 0, 0)));
Use this code:
DateTime? Startdate = cStartDate.GetValue<DateTime>().Date;
DateTime? Enddate = cEndDate.GetValue<DateTime>().Date;
TimeSpan diff = Enddate.GetValue<DateTime>()- Startdate.GetValue<DateTime>() ;
txtDayNo.Text = diff.Days.GetValue<string>();
TimeSpan Example:
private void Form1_Load(object sender, EventArgs e)
{
DateTime startdatetime = new DateTime(2001, 1, 2, 14, 30, 0);
DateTime enddatetime = DateTime.Now;
TimeSpan difference = enddatetime.Subtract(startdatetime);
string sdifference = "TotalDays:" + difference.TotalDays + Environment.NewLine;
sdifference += "TotalHours:" + difference.TotalHours + Environment.NewLine;
sdifference += "TotalMilliseconds:" + difference.TotalMilliseconds + Environment.NewLine;
sdifference += "TotalMinutes:" + difference.TotalMinutes + Environment.NewLine;
sdifference += "TotalSeconds:" + difference.TotalSeconds + Environment.NewLine;
sdifference += "Ticks:" + difference.Ticks + Environment.NewLine;
sdifference += "Total:" + difference.Days + " days, " + difference.Hours + " hours, " + difference.Minutes + " minutes, " + difference.Seconds + " seconds and " + difference.Milliseconds + " milliseconds.";
TextBox TextBox1 = new TextBox();
TextBox1.Multiline = true;
TextBox1.Dock = DockStyle.Fill;
TextBox1.Text = sdifference;
this.Controls.Add(TextBox1);
}
Not exactly an answer to your question, but I prefer using var instead of annotating the variables with types. var IMO makes code look much cleaner than otherwise.
Here's your code snippet with vars:
var date1 = new DateTime(byear, bmonth, bday, 0, 0, 0);
var datenow = DateTime.Now;
var date2 = datenow - date1;
EDIT:
For the C# developers with the var-is-bad mindset:
[ Original Post Here ]
I use var extensively. There has been
criticism that this diminishes the
readability of the code, but no
argument to support that claim.
Admittedly, it may mean that it's not
clear what type we are dealing with.
So what? This is actually the point of
a decoupled design. When dealing with
interfaces, you are emphatically not
interested in the type a variable has.
var takes this much further, true, but
I think that the argument remains the
same from a readability point of view:
The programmer shouldn't actually be
interested in the type of the variable
but rather in what a variable does.
This is why Microsoft also calls type
inference “duck typing.”
So, what does a variable do when I
declare it using var? Easy, it does
whatever IntelliSense tells me it
does. Any reasoning about C# that
ignores the IDE falls short of
reality. In practice, every C# code is
programmed in an IDE that supports
IntelliSense.
If I am using a var declared variable
and get confused what the variable is
there for, there's something
fundamentally wrong with my code. var
is not the cause, it only makes the
symptoms visible. Don't blame the
messenger.
Now, the C# team has released a coding
guideline stating that var should only
be used to capture the result of a
LINQ statement that creates an
anonymous type (because here, we have
no real alternative to var). Well,
screw that. As long as the C# team
doesn't give me a sound argument for
this guideline, I am going to ignore
it because in my professional and
personal opinion, it's pure baloney.
(Sorry; I've got no link to the
guideline in question.)
Actually, there are some
(superficially) good explanations on
why you shouldn't use var but I still
believe they are largely wrong. Take
the example of “searchabililty”: the
author claims that var makes it hard
to search for places where MyType is
used. Right. So do interfaces.
Actually, why would I want to know
where the class is used? I might be
more interested in where it is
instantiated and this will still be
searchable because somewhere its
constructor has to be invoked (even if
this is done indirectly, the type name
has to be mentioned somewhere). -
Konrad Rudolph

Categories