Optional return in C#.Net - c#

Java 1.8 is receiving the Optional<T> class, that allows us to explicitly say when a method may return a null value and "force" its consumer to verify if it is not null (isPresent()) before using it.
I see C# has Nullable<T>, that does something similar, but with basic types. It seems to be used for DB queries, to distinguish when a value exists and is 0 from when it doesn't exist and is null.
But it seems that C#'s Nullable<T>doesn't work for objects, only for basic types, while Java's Optional<T> only works for objects and not for basic types.
Is there a Nullable/Optional class in C#, that forces us to test if object exists before extracting and using it?

Not in the language, no, but you can make your own:
public struct Optional<T>
{
public bool HasValue { get; private set; }
private T value;
public T Value
{
get
{
if (HasValue)
return value;
else
throw new InvalidOperationException();
}
}
public Optional(T value)
{
this.value = value;
HasValue = true;
}
public static explicit operator T(Optional<T> optional)
{
return optional.Value;
}
public static implicit operator Optional<T>(T value)
{
return new Optional<T>(value);
}
public override bool Equals(object obj)
{
if (obj is Optional<T>)
return this.Equals((Optional<T>)obj);
else
return false;
}
public bool Equals(Optional<T> other)
{
if (HasValue && other.HasValue)
return object.Equals(value, other.value);
else
return HasValue == other.HasValue;
}
}
Note that you won't be able to emulate certain behaviors of Nullable<T>, such as the ability to box a nullable value with no value to null, rather than a boxed nullable, as it has special compiler support for that (and a some other) behavior.

In my opinion, any Option implementation which exposes HasValue property is the defeat of the entire idea. The point of optional objects is that you can make unconditional calls to their contents without testing whether the content is there.
If you have to test whether the optional object contains a value, then you have done nothing new compared to common null tests.
Here is the article in which I am explaining optional objects in full detail: Custom Implementation of the Option/Maybe Type in C#
And here is the GitHub repository with code and examples: https://github.com/zoran-horvat/option
If you're reluctant to use a heavyweight Option solution, then you can easily build a lightweight one. You can make your own Option<T> type which implements IEnumerable<T> interface, so that you can leverage LINQ extension methods to turn calls optional. Here is the simplest possible implementation:
public class Option<T> : IEnumerable<T>
{
private readonly T[] data;
private Option(T[] data)
{
this.data = data;
}
public static Option<T> Create(T value)
{
return new Option<T>(new T[] { value });
}
public static Option<T> CreateEmpty()
{
return new Option<T>(new T[0]);
}
public IEnumerator<T> GetEnumerator()
{
return ((IEnumerable<T>)this.data).GetEnumerator();
}
System.Collections.IEnumerator
System.Collections.IEnumerable.GetEnumerator()
{
return this.data.GetEnumerator();
}
}
Using this Option<T> type is done via LINQ:
Option<Car> optional = Option<Car>.Create(myCar);
string color = optional
.Select(car => car.Color.Name)
.DefaultIfEmpty("<no car>")
.Single(); // you can call First(), too
You can find more about optional objects in these articles:
Custom Implementation of the Option/Maybe Type in C#
Understanding the Option (Maybe) Functional Type
How to Reduce Cyclomatic Complexity: Option Functional Type
And you may refer to my video courses for more details on how to simplify control flow using Option type and other means: Making Your C# Code More Functional and
Tactical Design Patterns in .NET: Control Flow
The first video course (Making Your C# Code More Functional) brings detailed introduction to railway-oriented programming, including the Either and Option types and how they can be used to manage optional objects and handle exceptional cases and errors.

There is better implementation of option type in C#. You can find this implemenation in Tactical design patterns in .NET by Zoran Horvat at pluralsight.com. It includes an explanation why and how to use it. The basic idea is to implement option class as implementation of IEnumerable<> interface.
public class Option<T> : IEnumerable<T>
{
private readonly T[] data;
private Option(T[] data)
{
this.data = data;
}
public static Option<T> Create(T element)
{
return new Option<T>(new[] { element });
}
public static Option<T> CreateEmpty()
{
return new Option<T>(new T[0]);
}
public IEnumerator<T> GetEnumerator()
{
return ((IEnumerable<T>) this.data).GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
}

In the project "C# functional language extensions" https://github.com/louthy/language-ext
exists the Option object of F# among others functional patters

Instead of writing your own class, you could use Microsoft.FSharp.Core.FSharpOption<T> from the FSharpCore.dll assembly. Unfortunately, the F# types are a bit clumsy when used in C#.
//Create
var none = FSharpOption<string>.None;
var some1 = FSharpOption<string>.Some("some1");
var some2 = new FSharpOption<string>("some2");
//Does it have value?
var isNone1 = FSharpOption<string>.get_IsNone(none);
var isNone2 = OptionModule.IsNone(none);
var isNone3 = FSharpOption<string>.GetTag(none) == FSharpOption<string>.Tags.None;
var isSome1 = FSharpOption<string>.get_IsSome(some1);
var isSome2 = OptionModule.IsSome(some1);
var isSome3 = FSharpOption<string>.GetTag(some2) == FSharpOption<string>.Tags.Some;
//Access value
var value1 = some1.Value; //NullReferenceException when None
var value2 = OptionModule.GetValue(some1); //ArgumentException when None

There's nothing built-in, but you can define your own. Note that an Option<T> implementation doesn't make sense without defining the map/bind operators.
public struct Option<T>
{
private bool hasValue;
private T value;
public Option(T value)
{
if (value == null) throw new ArgumentNullException("value");
this.hasValue = true;
this.value = value;
}
public Option<TOut> Select<TOut>(Func<T, TOut> selector)
{
return this.hasValue ? new Option<TOut>(selector(this.value)) : new Option<TOut>();
}
public Option<TOut> SelectMany<TOut>(Func<T, Option<TOut>> bind)
{
return this.hasValue ? bind(this.value) : new Option<TOut>();
}
public bool HasValue
{
get { return this.hasValue; }
}
public T GetOr(T #default)
{
return this.hasValue ? this.value : #default;
}
}

Perhaps this is closer to the F# Option type
public struct Option<T>
{
private T value;
private readonly bool hasValue;
public bool IsSome => hasValue;
public bool IsNone => !hasValue;
public T Value
{
get
{
if (!hasValue) throw new NullReferenceException();
return value;
}
}
public static Option<T> None => new Option<T>();
public static Option<T> Some(T value) => new Option<T>(value);
private Option(T value)
{
this.value = value;
hasValue = true;
}
public TResult Match<TResult>(Func<T, TResult> someFunc, Func<TResult> noneFunc) =>
hasValue ? someFunc(value) : noneFunc();
public override bool Equals(object obj)
{
if (obj is Option<T>)
{
var opt = (Option<T>)obj;
return hasValue ? opt.IsSome && opt.Value.Equals(value) : opt.IsNone;
}
return false;
}
public override int GetHashCode() =>
hasValue ? value.GetHashCode() : 0;
}

I decided to implement some kind of Optional<> Java class prototype some time ago using one of the last C# version.
Here it is:
public sealed class Optional<T>
{
private static readonly Optional<T> EMPTY = new Optional<T>();
private readonly T value;
private Optional() => value = default;
private Optional(T arg) => value = arg.RequireNonNull("Value should be presented");
public static Optional<T> Empty() => EMPTY;
public static Optional<T> Of(T arg) => new Optional<T>(arg);
public static Optional<T> OfNullable(T arg) => arg != null ? Of(arg) : Empty();
public static Optional<T> OfNullable(Func<T> outputArg) => outputArg != null ? Of(outputArg()) : Empty();
public bool HasValue => value != null;
public void ForValuePresented(Action<T> action) => action.RequireNonNull()(value);
public IOption<T> Where(Predicate<T> predicate) => HasValue
? predicate.RequireNonNull()(value) ? this : Empty() : this;
public IOption<TOut> Select<TOut>(Func<T, TOut> select) => HasValue
? Optional<TOut>.OfNullable(select.RequireNonNull()(value))
: Optional<TOut>.Empty();
public IOption<IOption<TOut>> SelectMany<TOut>(Func<T, IOption<TOut>> select) => HasValue
? Optional<IOption<TOut>>.OfNullable(select.RequireNonNull()(value))
: Optional<IOption<TOut>>.Empty();
public T Get() => value;
public T GetCustomized(Func<T, T> getCustomized) => getCustomized.RequireNonNull()(value);
public U GetCustomized<U>(Func<T, U> getCustomized) => getCustomized.RequireNonNull()(value);
public T OrElse(T other) => HasValue ? value : other;
public T OrElseGet(Func<T> getOther) => HasValue ? value : getOther();
public T OrElseThrow<E>(Func<E> exceptionSupplier) where E : Exception => HasValue ? value : throw exceptionSupplier();
public static explicit operator T(Optional<T> optional) => OfNullable((T) optional).Get();
public static implicit operator Optional<T>(T optional) => OfNullable(optional);
public override bool Equals(object obj)
{
if (obj is Optional<T>) return true;
if (!(obj is Optional<T>)) return false;
return Equals(value, (obj as Optional<T>).value);
}
public override int GetHashCode() => base.GetHashCode();
public override string ToString() => HasValue ? $"Optional has <{value}>" : $"Optional has no any value: <{value}>";
}

Use T? nullable reference instead of Option<T>
Since C#8 you should deprecate custom Option<T>-implementations. The null dilemma is now completely resolved.
T? is a complete substitution for Option<T>
C# has the following features for handling null:
Null coalescing operator
Null conditional operator
Non nullable & nullable reference types (since C#8)
Configurable compile errors/warnings
Keep in mind that
Option<Car> optional = Option<Car>.Create(myCar);
string color = optional
.Select(car => car.Color.Name)
.DefaultIfEmpty("<no car>")
.Single(); // you can call First(), too
is the same as
string color = myCar?.Color.Name ?? "<no car>";
and additionally the string color is also a reference that can't be null.

If you don't like baking your own solutions, I would use Language Ext. It is available on nuget. I have recently started using this library, and the safety from null references is amazing! I am not a expert with this library, but it can do what you are asking for, and much more.
Here is a taste of what can be done:
using System;
using LanguageExt;
using static LanguageExt.Prelude;
public class Demo
{
public static Option<int> ToEvenOrNone(int i) =>
i % 2 == 0
? i.Apply(Optional)
: None;
public static void PrintToDebug(Option<int> value) =>
value
.Some(Console.WriteLine)
.None(() => Console.WriteLine("Value is not Even!"));
public static void Test()
{
for (int i = 0; i < 10; i++)
{
PrintToDebug(ToEvenOrNone(i));
}
}
}
Here is the output:
0
Value is not Even!
2
Value is not Even!
4
Value is not Even!
6
Value is not Even!
8
Value is not Even!

Is there a Nullable/Optional class in C#, that forces us to test if
object exists before extracting and using it?
Nullables were created so that primitive types could be null. Their default value didn't have to be an actual value (Like int, without nullables it's default is 0, so is that a 0 means something 0 or a not set to anything 0?)
No there is nothing that you can do to force a programmer to check if an object is null. That's good though. Doing so would create an immense amount of overhead. If this was a language feature, how often would you force check? Would you require it when the variable is first assigned? What if the variable points to another object later? Would you force it to check before every method and property, and if it fails would you throw an exception? You get that now with a null reference exception. You would get very little benefit in forcing someone to do this beyond what you already have.

Learned a lot from Zoran Horvat's answer. Here is my code. optional can has a real value or an empty. On the consuming side, same code handle them all.
void Main()
{
var myCar = new Car{ Color = Color.Black, Make="Toyota"};
Option<Car> optional = Option<Car>.Create(myCar);
// optional is an Empty 50% of the time.
if(new Random().NextDouble() > 0.5)
optional = Option<Car>.CreateEmpty();
string color = optional
.Select(car => car.Color.Name)
.DefaultIfEmpty("<no car>")
.Single();
Console.Write(color);
}
class Car {
public Color Color { get; set; }
public string Make { get; set;}
}
public class Option<T> : IEnumerable<T>
{
private readonly T[] data;
private Option(T[] data)
{
this.data = data;
}
public static Option<T> Create(T value)
{
return new Option<T>(new T[] { value });
}
public static Option<T> CreateEmpty()
{
return new Option<T>(new T[0]);
}
public IEnumerator<T> GetEnumerator()
{
return ((IEnumerable<T>)this.data).GetEnumerator();
}
System.Collections.IEnumerator
System.Collections.IEnumerable.GetEnumerator()
{
return this.data.GetEnumerator();
}
}

https://github.com/mcintyre321/OneOf
I thought this oneOf class had a good re-creation of option type. It even includes a .switch/.match with pattern matching, and most importantly it works at runtime which is what you expect out of an Option pattern.

Related

Type.GetMethod() for polymorphic method (both generic and non-generic)

I am currently creating a custom way of deep-copying my objects. I use a static class for this functionality.
public static class CopyServer
{
public static int CopyDeep(int original)
{
return original;
}
//not shown: same for all other value types I use (long, float,...)
public static T CopyDeep<T>(T original) where T: ICopyAble
{
if (original == null)
return default;
if (original is ICopyAutofields)
return CopyAutofields(original);
return (T)original.CopyDeep();
}
private static T CopyAutofields<T>(T original)
{
Delegate del;
if (!_copyFunctions.TryGetValue(typeof(T), out del))
{
//not shown: Building expression for parameter etc.
foreach (var fieldInfo in typeof(T).GetFields())
{
//not shown: checking options set by custom attributes
MethodInfo methodInfo = typeof(CopyServer).GetMethod("CopyDeep", new[] { fieldInfo.FieldType });
//I can't remove the second param without getting an AmbiguousMatchException
if (methodInfo == null)
{
throw new Exception($"CopyDeep not defined for type {fieldInfo.FieldType}");
}
if (methodInfo.IsGenericMethod)
methodInfo = methodInfo.MakeGenericMethod(fieldInfo.FieldType);
Expression call = Expression.Call(methodInfo, readValue);
//not shown: Assign Expression
}
//not shown: return Expression and compiling
}
return ((Func<T, T>)del)(original);
}
}
I use T CopyAutofields<T> to build functions (by building and compiling Expression Trees) so I don't have to create copy-functions for each and every class I want to copy by hand. I control the copy-behaviour with Custom Attributes (I left this part in the code above since it is not relevant for my problem).
The code works fine as long as long as only fields with types for which a non-generic function exists are used. But it is not able to retrieve my generic function T CopyDeep<T>.
Example:
//This works:
public class Manager : ICopyAble,ICopyAutofields
{
public string FirstName;
public string LastName;
}
//This doesn't
//Meaning: typeof(CopyServer).GetMethod("copyDeep", new[] { fieldInfo.FieldType });
//in T copyAutofields<T> returns null for the Manager-field and my exception gets thrown
public class Employee : ICopyAble,ICopyAutofields
{
public string FirstName;
public string LastName;
public Manager Manager;
}
//This is what I was using before I started using the ICopyAutofields.
//This approach works, but its' too much too write since my classes usually
//have way more than three fields and I occasionally forget to update
//copyDeep()-function if I add new ones.
public class Employee : ICopyAble,ICopyAutofields
{
public string FirstName;
public string LastName;
public Manager Manager;
public IModable CopyDeep()
{
var result = new Employee();
result.FirstName = CopyServer.copyDeep(FirstName);
result.LastName= CopyServer.copyDeep(LastName);
result.Manager= CopyServer.copyDeep(Manager);
return result;
}
}
Long story short: I need a way of getting a matching function for a type T if both generic and non-generic functions with the right name exist.
In .NET 4.7.1 you need to use method GetMethods and filter the results:
class MyClass
{
public T M<T>(T t) { return default(T); }
public int M(int t) { return 0; }
}
var m = typeof(MyClass).GetMethod("M", new[] { typeof(string) }); // null
var m1 = typeof(MyClass).GetMethods()
.Where(mi => mi.Name == "M" && mi.GetGenericArguments().Any())
.First(); // returns generic method
In .NET Standard 2.1 (and .NET Core since 2.1) there is another way to resolve generic type arguments - Type.MakeGenericMethodParameter, like you can see it in this answer.
Also as workaround you can move your copyAutofields<T> method to generic class like CopyAutoFieldServer<T>:
public static class CopyAutoFieldServer<T>
{
public static T copyAutofields(T original) { ... }
}

Any significant reason to avoid `as IQueryable`?

I have a library of model-to-viewmodel mapping extension methods. Supporting them is a base class with a few common methods, including Transform, below:
internal abstract class TransformBase<TOriginal, TConverted>
{
protected abstract Expression<Func<TOriginal, TConverted>> Expression { get; }
public IQueryable<TConverted> Transform(IEnumerable<TOriginal> value)
{
var queryable = value as IQueryable<TOriginal> ?? value.AsQueryable();
return queryable.Select(Expression);
}
My question: is there any significant reason, besides a negligible performance hit, that I should avoid the as IQueryable cast above? For example, I could instead do the following:
internal abstract class TransformBase<TOriginal, TConverted>
{
protected abstract Expression<Func<TOriginal, TConverted>> Expression { get; }
public IQueryable<TConverted> Transform(IQueryable<TOriginal> value)
{
return value.Select(Expression);
}
public IQueryable<TConverted> Transform(IEnumerable<TOriginal> value)
{
return value.AsQueryable().Select(Expression);
}
... but I would prefer not to have to write the overloads in every one of my dependent classes. EDIT: To clarify, here is an example of what I'm seeking to avoid:
public static class TransformCompany
{
private static readonly TransformBase<Organization, CompanyHeader> header = new TransformPrecompiled<Organization, CompanyHeader>(
company => new CompanyHeader
{
Name = company.Name,
});
public static IQueryable<CompanyHeader> AsHeaders(this IQueryable<Organization> companies)
{
return header.Transform(companies);
}
// Note I have to include this capability in each of my dependent classes
// Worse is the possibility that someone may accidentally implement
// only IEnumerable for a future model transformation,
// causing a hidden data performance problem
public static IQueryable<CompanyHeader> AsHeaders(this IEnumerable<Organization> companies)
{
return header.Transform(companies);
}
I would say you do not need separate extensions for IEnumerable<T> and IQueryable<T> as IQueryable<T> inherits from IEnumerable<T>, and you also do not need to the cast.
Looking at referencesource, AsQueryable() actually does this check for you:
public static IQueryable<TElement> AsQueryable<TElement>(this IEnumerable<TElement> source)
{
if (source == null)
throw Error.ArgumentNull("source");
if (source is IQueryable<TElement>)
return (IQueryable<TElement>)source;
return new EnumerableQuery<TElement>(source);
}
Therefore the following should work for you with no performance hit:
internal abstract class TransformBase<TOriginal, TConverted>
{
protected abstract Expression<Func<TOriginal, TConverted>> Expression { get; }
public IQueryable<TConverted> Transform(IEnumerable<TOriginal> value)
{
return value.AsQueryable().Select(Expression);
}
}
public static class TransformCompany
{
public static IQueryable<CompanyHeader> AsHeaders(this IEnumerable<Organization> companies)
{
return header.Transform(companies);
}
}
Queryable.AsQueryable Method (IEnumerable)
If the type of source implements IQueryable,
AsQueryable(IEnumerable) returns it directly. Otherwise, it returns an
IQueryable that executes queries by calling the equivalent query
operator methods in Enumerable instead of those in Queryable.
Instead of casting you simplify your Transform method to
return value.AsQueryable().Select(Expression);

Generic conversion method throw InvalidCastException

I want to implement same simple generic conversion method but on runtime I am getting an error.
So the scenario is quite simple. I have same service that return me list of items of type External. I have my own WrapperExternal class that simply wrap this class and expose some additional functionality to it. I have some another set of classes that inherit from WrapExternal and add different functionalities.
I want to create generic method that accept list of External list items and return list of items of specified type.
My application code:
static void Main(string[] args)
{
var items = GetItemsFromServer();
var converted = ConvertItems<SubWrapperExternal>(items).ToList();
}
public static IEnumerable<T> ConvertItems<T>(IEnumerable<External> externalItems) where T : WrapperExternal
{
return externalItems
.Where( item => true)
.Select(item => (T)item);
}
When you try to run this code you will get exception in line (T)item:
An unhandled exception of type 'System.InvalidCastException' occurred in ConsoleApplication1.exe
Additional information:
Unable to cast object of type 'ConsoleApplication1.WrapperExternal' to type 'ConsoleApplication1.SubWrapperExternal'.
Do you know how can I make it to works?
Test application code:
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var items = GetItemsFromServer();
var converted = ConvertItems<SubWrapperExternal>(items).ToList();
}
private static List<External> GetItemsFromServer()
{
return new List<External>
{
new External{Name = "A"},
new External{Name = "B"},
new External{Name = "C"},
};
}
public static IEnumerable<T> ConvertItems<T>(IEnumerable<External> externalItems) where T : WrapperExternal
{
return externalItems
.Where( item => true)
.Select(item => (T)item);
}
}
class External
{
public string Name { get; set; }
}
class WrapperExternal
{
public External External { get; private set; }
public WrapperExternal(External external)
{
External = external;
}
public static explicit operator WrapperExternal(External item)
{
return item != null ? new WrapperExternal(item) : null;
}
public static implicit operator External(WrapperExternal item)
{
return item != null ? item.External : null;
}
}
class SubWrapperExternal : WrapperExternal
{
public SubWrapperExternal(External external)
: base(external)
{
}
public static explicit operator SubWrapperExternal(External item)
{
return item != null ? new SubWrapperExternal(item) : null;
}
public static implicit operator External(SubWrapperExternal item)
{
return item != null ? item.External : null;
}
}
}
Conversion operators are a faff to use with generics - generics don't support any static operator overloads. Because of this, the (T) cast is performing a non-converting type check (generics need to use the same IL for every possible T, remember) - a basic castclass.
The only "simple" way of doing what you want is to cheat with dynamic:
return externalItems.Select(item => (T)(dynamic)item);
Since the C#-specific dynamic provider knows all the common rules of C#, it knows about conversion operators, and will apply them on-demand. There is a slight performance cost associated with this, but it isn't as bad as it looks at first glance, as the strategy is cached (as IL) once per type - it doesn't perform per-item reflection.

How to make a custom Dictionary with different return code? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to get null instead of the KeyNotFoundException accessing Dictionary value by key?
I currently have lots of Dictionary<string, T> uses in my project, and most of them look like so:
if (myDic.ContainsKey("some key"))
localVar = myDic["some key"];
It's not very effecient too, as it does two calls to the dictionary, which can be resource consuming. TryGetValue() is a cool thing, but it just doesn't do it in one line.
I just want to get null if there is no such key from var v = myDic[key]. How do I do that?
You may use an extension method with TryGetValue:
public static U GetValueByKeyOrNull<T, U>(this Dictionary<T, U> dict, T key)
where U : class
{
U value;
dict.TryGetValue(key, out value);
return value;
}
thanks to which you'll be able to write
somedict.GetValueByKeyOrNull("key1")
In the end trying to do this very thing I came up with a variant using a deriving from dictionary class with explicit interface implementation: How to get null instead of the KeyNotFoundException accessing Dictionary value by key?
That is
public interface INullValueDictionary<T, U>
where U : class
{
U this[T key] { get; }
}
public class NullValueDictionary<T, U> : Dictionary<T, U>, INullValueDictionary<T, U>
where U : class
{
U INullValueDictionary<T, U>.this[T key]
{
get
{
U val;
dict.TryGet(key, out val);
return val;
}
}
}
and use it instead of the original dictionary everywhere:
//create some dictionary
NullValueDictionary<int, string> dict = new NullValueDictionary<int, string>
{
{1,"one"}
};
//have a reference to the interface
INullValueDictionary<int, string> idict = dict;
string val = idict[2]; // null
val = idict[1]; // "one"
I don't like to deal with null so my implementation will look like this:
interface Maybe<T> {
bool HasValue {get;}
T Value {get;}
}
class Nothing<T> : Maybe<T> {
public bool HasValue { get { return false; } }
public T Value { get { throw new Exception(); } }
public static const Nothing<T> Instance = new Nothing<T>();
}
class Just<T> : Maybe<T> {
private T _value;
public bool HasValue { get { return true; } }
public T Value { get { return _value; } }
public Just(T val) {
_value = val;
}
}
Maybe is a object that can contain value or not. Note that Nothing class contains static field Instance. We can use this value instead of creating new value each time we need to return Nothing from function.
Now, we need to create our own dictionary class:
class MyDictionary<TKey, TValue>
{
private Dictionary<TKey, TValue> _dict;
...
public Maybe<TValue> this[TKey key] {
TValue val;
if (_dict.TryGetValue(key, out val)) {
return new Just<TValue>(val);
return Nothing<TValue>.Instance;
}
}
Advantage of this approach is not clear, because C# doesn't have pattern matching. But it can be emulated with dynamic:
void ProcessResult(Just<string> val) {
Console.WriteLine(val);
}
void ProcessResult(Nothing<string> n) {
Console.WriteLine("Key not found");
}
var dict = new MyDictionary<string, string>();
...
dynamic x = dict["key"];
ProcessResult(x);
I think that this is very clear way to express the fact that dictionary can't always return meaningful result. Also it is obvious for reader that function overload ProcessResult(Just<T>) will be called only for values that present in dictionary and other overload will be called in case when key is not found.
Pros:
Type serves as a specification.
Dictionary can contain both value and reference types.
Cons:
More keystrokes.
Little more complexity to deal with.
I decided to do it like this:
class MyDictionary<TKey, TValue> : Dictionary<TKey, TValue>
{
public new TValue this[TKey key]
{
get
{
TValue value;
return TryGetValue(key, out value) ? value : default(TValue);
}
set { base[key] = value; }
}
}
It lets me use it like any other dictionary, through square brackets. Since I'm not going to use this with value types as TValue, I think it's good enough a solution.

List.Sort in C#: comparer being called with null object

I am getting strange behaviour using the built-in C# List.Sort function with a custom comparer.
For some reason it sometimes calls the comparer class's Compare method with a null object as one of the parameters. But if I check the list with the debugger there are no null objects in the collection.
My comparer class looks like this:
public class DelegateToComparer<T> : IComparer<T>
{
private readonly Func<T,T,int> _comparer;
public int Compare(T x, T y)
{
return _comparer(x, y);
}
public DelegateToComparer(Func<T, T, int> comparer)
{
_comparer = comparer;
}
}
This allows a delegate to be passed to the List.Sort method, like this:
mylist.Sort(new DelegateToComparer<MyClass>(
(x, y) => {
return x.SomeProp.CompareTo(y.SomeProp);
});
So the above delegate will throw a null reference exception for the x parameter, even though no elements of mylist are null.
UPDATE: Yes I am absolutely sure that it is parameter x throwing the null reference exception!
UPDATE: Instead of using the framework's List.Sort method, I tried a custom sort method (i.e. new BubbleSort().Sort(mylist)) and the problem went away. As I suspected, the List.Sort method passes null to the comparer for some reason.
This problem will occur when the comparison function is not consistent, such that x < y does not always imply y < x. In your example, you should check how two instances of the type of SomeProp are being compared.
Here's an example that reproduces the problem. Here, it's caused by the pathological compare function "compareStrings". It's dependent on the initial state of the list: if you change the initial order to "C","B","A", then there is no exception.
I wouldn't call this a bug in the Sort function - it's simply a requirement that the comparison function is consistent.
using System.Collections.Generic;
class Program
{
static void Main()
{
var letters = new List<string>{"B","C","A"};
letters.Sort(CompareStrings);
}
private static int CompareStrings(string l, string r)
{
if (l == "B")
return -1;
return l.CompareTo(r);
}
}
Are you sure the problem isn't that SomeProp is null?
In particular, with strings or Nullable<T> values.
With strings, it would be better to use:
list.Sort((x, y) => string.Compare(x.SomeProp, y.SomeProp));
(edit)
For a null-safe wrapper, you can use Comparer<T>.Default - for example, to sort a list by a property:
using System;
using System.Collections.Generic;
public static class ListExt {
public static void Sort<TSource, TValue>(
this List<TSource> list,
Func<TSource, TValue> selector) {
if (list == null) throw new ArgumentNullException("list");
if (selector == null) throw new ArgumentNullException("selector");
var comparer = Comparer<TValue>.Default;
list.Sort((x,y) => comparer.Compare(selector(x), selector(y)));
}
}
class SomeType {
public override string ToString() { return SomeProp; }
public string SomeProp { get; set; }
static void Main() {
var list = new List<SomeType> {
new SomeType { SomeProp = "def"},
new SomeType { SomeProp = null},
new SomeType { SomeProp = "abc"},
new SomeType { SomeProp = "ghi"},
};
list.Sort(x => x.SomeProp);
list.ForEach(Console.WriteLine);
}
}
I too have come across this problem (null reference being passed to my custom IComparer implementation) and finally found out that the problem was due to using inconsistent comparison function.
This was my initial IComparer implementation:
public class NumericStringComparer : IComparer<String>
{
public int Compare(string x, string y)
{
float xNumber, yNumber;
if (!float.TryParse(x, out xNumber))
{
return -1;
}
if (!float.TryParse(y, out yNumber))
{
return -1;
}
if (xNumber == yNumber)
{
return 0;
}
else
{
return (xNumber > yNumber) ? 1 : -1;
}
}
}
The mistake in this code was that Compare would return -1 whenever one of the values could not be parsed properly (in my case it was due to wrongly formatted string representations of numeric values so TryParse always failed).
Notice that in case both x and y were formatted incorrectly (and thus TryParse failed on both of them), calling Compare(x, y) and Compare(y, x) would yield the same result: -1. This I think was the main problem. When debugging, Compare() would be passed null string pointer as one of its arguments at some point even though the collection being sorted did not cotain a null string.
As soon as I had fixed the TryParse issue and ensured consistency of my implementation the problem went away and Compare wasn't being passed null pointers anymore.
Marc's answer is useful. I agree with him that the NullReference is due to calling CompareTo on a null property. Without needing an extension class, you can do:
mylist.Sort((x, y) =>
(Comparer<SomePropType>.Default.Compare(x.SomeProp, y.SomeProp)));
where SomePropType is the type of SomeProp
For debugging purposes, you want your method to be null-safe. (or at least, catch the null-ref. exception, and handle it in some hard-coded way). Then, use the debugger to watch what other values get compared, in what order, and which calls succeed or fail.
Then you will find your answer, and you can then remove the null-safety.
Can you run this code ...
mylst.Sort((i, j) =>
{
Debug.Assert(i.SomeProp != null && j.SomeProp != null);
return i.SomeProp.CompareTo(j.SomeProp);
}
);
I stumbled across this issue myself, and found that it was related to a NaN property in my input. Here's a minimal test case that should produce the exception:
public class C {
double v;
public static void Main() {
var test =
new List<C> { new C { v = 0d },
new C { v = Double.NaN },
new C { v = 1d } };
test.Sort((d1, d2) => (int)(d1.v - d2.v));
}
}

Categories