Use of unassigned local variable 'strCity' - c#

this is the error its giving, my biz code is fine as well as stored procedure, without "strCity" variable everything was working fine, but the moment i added this addition, is causing me trouble
txtCityName.Text = null;
string strVal = hdnOption.Value;
IFormatProvider provider = new System.Globalization.CultureInfo("en-GB", true);
DateTime dtStart = new DateTime();
DateTime? dtEnd = null;
string strCity;
if (strVal == "today")
{
HideCustomSearch();
dtStart = DateTime.Today;
dtEnd = DateTime.Today;
strCity = txtCityName.Text.ToString().Trim();
}
if (strVal == "weekly")
{
HideCustomSearch();
dtStart = DateTime.Now.AddDays(-7).Date;
dtEnd = DateTime.Today;
strCity = txtCityName.Text.ToString().Trim();
}
if (strVal == "byweekly")
{
HideCustomSearch();
dtStart = DateTime.Now.AddDays(-15).Date;
dtEnd = DateTime.Today;
strCity = txtCityName.Text.ToString().Trim();
}
if (strVal == "monthly")
{
HideCustomSearch();
dtStart = DateTime.Now.AddMonths(-1).Date;
dtEnd = DateTime.Today;
strCity = txtCityName.Text.ToString().Trim();
}
if (strVal == "yearly")
{
HideCustomSearch();
dtStart = DateTime.Now.AddYears(-1).Date;
dtEnd = DateTime.Today;
strCity = txtCityName.Text.ToString().Trim();
}
if (strVal == "custom")
{
ShowCustomSearch();
dtStart = DateTime.Now;
dtEnd = DateTime.Now;
strCity = txtCityName.Text.ToString().Trim();
strCity = null;
hdndtStart.Value = txtdtStart.ToString();
hdndtEnd.Value = txtdtEnd.Text.ToString();
}
FillGridFilter(dtStart, dtEnd, strCity);
P.S. its giving me error on last line "strCity" only

Your error occures because you have not got an 'else' anywhere after the ifs. The compiler can not verify that the value 'strCity' will ever be assigned (there might be a number of different options for 'strVal ').
You therefor have to assign a default value.
Writing the code as a switch statement:
http://msdn.microsoft.com/en-us/library/vstudio/06tc147t.aspx
would probable make it more clear since you can define a 'default' case in those situations.

Better still, assign null to strCity, use else if instead of if in your conditional logic and test for strCity being null before your call to FillGridFilter.
From what I can see all the possible options for your strVal variable are mutually exclusive so there is no need to force re-evaluation of it in each test.

You have to assign some default value to local variables.
This error is given in your case because compiler is thinking string strCity; may never get assigned value.
While declaring string strCity; assign some value to it.
string strCity="";
or
string strCity=string.Empty;
Try this, error will go.

Because you have used if staments with lot of conditions. The value will be assigned at runtime to the strCity variable.But after the if statement the strCity you have used as parameter to the function FillGridFilter so the compiler will not sure the if condition is exicutes or not. that's way
Error
Use of unassigned local variable 'strCity'
it's showing
so better to assign the default value to the variable strCity

Better to put
string strCity=null;
or
string strCity=String.Empty;
But make sure that FillGridFilter function handles the null or empty value.
Regards,
Nitin Joshi

Related

C# DateTime and String value condition check

I have a problem.
This is not working
> var from = "";
> StartDTime = Convert.ToDateTime(from);
This is working
> var from = "2021-10-05";
> StartDTime = Convert.ToDateTime(from);
Some time I'm sending Date Value, but sometime in not sending Date Value.in that time from variable pass as a empty string. I want to set if from variable is = "" then need to set default Date Value.so how can I resolve this?. Please help me guys. Thank you
A safe way of doing that would be:
StartDTime = string.IsNullOrEmpty(from) ? DateTime.Now : DateTime.Parse(from);
But if you have control over the code passing the "from" variable, you can declare it as nullable DateTime, then your code would look like this:
DateTime? from = null;
var StartDTime = from.HasValue ? from.Value : DateTime.Now;
Which for short would be:
StartDTime = from ?? DateTime.Now;
DateTime.TryParse will do the job for you:
for example:
DateTime dateTime;
var from = "";
DateTime.TryParse(from, out dateTime);
One-liner, with only the validation you specify:
StartDTime = from == "" ? new DateTime() : Convert.ToDateTime(from);
It's not ellegant, but works.
var from = "";
if(from == ""){ from = DateTime.MinValue.ToString(); }
DateTime StartDTime = Convert.ToDateTime(from);
But i think that a nullable DateTime would be more elegant, like this:
var from = null;
DateTime? StartDTime = from;
Or you can set a default date, like this:
var from = null;
DateTime? StartDTime = from ?? YourDefaultDate;
Convert methods either successfully convert the string passed to it, or throws an error, that's the way it's supposed to work. For most data types there are also TryParse methods that return true/false based on if it converted successfully and have an output variable which will be DateTime.MinValue if it failed. This is how I would handle your situation:
DateTime startDTime;
string from = "";
if (!DateTime.TryParse(from, out startDTime)){
startDTime = DateTime.Now;
}
This will set the startTime to the date passed in from, but if no date was passed it sets it to the current date and time - if you want a different default value, that replaces new DateTime() and if your default should be January 1, 0001, then you can just use the TryParse part directly, since that's the automatic default for a failed TryParse.

Trouble with setting values in a class to .Empty

I'm creating a program that uses Microsoft access and i'm having trouble with setting a value in a class to .Empty. It works fine with a string but it does not work with int or DateTime, i'm wondering what could I use instead?
public CustomerData()
{
FirstName = string.Empty;
LastName = string.Empty;
Company = string.Empty;
Question1 = string.Empty;
Question2 = string.Empty;
Question3 = string.Empty;
Question4 = string.Empty;
Question5 = int.Empty;
FeedbackComments = string.Empty;
FDate = DateTime.Empty;
}
There is no Empty property for DateTime class, probably you should use MinValue; property to initialize the date time variable. which will initialize the variable with 1/1/0001 12:00:00 AM. So the code for this would be
FDate = DateTime.MinValue;
Read more about DateTime.MinValue, Same in the case of int.Empty, you can use 0 instead or int.MinValue which will give you -2147483648
A DateTime object is of different type from a String object and there isn't any implicit conversion between them. Hence, you can't assign a String value to a variable that can hold DateTime values. I would say that you have two otpions
Use the DateTime.MinValue, FDate = DateTime.MinValue.
Redeclare the type of value as DateTime? and set the value of null.

Find TotalDays between two Datetime? variables

DateTime? arrival = (DateTime?)(t.ArrivalDate.Value);
DateTime? departure = (DateTime?)(t.DepartureDate);
Okay i know both of them are nullable and .TotalDays does not work on nullable object. So kindly tell me how am i supposed to find days difference between these two objects.
Note:
Both objects contains Date(s) i.e. are not null
Since there's no meaningful value to their difference if any of them is null, you only need to concern yourself with the case where they're not:
DateTime? arrival = (DateTime?)(t.ArrivalDate.Value);
DateTime? departure = (DateTime?)(t.DepartureDate);
double? totalDays = arrival.HasValue && departure.HasValue
? (double?)(departure - arrival).GetValueOrDefault().TotalDays
: null;
The subtraction should work because of implicit casting to DateTime.
Note: Both objects contains Date(s) i.e. are not null
If you are sure that dates never have null then you can use .Value for nullable DateTime objects. You will get exception when any of them is null.
double days = departure.Value.Subtract(arrival.Value).TotalDays;
//Set dates
DateTime? beginDate = DateTime.Now;
DateTime? endDate = DateTime.Now.AddDays(10);
//Check both values have a value (they will based on above)
//If they do get the ticks between them
long diff = 0;
if (beginDate.HasValue && endDate.HasValue)
diff = endDate.Value.Ticks - beginDate.Value.Ticks;
//Get difference in ticks as a time span to get days between.
int daysDifference = new TimeSpan(diff).Days;
Here i give you tested code please have a look :
DateTime? startDate = DateTime.Now;
DateTime? endDate = DateTime.Now.AddDays(5);
long differenceOfDays = 0;
if (startDate.HasValue && endDate.HasValue)
differenceOfDays = endDate.Value.Ticks - startDate.Value.Ticks;
int daysDifference = new TimeSpan(differenceOfDays).Days;

Set an empty DateTime variable

I would declare an empty String variable like this:
string myString = string.Empty;
Is there an equivalent for a 'DateTime' variable ?
Update :
The problem is I use this 'DateTime' as a parameter for a 'StoredProcedure' in SQL.
E.g:
DateTime? someDate = null;
myCommand.Parameters.AddWithValue("#SurgeryDate", someDate);
When I run this code an exception is catched telling me the 'StoredProcedure' expected a '#SurgeryDate' parameter.
But i provided it.
Any idea why?
Since DateTime is a value type you cannot assign null to it, but exactly for these cases (absence of a value) Nullable<T> was introduced - use a nullable DateTime instead:
DateTime? myTime = null;
No. You have 2 options:
DateTime date = DateTime.MinValue;
This works when you need to do something every X amount of time (since you will always be over MinValue) but can actually cause subtle errors (such as using some operators w/o first checking if you are not MinValue) if you are not careful.
And you can use Nullable:
DateTime? date = null;
Which is nice and avoids most issues while introducing only 1 or 2.
It really depends on what you are trying to achieve.
You can set a DateTime variable to be '1/1/0001 00:00:00' but the variable itself cannot be null. To get this MinTime use:
DateTime variableName = DateTime.MinValue;
You may want to use a nullable datetime. Datetime? someDate = null;
You may find instances of people using DateTime.Max or DateTime.Min in such instances, but I highly doubt you want to do that. It leads to bugs with edge cases, code that's harder to read, etc.
The method you used (AddWithValue) doesn't convert null values to database nulls. You should use DBNull.Value instead:
myCommand.Parameters.AddWithValue(
"#SurgeryDate",
someDate == null ? DBNull.Value : (object)someDate
);
This will pass the someDate value if it is not null, or DBNull.Value otherwise. In this case correct value will be passed to the database.
Either:
DateTime dt = new DateTime();
or
DateTime dt = default(DateTime);
If you set the date to
DateTime dNewDate = new DateTime();
The value is set to {1/1/0001 12:00:00 AM}
Option 1: Use a nullable DateTime?
Option 2: Use DateTime.MinValue
Personally, I'd prefer option 1.
A string is a sequence of characters. So it makes sense to have an empty string, which is just an empty sequence of characters.
But DateTime is just a single value, so it's doesn't make sense to talk about an “empty” DateTime.
If you want to represent the concept of “no value”, that's represented as null in .Net. And if you want to use that with value types, you need to explicitly make them nullable. That means either using Nullable<DateTime>, or the equivalent DateTime?.
DateTime (just like all value types) also has a default value, that's assigned to uninitialized fields and you can also get it by new DateTime() or default(DateTime). But you probably don't want to use it, since it represents valid date: 1.1.0001 0:00:00.
There's no such thing as an empty date per se, do you mean something like:
DateTime? myDateTime = null;
The .addwithvalue needs dbnull.
You could do something like this:
DateTime? someDate = null;
//...
if (someDate == null)
myCommand.Parameters.AddWithValue("#SurgeryDate", DBnull.value);
or use a method extension...
public static class Extensions
{
public static SqlParameter AddWithNullValue(this SqlParameterCollection collection, string parameterName, object value)
{
if (value == null)
return collection.AddWithValue(parameterName, DBNull.Value);
else
return collection.AddWithValue(parameterName, value);
}
}
This will work for null able dateTime parameter
. .
SearchUsingDate(DateTime? StartDate, DateTime? EndDate){
DateTime LastDate;
if (EndDate != null)
{
LastDate = (DateTime)EndDate;
LastDate = LastDate.AddDays(1);
EndDate = LastDate;
}
}

Variable Context Question

In the following code snippet, if I leave out the line of code that is surrounded by the /////'s, I get an error that reads: "Use of unassigned local variable CurrentDate". It seems a bit silly for me to just give CurrentDate an arbitrary value, is there a better way around this?
DateTime CurrentDate;
///////////////////////////
CurrentDate = DateTime.Now;
///////////////////////////
if(1==1)
{
CurrentDate = DateTime.Now.AddDays(1);
}
if(CurrentDate == DateTime.Now)
{
...
}
Don't do if (1 == 1)?
Seriously though if the compiler is giving you this error it's usually either because your code is wrong or it's because it's too complex and could be better expressed in another way where you don't need to access possibly unassigned variables.
Can you come up with a real world example where you get this error where there isn't an obvious solution by making a simple refactoring? This would make your question more answerable.
Having said that if you do run into one of these situations there are a few other approaches you could use:
DateTime CurrentDate = DateTime.MaxValue;
DateTime CurrentDate = default(DateTime);
DateTime? CurrentDate = null;
I like the last option because it expresses what you mean - that you don't know the value. It makes the code a little more verbose though as you have an extra level of redirection every time you wish to access a value. You can use the time spent typing .Value to consider whether or not you have correctly handled the situation where it could be null.
Also: Have you considered that the value of DateTime.Now could change between the first and second calls? That final if statement looks like it won't do what you intended.
You could do this:
DateTime CurrentDate;
if(1==1)
{
CurrentDate = DateTime.Now.AddDays(1);
}
else
{
///////////////////////////
CurrentDate = DateTime.Now;
///////////////////////////
}
if(CurrentDate == DateTime.Now)
{
...
}
This will eliminate the compiler error.
NOTE: in VS2008 this will compile:
if(1==1)
{
CurrentDate = DateTime.Now.AddDays(1);
}
//else
//{
/////////////////////////////
//CurrentDate = DateTime.Now;
/////////////////////////////
//}
if(CurrentDate == DateTime.Now)
{
//
}
why dont just assigned directly
DateTime CurrentDate = DateTime.Now;
The example is a bit convoluted, but, no, there isn't a better way around that.
You have to assign a value to a variable heading into a conditional block, even if you are sure that the block will always execute (the 1=1 in your example)
However, I would recommend against DateTime.Now as the initialization value, because it by some mirracle, the block does not execute, the situation should be easily detectable, and DateTime.Now sound way more real than DateTime.MinValue
I always set my objects to null so that it throws a null reference exception if a value is not created. However as Hans pointed out null doesn't work in this situation because in their infinite wisdom Microsoft decided to make DateTime not nullable. As such I normally use DateTime.MinValue since it gives me a specific value to check for and other than time traveling will always be in the past unlike DateTime.MaxValue which is coming up here for some of you archaic 32bit peeps.
Example
DateTime CurrentDate;
///////////////////////////
CurrentDate = DateTime.MinValue;
///////////////////////////
if(1==1)
{
CurrentDate = DateTime.Now.AddDays(1);
}
if(CurrentDate == DateTime.Now)
{
...
}

Categories