In C# is it possible to pass a method a nullable Func?
Neither Func<A, bool>?
nor Func?<A, bool>
is working.
In C# is it possible to pass a method a nullable Func?
Neither Func<A, bool>?
nor Func?<A, bool>
is working.
That doesn't make sense.
All reference types, including Func<...>
, can already be null
.
Nullable types apply to value types (struct
s), which cannot ordinarily be null
.
A Func is a delegate which is a reference type. This means it is already nullable (you can pass null to a method).
All reference types including Func as delegate, can be null by default.
Func<T>
must be marked as Func<T>?
to be able to receive a null
as default parameter value.
/// <summary>
/// Returns an unique absolute path based on the input absolute path.
/// <para>It adds suffix to file name if the input folder already has the file with the same name.</para>
/// </summary>
/// <param name="absolutePath">An valid absolute path to some file.</param>
/// <param name="getIndex">A suffix function which is added to original file name. The default value: " (n)"</param>
/// <returns>An unique absolute path. The suffix is used when necessary.</returns>
public static string GenerateUniqueAbsolutePath(string absolutePath, Func<UInt64, string> getIndex = null)
{
if (getIndex == null)
{
getIndex = i => $" ({i})";
}
// ... other logic
}
/// <summary>
/// Returns an unique absolute path based on the input absolute path.
/// <para>It adds suffix to file name if the input folder already has the file with the same name.</para>
/// </summary>
/// <param name="absolutePath">An valid absolute path to some file.</param>
/// <param name="getIndex">A suffix function which is added to original file name. The default value: " (n)"</param>
/// <returns>An unique absolute path. The suffix is used when necessary.</returns>
public static string GenerateUniqueAbsolutePath(string absolutePath, Func<UInt64, string>? getIndex = null)
{
if (getIndex == null)
{
getIndex = i => $" ({i})";
}
// ... other logic
}
Func -> Encapsulates a method that returns a type specified by generic parameter
If return type is void, There is a different delegate (Action)
Action ->Encapsulates a method that does not return a value.
If you require Func to accept parameters that can accept null (nullable type), or require Func to return value which may be null(nullable type), there is no restriction.
For Example.
Func<int?, int?, bool> intcomparer =
(a,b)=>
{
if(a.HasValue &&b.HasValue &&a==b)
return true;
return false;
} ;
Func<int?, int?, bool?> nullintcomparer =
(a,b)=>
{
if(a.HasValue &&b.HasValue &&a==b)
return true;
if(!a.HasValue || !b.HasValue)
return null;
return false;
} ;
var result1 = intcomparer(null,null); //FALSE
var result2 = intcomparer(1,null); // FALSE
var result3 = intcomparer(2,2); //TRUE
var result4 = nullintcomparer(null,null); // null
var result5 = nullintcomparer(1,null); // null
var result6 = nullintcomparer(2,2); //TRUE
© 2022 - 2024 — McMap. All rights reserved.