C # how to handle return type exception of GUID?

I have a method with the following signature:

public Guid FindTermIDFromCustomProperty() 
{
     // Logic here to find an item and return the guid 
}

My problem is that if no elements were found in the function, then the GUID will not be returned - this goes without saying! But is there a way to return a small GUID?

Even better, is there a more general approach that I could use not only for GUIDs, but usually when I return a strong type? I really don't want to use an object as a return type, there must be a better way.

Thanks in advance.

+3
source share
6 answers

If you are using .NET 2.0 or later, you can return a type with a null value.

public Guid? FindTermIDFromCustomProperty() 
{
    // Logic here to find an item and return the guid 
    else
        return null;
}

var guid = FindTermIDFromCustomProperty();
if (guid.HasValue) // or "if (guid != null)"
    DoSomethingWith(guid.Value);
+5
source

, Guid.Empty, , .

, , bool out , bool, , . .

public bool FindTermIDFromCustomProperty(out Guid termId) 
+6

nullable Guid, , , null

public System.Nullable<Guid> FindTermIDFromCustomProperty() 
{
     // Logic here to find an item and return the guid

     if (!found)
     {
         return null;
     }
}

.

null.

+6

,

1: : int, datetime .. (0, DateTime.minValue, Guid.Empty) nullable, Guid?, int? .., null. nullable , , , . , . , , , psuedo . , , .

null.
null : , , . null, , .. , , , . , , , , foreach, GetEnumerator(), , null.

2: , , , , , .

, , , , - , , ( , ). , , , . , , .

+3

Guid.Empty. ( , - ItemNotFoundException). null:

public Nullable<Guid> FindTermIDFromCustomProperty() 
{
     // Logic here to find an item and return the guid 
}
+1

Try using types with a null value. For value types, you can make them nullable by adding ?, for example.

Int? x = null;

if (x! = null) {

}

+1
source

Source: https://habr.com/ru/post/1780922/


All Articles