Default Function used with Generic Functions in C#
I was writing a generic function that would non-uniformly randomly select an item from a weighted list. I wanted to re-use the same code in several parts of the system that used different object types. Accordingly, I decided to define the function using generic types.Here's the prototype of my function:
private static T PickRandomElement<T> (SerializableDictionary<T, double> elements)

If the list did not meet certain conditions -- i.e. the sum of the probabilities was not 1. -- I wanted to return null denoting that there was a problem. However, because this function returns a generic type we cannot simply return null. Luckily the C# Designers have spent a considerable amount of time flushing out the details.To return null in a function that returns a generic type you can use the default keyword. Here's a simple example for the method prototype declared above:
return default(T);

Comments...

Like to leave a comment ?


Title

Comment

Name