Right now the form can send me three values for my boolean fields.
false
true
""
procedure.needsAuditing = Convert.ToBoolean(collection["needsAuditing"]);
How to I structure this variable so that if it is "" it will not try to convert it to a Boolean but instead pass null?
If you want a third state for a bool which indicates not determined(null) you can use a Nullable<bool>.
So change the property to:
public bool? needsAuditing{ get; set; }
and assign it in this way:
object needsAuditing = collection["needsAuditing"];
if(needsAuditing == null)
procedure.needsAuditing = (bool?) null;
else
procedure.needsAuditing = Convert.ToBoolean(needsAuditing);
Side-note: you should consider to use pascal case propertynames. See Property Naming Guidelines.
Try like this...first make procedure.needsAuditing Nullable see thisLink For More Details For Nullable Type.
then do it like this...
bool? c;
procedure.needsAuditing =collection["needsAuditing"]==""? c=null: Convert.ToBoolean(collection["needsAuditing"]);
if(string.IsNullOrEmpty(collection["needsAuditing"].ToString())
procedure.needsAuditing = null;
else
procedure.needsAuditing = Convert.ToBoolean(collection["needsAuditing"]);
Assuming needsAuditing is a bool?
Edit: I did an if else instead of a ? because the compiler would complain that there's no conversion between null and bool (which would be the return type of Convert.ToBoolean)
Create a ModelBinder which will convert your string input to nullable bool type.
Your method after that will look like this:
void Method(bool? value)
{
}
Assign the procedure.needsAuditing property to the result of the following method:
bool? ParseInput(string input)
{
int integerInput;
if (int.TryParse(input, out integerInput))
return integerInput == 1;
return null;
}
Related
I have a class which contains a nullable strings, I want to make a check to see whether they stay null or somebody has set them.
simliar to strings, the class contains integers which are nullable, where i can perform this check by doing an equality comparison
with the .HasValue() method - it seems like strings dont have this?
So how do check whether it goes from null to notNull?
public class Test
{
public string? a
public string? b
public int? c
}
var oldQ = new Test(c=123)
var newQ = new Test(c=546)
bool isStilValid = newQ.c.HasValue() == oldQ.c.HasValue() //(this is not possible?)&& newQ.b.HasValue() == oldQ.b.HasValue()
why is this not possible?
HasValue property belongs to Nullable<T> struct, where T is also restricted to be a value type only. So, HasValue is exist only for value types.
Nullable reference types are implemented using type annotations, you can't use the same approach with nullable value types. To check a reference type for nullability you could use comparison with null or IsNullOrEmpty method (for strings only). So, you can rewrite your code a little bit
var oldQ = new Test() { c = 123 };
var newQ = new Test() { c = 456 };
bool isStilValid = string.IsNullOrEmpty(newQ.b) == string.IsNullOrEmpty(oldQ.b);
Or just use a regular comparison with null
bool isStilValid = (newQ.b != null) == (oldQ.b != null);
Only struct in C# have HasValue method, but you can simple create your own string extension as below and that will solve your problem.
public static class StringExtension {
public static bool HasValue(this string value)
{
return !string.IsNullOrEmpty(value);
}
}
I hope this is helpful for someone.
The equivalent comparing to null would be:
bool isStillValid = (newQ.c != null) == (oldQ.c != null) && (newQ.b != null) == (oldQ.b != null);
That's the equivalent to your original code, but I'm not sure the original code is correct...
isStillValid will be true if ALL the items being tested for null are actually null. Is that really what you intended?
That is, if newQ.c is null and oldQ.c is null and newQ.b is null and oldQ.b is null then isStillValid will be true.
The Nullable<T> type requires a type T that is a non-nullable value type for example int or double.
string typed variables are already null, so the nullable string typed variable doesn't make sense.
You need to use string.IsNullOrEmpty or simply 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;
Basically I want the following generic function:
public string StringOrNull<T> (T value)
{
if (value != null)
{
return value.ToString();
}
return null;
}
I know I could use a constraint such as where T: class, but T can be a primitive type, Nullable<>, or a class. Is there a generic way to do this?
Edit
Turns out I jumped the gun. This actually works just fine as this sample shows:
class Program
{
static void Main(string[] args)
{
int i = 7;
Nullable<int> n_i = 7;
Nullable<int> n_i_asNull = null;
String foo = "foo";
String bar = null;
Console.WriteLine(StringOrNull(i));
Console.WriteLine(StringOrNull(n_i));
Console.WriteLine(StringOrNull(n_i_asNull));
Console.WriteLine(StringOrNull(foo));
Console.WriteLine(StringOrNull(bar));
}
static private string StringOrNull<T>(T value)
{
if (value != null)
{
return value.ToString();
}
return null;
}
}
default Keyword in Generic Code
In generic classes and methods, one issue that arises is how to assign a default value to a parameterized type T when you do not know the following in advance:
Whether T will be a reference type or a value type.
If T is a value type, whether it will be a numeric value or a struct.
Here's a fun one:
public static class ExtensionFunctions{
public static string ToStringOrNull( this object target ) {
return target != null ? target.ToString() : null;
}
}
The cool part? This will work:
( (string) null ).ToStringOrNull();
So will this:
5.ToStringOrNull();
Extension functions are pretty awesome... they even work on null objects!
If you pass a primitive type, it will automatically be boxed, so you don't need to worry about the null comparison. Since boxing occurs automatically, you can even explicitly compare an int to null without an error, but the result will always be false (and you'll probably get a compiler warning telling you so).
You can use default keyword to return the default of T:
public string StringOrNull<T> (T value)
{
.....
return default(T).ToString();
}
Why generic?
public string StringOrNull (object value)
{
if (value != null){
return value.ToString();
}
return null;
}
Can anyone help?
I have some code that is shared between 2 projects. The code points to a model which basically is a collection of properties that comes from a db.
Problem being is that some properties use nullable types in 1 model and the other it doesn't
Really the dbs should use the same but they don't ..
so for example there is a property called IsAvailble which uses "bool" in one model and the other it uses bool? (nullable type)
so in my code i do the following
objContract.IsAvailble.Value ? "Yes" : "No" //notice the property .VALUE as its a bool? (nullable type)
but this line will fail on model that uses a standard "bool" (not nullable) as there is no property .VALUE on types that are NOT nullable
Is there some kind of helper class that i check if the property is a nullable type and i can return .Value .. otherwise i just return the property.
Anybody have a solution for this?
EDIT
This is what i have now..... i am checking HasValue in the nullable type version
public static class NullableExtensions
{
public static T GetValue(this T obj) where T : struct
{
return obj;
}
public static T GetValue(this Nullable obj) where T : struct
{
return obj.Value;
}
public static T GetValue<T>(this T obj, T defaultValue) where T : struct
{
return obj;
}
public static T GetValue<T>(this Nullable<T> obj, T defaultValue) where T : struct
{
if (obj.HasValue)
return obj.Value;
else
return defaultValue;
}
}
This is a little weird, but maybe you can use an extension method here:
static class NullableExtensions
{
public static T GetValue<T>(this T obj) where T : struct
{
return obj;
}
public static T GetValue<T>(this Nullable<T> obj) where T : struct
{
return obj.Value;
}
}
They will work with nullable or regular types:
int? i = 4;
int j = 5;
int a = i.GetValue();
int b = j.GetValue();
I wouldn't cast. use the ?? operator
http://msdn.microsoft.com/en-us/library/ms173224(VS.80).aspx
bool? isAvailble = null;
//string displayIsAvailble = (bool)(isAvailble) ? "Yes" : "No"; //exception Nullable object must have a value.
string displayIsAvailble = (isAvailble ?? false) ? "Yes" : "No"; //outputs "no"
Console.WriteLine(displayIsAvailble);
(bool)(objContract.IsAvailble) ? "Yes" : "No"
Best I can suggest is to always cast to the nullable, then use the null coalescing operator to say what you want the value to be when it's null. e.g.:
string s3 = (bool?)b ?? false ? "yes" : "no";
The above will work whether b is defined as bool or bool?
Convert.ToBoolean(objContract.IsAvailble) ? "yes" : "no"
OR
Is this what you are looking for?
bool? n = false;
bool nn = true;
Console.WriteLine(n ?? nn);
One more alternative:
objContract.IsAvailble == true ? "Yes" : "No"
On the nullable, only true is true, null or false is false. On the regular bool, true/false is normal.
You could use:
bool? b1 = objContract.IsAvailable;
string s1 = b1.Value ? "Yes" : "No";`
This should work whether objectContract.IsAvailable is a bool or bool? or any other nullable type.
For dates for example:
DateTime? t1 = objContract.EitherNullableOrNotNullableDate;
string s1 = t1.Value.ToString();
I have a DateTime? variable, sometimes the value is null, how can I return an empty string "" when the value is null or the DateTime value when not null?
Though many of these answers are correct, all of them are needlessly complex. The result of calling ToString on a nullable DateTime is already an empty string if the value is logically null. Just call ToString on your value; it will do exactly what you want.
string date = myVariable.HasValue ? myVariable.Value.ToString() : string.Empty;
Actually, this is the default behaviour for Nullable types, that without a value they return nothing:
public class Test {
public static void Main() {
System.DateTime? dt = null;
System.Console.WriteLine("<{0}>", dt.ToString());
dt = System.DateTime.Now;
System.Console.WriteLine("<{0}>", dt.ToString());
}
}
this yields
<>
<2009-09-18 19:16:09>
Calling .ToString() on a Nullable<T> that is null will return an empty string.
You could write an extension method
public static string ToStringSafe(this DateTime? t) {
return t.HasValue ? t.Value.ToString() : String.Empty;
}
...
var str = myVariable.ToStringSafe();
All you need to do is to just simply call .ToString(). It handles Nullable<T> object for null value.
Here is the source of .NET Framework for Nullable<T>.ToString():
public override string ToString() {
return hasValue ? value.ToString() : "";
}
DateTime? d;
// stuff manipulating d;
return d != null ? d.Value.ToString() : String.Empty;
DateTime d?;
string s = d.HasValue ? d.ToString() : string.Empty;
DateTime? MyNullableDT;
....
if (MyNullableDT.HasValue)
{
return MyNullableDT.Value.ToString();
}
return "";
if (aDate.HasValue)
return aDate;
else
return string.Empty;
According to Microsoft's documentation:
The text representation of the value of the current Nullable object if the HasValue property is true, or an empty string ("") if the HasValue property is false.