Home > Blockchain >  Cannot convert from out System.Guid? to System.Guid
Cannot convert from out System.Guid? to System.Guid

Time:12-09

I'm trying to parse string into nullable guid. Depending on the TryParse result nullable guid should store value or be null.

private Guid? GetData()
{
    string carName = "Volvo";
    Guid? data = Guid.TryParse(carName, out data) ? (Guid?)data : null;
    
    return data;
}

I'm getting a compile-time error on out data with message

Cannot convert from out System.Guid? to System.Guid

CodePudding user response:

You need to use a different variable name:

Guid? data = Guid.TryParse(carName, out Guid _data) ? (Guid?)_data : null;

Currently, you use data for both

  • the end result (a Guid?) and
  • the out parameter of TryParse (which needs to be a Guid, not a Guid?).

CodePudding user response:

Lets make it simple and logical, and readable

if (Guid.TryParse(carName, out Guid g)
    return g;
return null;

if 3 lines bother you

return Guid.TryParse(carName, out Guid g) ? g : (Guid?)null;

CodePudding user response:

It's probably better to not do so much in one line. This will make it easier to read and understand.

private Guid? GetData()
    {
        string carName = "Volvo";
        // First try to parse the string into a guid
        var canParse = Guid.TryParse(carName, out var data);

        // Return either the converted value or null
        return canParse ? data : null;
    }
  • Related