How to make an integer field accepts null values?
[Range(10, 65]
[Display(Name = "oh")]
public int oh { get; set; }
I'm currently using this code, but I'm getting not null on sql server (I haven't used [Required]).
Thanks a lot!
Use ? keyword
public int? oh { get; set; }
It makes the type a Nullable type. Now you can set null to oh
And then check for its value by:
if(oh.HasValue){
Console.WriteLine(oh.Value)
}
.HasValue says if it has value or null.
.Value gets you the actual value
use
int? for the data type.
I don't know how this will work in conjunction with Range...
You can use a nullable type:
int? intNullable = null;
With a nullable type, you have another features like a bool property called HasValue which return if the int has a value and Value to get a value without nullable.
if (intNullable.HasValue)
{
int value = intNullable.Value;
}
In your case
public int? oh { get; set; }
The difference it the int is a value type while int? is a reference type. The ? is just a shortcut to Nullable<T> class. Value types cannot be null, reference type can. Read more about here http://msdn.microsoft.com/en-us/library/t63sy5hs.aspx
You can use ? in cases where a value type might be null:
public int? oh { get; set; }
Related
I have the following class:
public class RangeFilter<T> : IFilter<T> where T : IConvertible, IComparable {
public T Maximum { get; private set; }
public T Minimum { get; private set; }
public RangeFilter(T maximum) {
Minimum = null;
Maximum = maximum;
}
}
T can be an Int, a Double, ... When I pass only the maximum value I need the Minimum to be null but when I do that I get the following error:
Cannot convert null to type parameter 'T' because it could be a non-nullable value type.
Consider using 'default(T)' instead.
The reason I do not want to use default(T) is because I need to check later if Minimum is defined and default(T) is a valid value for Minimum.
As long as T is not nullable you can not set the value to null what you can do is something like this ...
public class RangeFilter<T> : IFilter<T>
where T : struct, IConvertible, IComparable
{
public T? Maximum { get; private set; }
public T? Minimum { get; private set; }
public RangeFilter(T maximum)
{
Minimum = null;
Maximum = maximum;
}
}
The problem is clearly described by a compiler error, but you can't use Nullable<T> because it's completely unusable here (what if T is a reference type, or Nullable<U>?) Fortunately, you can try an alternative, which is Functional.Maybe. It works both for value types and reference types.
The class you are creating is nullable by nature, the type you pass might not be. You can either restrict the type you pass as T (doc) or change your assignment to support both scenarios.
You could make flags instead of using a magic value to let you know if Minimum was set or not something is set or not
public HasMinimum {get; private set;}
private T _min;
public T Minimum
{
get
{
if(!HasMinimum)
throw new InvalidOperationException("Minimum not set");
return _min;
}
private set
{
HasMinimum = true;
_min = value;
}
}
Then in your constructor just don't set the minimum property
public RangeFilter(T maximum)
{
Maximum = maximum;
}
int and double are not nullable types, so they must have a value assigned to them and that's why you are getting that error. Although, you can use T? or Nullable<T> as a work around:
int? t = null; // t is nullable, so it works
You also can use nested Nullable<T>.GetValueOrDefault which can be also useful in your case, if you have a default value for your Min or Max.
Hope the question was clear.
I have a class structure in place and using it in an application already.
User would like to however change their total time keeping the calculated time intact. Calculated time is based on ComputeHours.
How do I introduce another property that will set its value based on ComputeHours for all existing data. Then if User changes this value, the new property should reflect this adjusted time.
public decimal TotalHours
{
get { return ComputeHours(); }
}
//Introducing new property
public decimal TotalAdjusted
{
???
}
It's important that I get the new property to set default to existsing property value, since the Grand Total time will then be based of this.
this is the typical pattern:
private decimal _totalAdjusted;
public ThisIsMyConstructor(){
_totalAdjusted = ComputeHours();
}
public decimal TotalAdjusted
{
set { _totalAdjusted = value; }
get { return _totalAdjusted ; }
}
since this isn't really doing anything special with _totalAdjusted, you can simplify it to this:
public ThisIsMyConstructor(){
TotalAdjusted = ComputeHours();
}
public decimal TotalAdjusted {get; set;}
If the result of ComputHours tends to change, and you want the default value to change with it, you can do this instead.
private decimal? _totalAdjusted == null;
public decimal TotalAdjusted
{
set { _totalAdjusted = value; }
get
{
return _totalAdjusted.HasValue ? _totalAdjusted.Value : ComputeHours();
}
}
Here's an explanation of some of the syntax there
the question mark on decimal? means that it's nullable.
HasValue is a property on a nullable object which is true when the nullable object is not null.
the Value property returns a non-nullable version of the nullable object.
The ? and : is the ternary operator. It essentially means if totalAdjusted.HasValue is true, then use _totalAdjusted.Value else use ComputeHours()
you can also just use the null coalescing operator to do the same thing.
return _totalAdjusted ?? ComputeHours();
the expression to the right of the ?? represents a default value in case _totalAdjusted is null
I have an object of type Employee which has a Guid property. I know if I want to set to null I must to define my type property as nullable Nullable<Guid> prop or Guid? prop.
But in my case I'm not able to change the type of the prop, so it will remains as Guid type and my colleague and I we don't want to use the Guid.Empty.
Is there a way to set my property as null or string.empty in order to restablish the field in the database as null.
I have a mechanism to transform from string.empty to null but I will change many things if the would change to accept a empty guid to null.
Any help please!
Is there a way to set my property as null or string.empty in order to restablish the field in the database as null.
No. Because it's non-nullable. If you want it to be nullable, you have to use Nullable<Guid> - if you didn't, there'd be no point in having Nullable<T> to start with. You've got a fundamental issue here - which you actually know, given your first paragraph. You've said, "I know if I want to achieve A, I must do B - but I want to achieve A without doing B." That's impossible by definition.
The closest you can get is to use one specific GUID to stand in for a null value - Guid.Empty (also available as default(Guid) where appropriate, e.g. for the default value of an optional parameter) being the obvious candidate, but one you've rejected for unspecified reasons.
Guid? myGuidVar = (Guid?)null;
It could be. Unnecessary casting not required.
Guid? myGuidVar = null;
Since "Guid" is not nullable, use "Guid.Empty" as default value.
Choose your poison - if you can't change the type of the property to be nullable then you're going to have to use a "magic" value to represent NULL. Guid.Empty seems as good as any unless you have some specific reason for not wanting to use it. A second choice would be Guid.Parse("ffffffff-ffff-ffff-ffff-ffffffffffff") but that's a lot uglier IMHO.
You can use typeof(Guid), "00000000-0000-0000-0000-000000000000" for DefaultValue of the property.
you can make guid variable to accept null first using ? operator then you use Guid.Empty or typecast it to null using (Guid?)null;
eg:
Guid? id = Guid.Empty;
or
Guid? id = (Guid?)null;
extrac Guid values from database functions:
#region GUID
public static Guid GGuid(SqlDataReader reader, string field)
{
try
{
return reader[field] == DBNull.Value ? Guid.Empty : (Guid)reader[field];
}
catch { return Guid.Empty; }
}
public static Guid GGuid(SqlDataReader reader, int ordinal = 0)
{
try
{
return reader[ordinal] == DBNull.Value ? Guid.Empty : (Guid)reader[ordinal];
}
catch { return Guid.Empty; }
}
public static Guid? NGuid(SqlDataReader reader, string field)
{
try
{
if (reader[field] == DBNull.Value) return (Guid?)null; else return (Guid)reader[field];
}
catch { return (Guid?)null; }
}
public static Guid? NGuid(SqlDataReader reader, int ordinal = 0)
{
try
{
if (reader[ordinal] == DBNull.Value) return (Guid?)null; else return (Guid)reader[ordinal];
}
catch { return (Guid?)null; }
}
#endregion
I think this is the correct way:
Guid filed = Guid.Empty;
int value=0;
if (value == 0)
{
value = null;
}
How can I set value to null above?
Any help will be appreciated.
In .Net, you cannot assign a null value to an int or any other struct. Instead, use a Nullable<int>, or int? for short:
int? value = 0;
if (value == 0)
{
value = null;
}
Further Reading
Nullable Types (C# Programming Guide)
Additionally, you cannot use "null" as a value in a conditional assignment. e.g...
bool testvalue = false;
int? myint = (testvalue == true) ? 1234 : null;
FAILS with: Type of conditional expression cannot be determined because there is no implicit conversion between 'int' and '<null>'.
So, you have to cast the null as well... This works:
int? myint = (testvalue == true) ? 1234 : (int?)null;
UPDATE (Oct 2021):
As of C# 9.0 you can use "Target-Typed" conditional expresssions, and the example will now work as c# 9 can pre-determine the result type by evaluating the expression at compile-time.
You cannot set an int to null. Use a nullable int (int?) instead:
int? value = null;
int does not allow null, use-
int? value = 0
or use
Nullable<int> value
public static int? Timesaday { get; set; } = null;
OR
public static Nullable<int> Timesaday { get; set; }
or
public static int? Timesaday = null;
or
public static int? Timesaday
or just
public static int? Timesaday { get; set; }
static void Main(string[] args)
{
Console.WriteLine(Timesaday == null);
//you also can check using
Console.WriteLine(Timesaday.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
Declare you integer variable as nullable
eg: int? variable=0; variable=null;
How to force a Null form elemnt to be Zero
I have the following model class:-
public partial class MemoryInfo
{
public long WORKSTATIONID { get; set; }
public Nullable<long> TOTALMEMORY { get; set; }
public Nullable<long> FREEMEMORY { get; set; }
public Nullable<long> VIRTUALMEMORY { get; set; }
public Nullable<long> FREEVIRTUALMEMORY { get; set; }
public virtual SystemInfo SystemInfo { get; set; }
}
And currently I am using the model class to build an API call as follow:-
query["ramSize"] = Request.Form["SystemInfo.MemoryInfo.TOTALMEMORY"];
query["virtualCapacity"] = Request.Form["SystemInfo.MemoryInfo.VIRTUALMEMORY"];
query["proSpeed"] = Request.Form["SPEED"];
string apiurl = System.Web.Configuration.WebConfigurationManager.AppSettings["ApiURL"];
var url = new UriBuilder(apiurl);
But currently if the user leave the ramSize field empty it will be sent as Null value and the API will ignore the values, while I need the following scenario; in case the ramSize field is empty to submit a values of zero .
Can anyone adive how I can do so ?
Thanks
Converting Null
You could use the ?? Operator. Which basically evaluates the preceding statement, and if it is null, uses the proceeding value.
query["ramSize"] = Request.Form["SystemInfo.MemoryInfo.TOTALMEMORY"] ?? 0;
MSDN
The ?? operator is called the null-coalescing operator and is used to
define a default value for nullable value types or reference types. It
returns the left-hand operand if the operand is not null; otherwise it
returns the right operand.
Just a note, I think that Request.Form[""] returns a string so you may have to enclose 0 in quotes.
Converting String.Empty
It seems you are in fact asking a different question, and you want to convert String.Empty or "" to 0. You can use the Tertiary Operator ? in this case:
string ramSize = Request.Form["SystemInfo.MemoryInfo.TOTALMEMORY"];
query["ramSize"] = String.IsNullOrEmpty(ramSize) ? "0" : ramSize;
MSDN
If condition is true, first expression is evaluated and becomes the
result; if false, the second expression is evaluated and becomes the
result. Only one of two expressions is ever evaluated.