How can I pad nullable ints with zeros? - c#

Is there any way to pad nullable int with zeros the way you can with normal int?
the myInt.ToString("D3") doesn't seem to work on nullale ints but for my current project I feel like I need to use nullable int in order to get the null value in my array instead of 0 as the default.

That is because int? is actually Nullable<T> where T is int here.
Calling ToString will call that on the Nullable struct, not the int. Nullable<T> has no knowledge of the overloads of ToString which int has.
You have to get the integer value first:
myInt.GetValueOrDefault(0).ToString("D3")

An int has never leading zeros, it just has a value. A string representation of an ìnt can have them. You can use the null-coalescing operator to convert the nullable-int to 0 if it has no value:
int? nullableInt = null;
string number = (nullableInt ?? 0).ToString("D3"); // 000
or use String.PadLeft:
number = (nullableInt ?? 0).ToString().PadLeft(3, '0');

You have to perform that action on the value:
myInt.Value.ToString("D3")
Example:
int? myInt = 3;
Console.WriteLine(myInt.Value.ToString("D3")); // Outputs 003

Related

What is the meaning of the ? operator? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
C# using the question mark after a type, for example: int? myVariable; what is this used for?
I saw the ? operator used in many places and tried to Google and StackOverflow it but both search engine exclude it from the query and does not return any good answers.
What is the meaning of this operator? I usually see it after the type declaration like:
int? x;
DateTime? t;
What is the difference between the two following declaration of an int for example:
int? x;
// AND
int x;
This operator is not an operator, but merely the syntactic sugar for a Nullable type:
int? x;
is the same as
Nullable<int> x;
You can read this : Nullable type -- Why we need Nullable types in programming language ?
int? x;//this defines nullable int x
x=null; //this is possible
// AND
int x; // this defines int variable
x=null;//this is not possible
It is not operator, but int? is shortcut for the Nullable<int>. Nullable<> is container that allows to set some value-type variable null value as well.
It called nullable types.
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.
int? x;
is equivalent to
Nullable<int> x;
? operator indicates the type is nullable.
For example;
int? x = null; //works properly since x is nullable
and
int x = null; //NOT possible since x is NOT nullable
Note that the way you access the value of the variable changes;
int? x = null;
int y = 0;
if (x.HasValue)
{
y = x.Value; // OK
}
And
y = x; //not possible since there is no direct conversion between types.
Diffrence b/w int? and int is int? can store null but int can't.
int? is called nullable operators and its used basically when working with database entities.
more info -http://msdn.microsoft.com/en-us/library/1t3y8s4s(v=vs.80).aspx
hope this helps !!
That operator makes all objects that is non nullable to nullable.
So it means if you will declare a variable int? x, it could be assigned like this:
int? x = null. If without the ? sign, you cannot assign it with a null value.

Check if decimal value is null

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);
}

Why type "int" is never equal to 'null'?

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.

What is 'long?' data type?

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.

How to check for valid value before converting Decimal

I assume this will blow up if total is null (I don't recall if decimals are initalized to null at the beginning or zero)
public int SomePropertyName
{
get { return Convert.ToInt32(Decimal.Round(total)); }
}
So should I check for null or > 0 ?
Decimal is a value type - there's no such value as "null" for a decimal.
However, it's perfectly possible for a decimal to be out of range for an int. You might want:
decimal rounded = decimal.Round(total);
if (rounded < int.MinValue || rounded > int.MaxValue)
{
// Do whatever you ought to here (it will depend on your application)
}
return (int) rounded;
I'm somewhat confused as to why you're using Convert.ToInt32 at all though, given that your property is declared to return a decimal. What's the bigger picture here? What are you trying to achieve?
Decimal is a value type and can not be null.
If you need to know if it had been initialized, you should probably use a nullable decimal:
Decimal? total = null;
public int SomePropertyName
{
get
{
if (total.HasValue) Convert.ToInt32(Decimal.Round(total.Value));
return 0; // or whatever
}
}
Decimals are value types, and so cannot be null.
So no need to check there..
As others have said, Decimal is a value type and cannot be null. However, if converting from a string then Decimal.TryParse is your friend...
System.Decimal is a value type, so it cannot be null. Second thing, the method's return value is decimal, so why would you want to convert to a Int32?

Categories

Resources