cannot convert from 'System.Guid?' to 'System.Guid'
Asked Answered
U

6

27

Does anyone know how to deal with this error?

cannot convert from 'System.Guid?' to 'System.Guid'
Underside answered 1/1, 2010 at 11:51 Comment(0)
K
59

See MSDN.

In that case, merely use myNullableVariable.Value (if you're sure it has a value), or (myNullableVariable.HasValue)?myNullableVariable.Value:somedefaulthere if you're not.

One can also use GetValueOrDefault() if one doesn't care if the default is a specific value when the nullable really is null.

The last way to do it is this: myNullableVariable.Value ?? defaultvalue.

See, technically a MyType? variable is a Nullable<MyType> under the covers. There are no implicit or explicit casts between the two, so what you need to do is extract the value out of the Nullable manually. The third way i listed is the most succinct (and best?) way to do it, to that would probably be best in most cases.

Kronstadt answered 1/1, 2010 at 11:54 Comment(0)
P
6

Use Guid?.Value property to convert 'System.Guid?' to 'System.Guid'. as following example

Obj GetValue(Guid yourID)
{
return FetchObject(yourID)
}
Void main()
{
Guid? passvalue;
Obj test = GetValue(passvalue.Value);
}
Philemon answered 20/4, 2015 at 12:27 Comment(0)
W
2

Simply use Nullable<T>.HasValue in if statement to check the value for null, then after it you can use Nullable<T>.Value to gets the value of an underlying type.

int? a = null;
if(a.HasValue){
  Console.WriteLine($"a has value {a.Value}");
} else {
  Console.WriteLine("No value found in a");
}
Waring answered 4/6, 2021 at 6:1 Comment(0)
R
1

First intialize the guid variable.

Guid yourGuid= Guid.NewGuid()

then set value in that which you want for eg:

 Guid defaultId = Guid.NewGuid();
 if (customerRow.GuardianState.Length > 2) {
 Guid StateId = record.StateId ?? defaultId;}
Riverhead answered 30/1, 2014 at 12:9 Comment(0)
H
0

cannot convert from 'System.Guid?' to 'System.Guid'

you are trying to save type System.Guid? to a type system.Guid inside your model you can edit System.Guid? to System.Guid by removing the question mark.

or RCIX answer above

Humiliation answered 25/9, 2017 at 22:16 Comment(1)
The answer was accepted 7 years ago, what new value does this bring?Antecedent
H
0

If you are sure value is not null then you can cast value as a (Guid)

var identifier = (Guid)myOtherIdentifier!;

Or you can use

var identifier = myOtherIdentifier.HasValue ? myOtherIdentifier : Guid.Empty;

Or another usage is

var identifier = myOtherIdentifier ?? Guid.Empty;
Hyposthenia answered 4/1 at 6:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.