How to set null to a GUID property - c#

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;

Related

why dont nullable strings have a hasValue() method?

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

integer fields set as null

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

How to structure this variable

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

C# Return value of a property which is nullable [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Type result with Ternary operator in C#
I ran into this scenario, and there doesn't seem to be a natural way to return a nullable int. The code below gives compilation error because the ternary operator doesn't like null.
public int? userId
{
get
{
int rv;
return int.TryParse(userIdString, out rv) ? rv : null;
}
}
So you (or just me) really have to go all the way and spell it all out:
public int? userId
{
get
{
int id;
if(int.TryParse(userIdString, out id)){
return id;
}
return null;
}
}
EDIT: Is there a more natural way of instantiating a nullable, to make the ternary operator work?
public int? userId
{
get
{
int rv;
return int.TryParse(userIdString, out rv) ? (int?)rv : null;
}
}
public int? userId
{
get
{
int rv;
return int.TryParse(userIdString, out rv) ? (int?)rv : null;
}
}
EDIT: I hadn't read the question carefully enough; the problem isn't that the conditional operator doesn't like nulls - it's that it needs to know what the overall type of the expression should be... and that type has to be the type of either the left-hand side, or the right-hand side. null itself is a type-less expression which can be converted to many types; int is a perfectly valid type, but it's one of the types which null can't be converted to. You can either make the right-hand side explicitly of type int? and get the implicit conversion of int to int? from the left-hand side, or you can perform a cast on the left-hand side, and get the implicit conversion of null to int?.
My answer is like James's, but casting the null instead:
public int? userId
{
get
{
int rv;
return int.TryParse(userIdString, out rv) ? rv : (int?) null;
}
}
This is to emphasize that it's not a null reference; it's a null value of type int?. At that point, the conversion of the int rv is obvious.
There are two other alternatives along the same lines to consider though:
return int.TryParse(userIdString, out rv) ? rv : new int?();
return int.TryParse(userIdString, out rv) ? rv : default(int?);
Personally I think the "casted null" is the nicest form, but you can make up your own mind.
Another alternative would be to have a generic static method:
public static class Null
{
public static T? For<T>() where T : struct
{
return default(T?);
}
}
and write:
return int.TryParse(userIdString, out rv) ? rv : Null.For<int>();
I don't think I really like that, but I offer it for your inspection :)
You're returning a (non-nullable) int or null in the same expression. You'll need to explicitly return a int? in your ternary expression for that to work.

Nullable GUID

In my database, in one of the table I have a GUID column with allow nulls. I have a method with a Guid? parameter that inserts a new data row in the table. However when I say myNewRow.myGuidColumn = myGuid I get the following error: "Cannot implicitly convert type 'System.Guid?' to 'System.Guid'."
The ADO.NET API has some problems when it comes to handling nullable value types (i.e. it simply doesn't work correctly). We've had no end of issues with it, and so have arrived at the conclusion that it's best to manually set the value to null, e.g.
myNewRow.myGuidColumn = myGuid == null ? (object)DBNull.Value : myGuid.Value
It's painful extra work that ADO.NET should handle, but it doesn't seem to do so reliably (even in 3.5 SP1). This at least works correctly.
We've also seen issues with passing nullable value types to SqlParameters where the generated SQL includes the keyword DEFAULT instead of NULL for the value so I'd recommend the same approach when building parameters.
OK; how is myGuidColumn defined, and how is myGuid defined?
If myGuid is Guid? and myGuidColumn is Guid, then the error is correct: you will need to use myGuid.Value, or (Guid)myGuid to get the value (which will throw if it is null), or perhaps myGuid.GetValueOrDefault() to return the zero guid if null.
If myGuid is Guid and myGuidColumn is Guid?, then it should work.
If myGuidColumn is object, you probably need DBNull.Value instead of the regular null.
Of course, if the column is truly nullable, you might simply want to ensure that it is Guid? in the C# code ;-p
same as Greg Beech's answer
myNewRow.myGuidColumn = (object)myGuid ?? DBNull.Value
You have to cast null to a nullable Guid, this how it worked for me :
myRecord.myGuidCol = (myGuid == null) ? (Guid?)null : myGuid.Value
Try System.Guid.Empty where you want it to be null
If you want to avoid working with nullable GUIDs in your c# code (personally, I often find it cumbersome to work with nullable types) you could somewhere early assign Guid.Empty to the .NET data which is null in the db. That way, you don't have to bother with all the .HasValue stuff and just check if myGuid != Guid.Empty instead.
or:
internal static T CastTo<T>(object value)
{
return value != DBNull.Value ? (T)value : default(T);
}
You can use a helper method:
public static class Ado {
public static void SetParameterValue<T>( IDataParameter parameter, T? value ) where T : struct {
if ( null == value ) { parameter.Value = DBNull.Value; }
else { parameter.Value = value.Value; }
}
public static void SetParameterValue( IDataParameter parameter, string value ) {
if ( null == value ) { parameter.Value = DBNull.Value; }
else { parameter.Value = value; }
}
}
If you are into extension methods...
/// <summary>
/// Returns nullable Guid (Guid?) value if not null or Guid.Empty, otherwise returns DBNull.Value
/// </summary>
public static object GetValueOrDBNull(this Guid? aGuid)
{
return (!aGuid.IsNullOrEmpty()) ? (object)aGuid : DBNull.Value;
}
/// <summary>
/// Determines if a nullable Guid (Guid?) is null or Guid.Empty
/// </summary>
public static bool IsNullOrEmpty(this Guid? aGuid)
{
return (!aGuid.HasValue || aGuid.Value == Guid.Empty);
}
Then you could say:
myNewRow.myGuidColumn = myGuid.GetValueOrDBNull();
NOTE: This will insert null when myGuid == Guid.Empty, you could easily tweak the method if you want to allow empty Guids in your column.
Guid? _field = null;
if (myValue!="")//test if myValue has value
{
_field = Guid.Parse(myValue)
}

Categories

Resources