private string? typeOfContract
{
get { return (string?)ViewState["typeOfContract"]; }
set { ViewState["typeOfContract"] = value; }
}
Later in the code I use it like this:
typeOfContract = Request.QueryString["type"];
I am getting the following error at the declaration of typeOfContract line stating:
The type 'string' must be a non-nullable value type in order to use
it as parameter 'T' in the generic type or method
'System.Nullable<T>'
Any ideas? Basically, I want to make sure that "type" exists in the QueryString before performing an action.
System.String is a reference type and already "nullable".
Nullable<T> and the ? suffix are for value types such as Int32, Double, DateTime, etc.
You are making it complicated. string is already nullable. You don't need to make it more nullable. Take out the ? on the property type.
string cannot be the parameter to Nullable because string is not a value type. String is a reference type.
string s = null;
is a very valid statement and there is not need to make it nullable.
private string typeOfContract
{
get { return ViewState["typeOfContract"] as string; }
set { ViewState["typeOfContract"] = value; }
}
should work because of the as keyword.
String is a reference type, so you don't need to (and cannot) use Nullable<T> here. Just declare typeOfContract as string and simply check for null after getting it from the query string. Or use String.IsNullOrEmpty if you want to handle empty string values the same as null.
For nullable, use ? with all of the C# primitives, except for string.
The following page gives a list of the C# primitives:
http://msdn.microsoft.com/en-us/library/aa711900(v=vs.71).aspx
Related
New to C#. I am trying this code, which I copied from w3school User Input
using System;
namespace Sample
{
class Test
{
public static void Main(string[] args)
{
string testString;
Console.Write("Enter a string - ");
testString = Console.ReadLine();
Console.WriteLine("You entered '{0}'", testString);
}
}
}
But after I execute the Program, it shows an error at Console.ReadLine();
Converting null literal or possible null value to non-nullable type.
you need to handle nullable try to replace
string testString;
with
string? testString = null;
or
string testString="";
In the declaration of testString, take note of the ? symbol that has been added after the data type. This shows that the variable can have a null value, which means it is nullable.
In recent versions of .NET, nullable reference types are supported by default and Console.ReadLine returns a nullable string. That means that you need to either declare your variable as nullable:
string? testString;
or specify that the return value will definitely not be null:
testString = Console.ReadLine()!;
If you use the former, you'll have allow for that when you use the variable later. The latter is OK because, in a console window, it will never be null.
You ought to do some reading on nullable reference types.
You need to make sure that you have a valid non-null string.
You could do this for example to make sure that it's valid before printing it to the console using the formatter:
testString = Console.ReadLine() ?? string.Empty;
This will assign an empty string to the testString variable in case that ReadLine() returns null.
I am new to c# so i need some guidance with this.
string NumInput = Console.ReadLine();
in my code, this statement gives the warning of
converting null literal or possible null value to non-nullable type.
Is there any alternative to this code line or anything which can make this warning disapear
Firstly, you are seeing this message because you have the C# 8 Nullable reference type feature enabled in your project.
Console.ReadLine() returns a value that can be either a string or null but you are using it to set a variable of type string. Instead either use the var keyword which will implicitly set your variable to the same type as the return value or manually set your variable as type nullable string string?. the ? denotes a nullable reference type.
You may then want to check that your variable does infact hold a string before you use it:
string? NumInput = Console.ReadLine();
if (NumInput == null)
{
// ...
}
I've made a method to convert a datetime object to a date-only format. In order to access it, I have to assign the value of my parameter to the value that will be in a datatable. The obvious method would thus be to add a ? after the DateTime object to make it nullable, however this removes it's methods (or at least, the one I need to use), making my method worthless.
string dateWithOutTime(DateTime? datetime)
{
string reply = datetime.Date.ToString();
return reply;
}
usage:
string str = dateWithOutTime(*DataSet*.*DataTable[n]*.Rows[n][n] as DateTime?);
Is there a way to accomplish this without adding any extra objects?
Note: a star (*) denotes a variable type/object
DateTime? doesn't have the same methods as DateTime, they're different types. You have to retrieve the actual datetime value using DateTime?'s Value property:
string dateWithOutTime(DateTime? datetime)
{
if(datetime.HasValue)
return datetime.Value.Date.ToString();
else
return //...
}
Read the documentation for Nullable<T> here.
Unless I misunderstand your problem, I'd say you need to check if your DateTime? parameter is null or not. If it is, return an empty string (or a string you want to display for missing dates). If it isn't, you can use the Value property:
string dateWithOutTime(DateTime? datetime)
{
return datetime.HasValue ? datetime.Value.Date.ToString() : String.Empty;
}
Update
If you only want the date-part in your string and you want it to be culture-sensitive, you can use ToShortDateString() instead of ToString(). You can even leave out the Date property:
string dateWithOutTime(DateTime? datetime)
{
return datetime.HasValue
? datetime.Value.ToShortDateString()
: String.Empty;
}
I have a Convert method that implements IValueConverter. My first statement is
var returnText = value as string not working to take over the value as string. However, it doesn't work and when I was debugging, I found out the value of the "value" variable didn't assign over to returnText so the returnText is always null. It is odd. Does anybody know why?
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var returnText = value as string;
if (!string.IsNullOrEmpty(returnText))
{
.....
Problem and Solution
The problem is that as string does not convert, it just casts the object to a string. If that doesn't work it will produce null instead. The object must be of string type originally, in this case that is obviously not the case.
One option that would likely work in your case is to call .ToString() on the object like so:
var returnText = value.ToString();
but please note that this really does depend on your object type, and what it's .ToString() method actually produces. You may get a value that you do not expect.
Additional Recommendations
As Tim has commented, ToString() will throw an exception if the object is null to begin with. It is recommended to test for this before calling any method on the object. Something like this will do:
string returnText = null;
if(value != null)
returnText = value.ToString();
Further Reading
See here for more information. A couple of useful quotes from that link:
The as operator is like a cast operation. However, if the conversion isn't possible, as returns null instead of raising an exception.
and
Note that the as operator performs only reference conversions, nullable conversions, and boxing conversions. The as operator can't perform other conversions, such as user-defined conversions, which should instead be performed by using cast expressions.
try
var returnText = value==null ? "": value.ToString();
Because this var returnText = value as string; means: Try to cast value as string if not, return null.
as (C# Reference) http://msdn.microsoft.com/en-us/library/vstudio/cscsdfbt.aspx
Why System.Convert.ToString() instead of .ToString()......
I'd rather use var returnText = System.Convert.ToString(value); because this will use the IConvertable interface. The ToString() could give a screwed-up result. (like classnames etc)
More info: Convert.ToString Method http://msdn.microsoft.com/en-us/library/astxcyeh.aspx
I'm trying to dynamically set an enum based on the value in a string so far so good I don't know what I've been doing wrong. I have the following code:
public enum TagLabels : long
{
TurnLeft = 0x0000000000000000000030A38DB1,
TurnRight = 0x00000000000000000000307346CC,
LiftApproach = 0x0000000000000000000012107A8D
}
TagLabels IDs;
string someID = "0x0000000000000000000012107A8D";
IDs = (TagLabels)Enum.Parse(typeof(TagLabels), someID ); //<== I get runtime error on this line
I cannot see what's wrong with what I'm doing.
Enum.Parse is intended to convert a string representation of the symbolic name into an enum val, as in Enum.Parse("TurnLeft"). If what you have is a string giving the numeric value, then you should just parse the string as the corresponding integer type and cast it to the Enum val.
IDs = (TagLabels)long.Parse("0x0000000000000000000012107A8D");
IDs = (TagLabels)Convert.ToInt64(someID, 16);
EDIT: You have a string that is in hex format and not a direct number. So, it needs conversion to int first.
If the Enum value exists, you can cast an int value to Enum type.
EDIT2: Changed after Marc's suggestion from Convert.ToInt32 to Convert.ToInt64
SomeID is a string and your enum is a long.
Try using TurnLeft instead of "0x0000000000000000000012107A8D"
Where is the string you're parsing? Aren't you trying to turn a string like "TurnLeft" into TagLabels.TurnLeft?
MSDN