I am going over some code written by another developer and am not sure what long? means:
protected string AccountToLogin(long? id)
{
string loginName = "";
if (id.HasValue)
{
try
{....
long is the same as Int64
long data type
The ? means it is nullable
A nullable type can represent the
normal range of values for its
underlying value type, plus an
additional null value
Nullable Types
Nullable example:
int? num = null;
if (num.HasValue == true)
{
System.Console.WriteLine("num = " + num.Value);
}
else
{
System.Console.WriteLine("num = Null");
}
This allows you to actually check for a null value instead of trying to assign an arbitrary value to something to check to see if something failed.
I actually wrote a blog post about this here.
long is an Int64, the ? makes it nullable.
"long?" is a nullable 64-bit signed integer. It's equivalent to Nullable<Int64>.
long? is a 64-bit, nullable integer.
To clarify, nullable means it can be null or an integer number ( 0, 1, etc.).
long? is a nullable type. This means that the id parameter can have a long value or be set to null. Have a look at the HasValue and Value properties of this parameter.
It's a nullable type declaration.
Related
I have Type and I want to get the default value. For example, if Type is class or nullable I should get null. But if it is integer, DateTime. decimal, ... I should get 0. What is the best way of doing this?
From your description you can just use a default expression or literal.
int a = default(int);
int a = default;
Default values of C# types (C# reference)
Type
Default value
Any reference type
null
Anybuilt-in integral numeric type
0 (zero)
Any built-in floating-point numeric type
0 (zero)
bool
false
char
'\0' (U+0000)
enum
The value produced by the expression (E)0, where E is the enum identifier.
struct
The value produced by setting all value-type fields to their default values and all reference-type fields to null.
Any nullable value type
An instance for which the HasValue property is false and the Value property is undefined. That default value is also known as the null value of a nullable value type.
I expect you can use something like this:
public static object GetDefaultValue(Type type)
{
return type.IsClass ? null : Activator.CreateInstance(type);
}
Try it online
You could use Activator.CreateInstance to generate an empty variable of the type and then check the value of it :)
I would like to check if the decimal number is NULL or it has some value, since the value is assigned from database in class object:
public decimal myDecimal{ get; set; }
and then I have
myDecimal = Convert.ToDecimal(rdrSelect[23].ToString());
I am trying:
if (rdrSelect[23] != DBNull.Value)
{
myDecimal = Convert.ToDecimal(rdrSelect[23].ToString());
}
But I am getting this:
the result of the expression is always 'true' since a value of type
'decimal' is never equal to null
How can I check if that decimal number has some value?
A decimal will always have some default value. If you need to have a nullable type decimal, you can use decimal?. Then you can do myDecimal.HasValue
you can use this code
if (DecimalVariable.Equals(null))
{
//something statements
}
decimal is a value type in .NET. And value types can't be null. But if you use nullable type for your decimal, then you can check your decimal is null or not. Like myDecimal?
Nullable types are instances of the System.Nullable struct. A nullable
type can represent the normal range of values for its underlying value
type, plus an additional null value.
if (myDecimal.HasValue)
But I think in your database, if this column contains nullable values, then it shouldn't be type of decimal.
I've ran across this problem recently while trying to retrieve a null decimal from a DataTable object from db and I haven't seen this answer here. I find this easier and shorter:
var value = rdrSelect.Field<decimal?>("ColumnName") ?? 0;
This was useful in my case since i didn't have a nullable decimal in the model, but needed a quick check against one. If the db value happens to be null, it'll just assign the default value.
Assuming you are reading from a data row, what you want is:
if ( !rdrSelect.IsNull(23) )
{
//handle parsing
}
Decimal is a value type, so if you wish to check whether it has a value other than the value it was initialised with (zero) you can use the condition myDecimal != default(decimal).
Otherwise you should possibly consider the use of a nullable (decimal?) type and the use a condition such as myNullableDecimal.HasValue
If you're pulling this value directly from a SQL Database and the value is null in there, it will actually be the DBNull object rather than null. Either place a check prior to your conversion & use a default value in the event of DBNull, or replace your null check afterwards with a check on rdrSelect[23] for DBNull.
You can also create a handy utility functions to handle values from DB in cases like these.
Ex. Below is the function which gives you Nullable Decimal from object type.
public static decimal? ToNullableDecimal(object val)
{
if (val is DBNull ||
val == null)
{
return null;
}
if (val is string &&
((string)val).Length == 0)
{
return null;
}
return Convert.ToDecimal(val);
}
int n == 0;
if (n == null)
{
Console.WriteLine("......");
}
Is it true that the result of expression (n == null) is always false since
a value of type int is never equal to null of type int? (see warning below)
Warning CS0472 The result of the expression is always 'false' since a value of type 'int' is never equal to 'null' of type 'int?'
If you want your integer variable to allow null values, declare it to be a nullable type:
int? n = 0;
Note the ? after int, which means that type can have the value null. Nullable types were introduced with v2.0 of the .NET Framework.
In C# using an uninitialized variable is not allowed.
So
int i;
Console.Writeline(i);
Results in a compilation error.
You can initialize int with new such as:
int anInt = new int();
This will result in the Default value for int which is 0. In cases where you do wish to have a generic int one can make the int nullable with the syntax
int? nullableInt = null;
Because int is a value type rather than a reference type. The C# Language Specification doesn't allow an int to contain null. Try compiling this statement:
int x = null ;
and see what you get.
You get the compiler warning because it's a pointless test and the compiler knows it.
"Value types" in .NET (like int, double, and bool) cannot, by definition, be null - they always have an actual value assigned. Check out this good intro to value types vs. reference types.
The usage of NULL applies to Pointers and References in general. A value 0 assigned to an integer is not null. However if you can assign a pointer to the integer and assign it to NULL, the statement is valid.
To sum up =>
/*Use the keyword 'null' while assigning it to pointers and references. Use 0 for integers.*/
Very simply put, an int is a very basic item. It's small and simple so that it can be handled quickly. It's handled as the value directly, not along the object/pointer model. As such, there's no legal "NULL" value for it to have. It simply contains what it contains. 0 means a 0. Unlike a pointer, where it being 0 would be NULL. An object storing a 0 would have a non-zero pointer still.
If you get the chance, take the time to do some old-school C or assembly work, it'll become much clearer.
public static int? n { get; set; } = null;
OR
public static Nullable<int> n { get; set; }
or
public static int? n = null;
or
public static int? n
or just
public static int? n { get; set; }
static void Main(string[] args)
{
Console.WriteLine(n == null);
//you also can check using
Console.WriteLine(n.HasValue);
Console.ReadKey();
}
The null keyword is a literal that represents a null reference, one that does not refer to any object.
In programming, nullable types are a feature of the type system of some programming languages which allow the value to be set to the special value NULL instead of the usual possible values of the data type.
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/null
https://en.wikipedia.org/wiki/Null
No, because int is a value type. int is a Value type like Date, double, etc. So there is no way to assigned a null value.
private int? _City_Id;
Without knowing your target language to respond with, in C# 2.0 the ? denotes nullable value types.
Nullable value types (denoted by a question mark, e.g. int? i = null;) which add null to the set of allowed values for any value type.
Which, as Calum points out (all credit to him), means that the variable can be assigned null. Normally primitives like int and double can't be null,
int? x = 10;
double? d = 4.108
Typically the main use of the question mark is for the conditional, x ? "yes" : "no".
But I have seen another use for it but can't find an explanation of this use of the ? operator, for example.
public int? myProperty
{
get;
set;
}
It means that the value type in question is a nullable type
Nullable types are instances of the System.Nullable struct. A
nullable type can represent the correct range of values for its
underlying value type, plus an additional null value. For example, a
Nullable<Int32>, pronounced "Nullable of Int32," can be assigned any
value from -2147483648 to 2147483647, or it can be assigned the null
value. A Nullable<bool> can be assigned the values true, false, or
null. The ability to assign null to numeric and Boolean types is
especially useful when you are dealing with databases and other data
types that contain elements that may not be assigned a value. For
example, a Boolean field in a database can store the values true or
false, or it may be undefined.
class NullableExample
{
static void Main()
{
int? num = null;
// Is the HasValue property true?
if (num.HasValue)
{
System.Console.WriteLine("num = " + num.Value);
}
else
{
System.Console.WriteLine("num = Null");
}
// y is set to zero
int y = num.GetValueOrDefault();
// num.Value throws an InvalidOperationException if num.HasValue is false
try
{
y = num.Value;
}
catch (System.InvalidOperationException e)
{
System.Console.WriteLine(e.Message);
}
}
}
It is a shorthand for Nullable<int>. Nullable<T> is used to allow a value type to be set to null. Value types usually cannot be null.
In
x ? "yes" : "no"
the ? declares an if sentence. Here: x represents the boolean condition; The part before the : is the then sentence and the part after is the else sentence.
In, for example,
int?
the ? declares a nullable type, and means that the type before it may have a null value.
it declares that the type is nullable.
practical usage:
public string someFunctionThatMayBeCalledWithNullAndReturnsString(int? value)
{
if (value == null)
{
return "bad value";
}
return someFunctionThatHandlesIntAndReturnsString(value);
}
int? is shorthand for Nullable<int>. The two forms are interchangeable.
Nullable<T> is an operator that you can use with a value type T to make it accept null.
In case you don't know it: value types are types that accepts values as int, bool, char etc...
They can't accept references to values: they would generate a compile-time error if you assign them a null, as opposed to reference types, which can obviously accept it.
Why would you need that?
Because sometimes your value type variables could receive null references returned by something that didn't work very well, like a missing or undefined variable returned from a database.
I suggest you to read the Microsoft Documentation because it covers the subject quite well.
Means that the variable declared with (int?) is nullable
int i1=1; //ok
int i2=null; //not ok
int? i3=1; //ok
int? i4=null; //ok
To add on to the answers above, here is a code sample
struct Test
{
int something;
}
struct NullableTest
{
int something;
}
class Example
{
public void Demo()
{
Test t = new Test();
t = null;
NullableTest? t2 = new NullableTest();
t2 = null;
}
}
This would give a compilation error:
Error 12 Cannot convert null to 'Test' because it is a non-nullable
value type
Notice that there is no compilation error for NullableTest. (note the ? in the declaration of t2)
To add on to the other answers:
Starting in C# 8.0, Nullable<> and ? are NOT always interchangeable. Nullable<> only works with Value types, whereas ? works with both Reference and Value types.
These can be seen here in the documentation
"A nullable reference type is noted using the same syntax as nullable
value types: a ? is appended to the type of the variable."
And here
public struct Nullable<T> where T : struct