How can I test that LINQ Range operator is deferred? - c#

I have implemented some sort of LINQ Range operator and do want to have a test which will verify that the Range operator is actually deferred.
My Range operator methods:
/// <summary>
/// The Range static method, validation part.
/// </summary>
/// <param name="start">The start.</param>
/// <param name="count">The count.</param>
/// <returns></returns>
public static IEnumerable<int> Range(int start, int count)
{
long max = ((long) start) + count - 1;
if (count < 0 || max > Int32.MaxValue) throw new ArgumentOutOfRangeException(nameof(count));
return RangeIterator(start, count);
}
/// <summary>
/// The Range operator iterator.
/// </summary>
/// <param name="start">The start.</param>
/// <param name="count">The count.</param>
/// <returns></returns>
static IEnumerable<int> RangeIterator(int start, int count)
{
for (int i = 0; i < count; ++i)
{
yield return start + i;
}
}
For the other deferred operators I have created ThrowingExceptionEnumerable utility class, which helps with testing:
/// <summary>
/// The class responsible for verifying that linq operator is deferred.
/// </summary>
/// <typeparam name="T"></typeparam>
public sealed class ThrowingExceptionEnumerable<T> : IEnumerable<T>
{
/// <summary>
/// The methods throws <see cref="InvalidOperationException"/>.
/// </summary>
/// <returns></returns>
public IEnumerator<T> GetEnumerator()
{
throw new InvalidOperationException();
}
/// <inheritdoc />
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
/// <summary>
/// The method which checks that the given <see cref="deferredFunction"/> actually uses deferred execution.
/// When the function just call itself it should not throw an exception. But, when using the result
/// by calling <see cref="GetEnumerator"/> and than GetNext() methods should throws the <see cref="InvalidOperationException"/>.
/// </summary>
/// <typeparam name="TSource">The deferred function source type.</typeparam>
/// <typeparam name="TResult">The deferred function result type.</typeparam>
/// <param name="deferredFunction">The deferred function (unit of work under the test).</param>
public static void AssertDeferred<TSource,TResult>(
Func<IEnumerable<TSource>, IEnumerable<TResult>> deferredFunction)
{
var source = new ThrowingExceptionEnumerable<TSource>();
// Does not throw any exception here, because GetEnumerator() method is not yet used.
var result = deferredFunction(source);
// Does not throw InvalidOperationException even here, despite the fact that we retrieve the enumerator.
using var iterator = result.GetEnumerator();
Assert.Throws<InvalidOperationException>(() => iterator.MoveNext());
}
And for instance deferred Select operator has the following test:
/// <summary>
/// Should check that Select operator is deferred.
/// </summary>
[Fact]
public void VerifySelectExecutionIsDeferred()
{
ThrowingExceptionEnumerable<int>.AssertDeferred<int, int>(source => source.Select(x => x));
}
The first problem I have faced during writing such unit test for the Range operator is that Range is actually a static method and not an extension method. Also the thing is, that Range signature does not have a source parameter, so the same approach can not be used.
Do you have some clever ideas, how it can be tested?

External code isn't going to be able to do anything to verify that the values are generated on the fly. The only actual difference between a method like this and one that materializes a collection and returns it is the memory footprint at scale, which is quite difficult to reliably test in a unit test.
You can clearly tell that it doesn't do that my looking at the code, but you'd need to alter the implementation in some pretty significant way to end up with something that would allow you to verify that in a unit test (such as writing a more generalized "Generate" method that used a delegate to generate the next value).
If you had some sort of hard requirement that your implementation has unit tests to verify such things, I'd write such a Generate method, implement your Range method by calling Generate, write a unit test to verify that Generate doesn't call the delegate until generating the next value in the sequence, and then assert that the Range method defers execution because it uses Generate to produce its sequence. I wouldn't want to do this in production code though, this would really be just a way of meeting the requirement and making some sacrifices in readability and (mild) performance for the sake of it.

Related

How to document overloaded methods with the same XML comments?

I know there are questions like this, but they're old. So I'm creating a new one.
At the moment when there are 3 overloaded methods I have to do this:
/// <summary>
/// Description that described summary of an overloaded method.
/// </summary>
/// <param name="fileName">Description that describes filename parameter</param>
/// <param name="options">Description that describes options parameter</param>
/// <returns>Description of what method returns</returns>
public bool ReadFrom(string fileName, ReaderOptions options = null) {
return false;
}
/// <summary>
/// Description that described summary of an overloaded method.
/// </summary>
/// <param name="stream">Description that describes stream parameter</param>
/// <param name="options">Description that describes options parameter</param>
/// <returns>Description of what method returns</returns>
public bool ReadFrom(Stream stream, ReaderOptions options = null) {
return false;
}
/// <summary>
/// Description that described summary of an overloaded method.
/// </summary>
/// <param name="rawData">Description that describes rawData parameter</param>
/// <param name="options">Description that describes options parameter</param>
/// <returns>Description of what method returns</returns>
public bool ReadFrom(byte[] rawData, ReaderOptions options = null) {
return false;
}
And I would like to have something like this:
#region overloadedReadFromMethods
/// <summary>
/// Description that described summary of an overloaded method.
/// </summary>
/// <param name="fileName">Description that describes filename parameter</param>
/// <param name="options">Description that describes options parameter</param>
/// <returns>Description of what method returns</returns>
public bool ReadFrom(string fileName, ReaderOptions options = null) {
return false;
}
/// <param name="stream">Description that describes stream parameter</param>
public bool ReadFrom(Stream stream, ReaderOptions options = null) {
return false;
}
/// <param name="rawData">Description that describes rawData parameter</param>
/// <returns>Even considering that returns tag is present on the first overloaded method,
/// this overloaded method shows this specific description.
/// </returns>
public bool ReadFrom(byte[] rawData, ReaderOptions options = null) {
return false;
}
#endregion overloadedReadFromMethods
So the first overloaded method describes default description and then methods below can override it with their own descriptions. I want it to show in Visual Studio's IntelliSense.
TLDR - It's not possible
Long story short, as was the case in the past, you still cannot re-use comments this way.
Some interesting ideas here
Create one function with optional parameters. While this would mitigate the problem, I find that optional parameters are sometimes incovenient themselves as they overcomplicate the logic inside and make unit testing very difficult. Overaloading in your case make sense, so this solution does not apply.
Use the <overloads> comment. I can't see it in the official documentation though
Use the <see> and <seealso> xml tag to use reference
Use the <include> tag
This is still not a solution but it allows you to have separate xml documents and handle overall. include documentation
I think the extra work to document each method is necessary because they all have different signatures. Methods have different <param></param>
InheritDoc is a package that can be used to inherit xml docs.

How to cast C# interface to Java.Lang.Object?

Currently, I am working on IEGL10 in Xamarin. I have implemented ISurfaceHolderCallback and on SurfaceCreated(ISurfaceHolder holder) I have to call a method like this.
public void SurfaceCreated(ISurfaceHolder holder)
{
mEglSurface = mEgl.EglCreateWindowSurface(mEglDisplay, mEglConfig,
holder, null);
}
The problem is, the holder is a C# interface and EglCreateWindowSurface requires Java.Lang.Object. So how can I do the casting. If I directly cast holder like (Java.Lang.Object)holder. It is throwing invalid cast exception.
Please help guys I am really stuck here.
How to cast C# interface to Java.Lang.Object?
MonoDroid has integrated extension for this purpose :
Java.Lang.Object holder_object = holder.JavaCast<Java.Lang.Object>();
EGLSurface mEglSurface = mEgl.EglCreateWindowSurface(mEglDisplay, mEglConfig, holder_object, null);
You could see the document :
public static class Extensions
{
//
// Summary:
// /// Performs an Android runtime-checked type conversion. ///
//
// Parameters:
// instance:
// /// An Android.Runtime.IJavaObject instance to convert /// to a TResult instance.
// ///
//
// Type parameters:
// TResult:
// /// The type to convert instance to. /// TResult must implement the /// Android.Runtime.IJavaObject
// interface. ///
//
// Returns:
// /// A TResult representation for /// instance. ///
//
// Exceptions:
// T:System.ArgumentException:
// ///
// /// The JNI class for TResult cannot be found. ///
// ///
// -or-
// ///
// /// The proxy class for TResult is /// abstract, and the non-abstract Proxy can't
// be found. ///
// ///
//
// T:System.InvalidCastException:
// /// The Anrdroid object instance instance.Handle /// cannot be converted to the
// Android type corresponding to /// TResult. ///
//
// T:System.NotSupportedException:
// /// An unknown error occurred. ///
//
// Remarks:
// /// /// This is a hack, but a currently necessary one. /// ///
// /// Most of the Android types are staticly generated /// wrappers over a description
// of the underlying Android types. This /// intermediate description does not expose
// implementation details, /// which sometimes must be relied upon. ///
// ///
// /// For example, consider the /// Javax.Microedition.Khronos.Egl.EGLContext.EGL
// /// property, which returns an instance of the /// Javax.Microedition.Khronos.Egl.IEGL
// /// interface. This interface is useless, containing no members to /// invoke
// or use. The developer is instead expected to convert this /// instance to an
// interface which contains actual operations, such as /// the Javax.Microedition.Khronos.Egl.IEGL10
// interface. /// Unfortunately, the MonoDroid-generated wrappers do not know this,
// /// nor can they (the EGL10 implementation may be removed in a /// future Android
// version). The result is that if developers attempt /// to cast within managed
// code, the result will be a /// System.InvalidCastException: ///
// /// EGL10 egl10 = (EGL10) EGLContext.EGL; // throws ///
// /// The JavaCast() method allows performing such type conversions /// while bypassing
// the managed type system and instead relying upon /// the Android runtime system
// to perform the type checking. This /// allows: ///
// /// EGL10 egl10 = EGLContext.EGL.JavaCast<EGL10>(); // good ///
public static TResult JavaCast<TResult>(this IJavaObject instance) where TResult : class, IJavaObject;
}

Class to calculate hash codes in GetHashCode

I use an XOR based implementation in the GetHashCode implementation of most of my equatable types.
I've read several posts explaining why it is not the best solution so I decided to implement GetHashCode as suggested by Jon Skeet:
unchecked // Overflow is fine, just wrap
{
int hash = 17;
hash = hash * 23 + field1.GetHashCode();
hash = hash * 23 + field2.GetHashCode();
hash = hash * 23 + field3.GetHashCode();
return hash;
}
Since the code is likely to be similar in most implementations, I tried to build a helper class to calculate hash codes for all my classes. It should be an easy thing to do but one of the main constraints with GetHashCode is it has to be fast. Therefore any implementation involving allocation is probably a no go (for instance, the use of a non static class).
Ideally a call to such a method would look like:
public override GetHashCode() => HashCodeCalculator.Calculate(X, Y, Z);
And have all the logic (unchecked + primes + null check...). But the use of a params parameter implicitly creates an array.
Is it best to duplicate the hashing algorithm in each class instead? Or is a class like the following as efficient?
public static class HashCalculator
{
private const int _seed = 5923;
private const int _multiplier = 7481;
public static int Add(object value) => Add(_seed, value);
public static int Add(int current, object value)
{
int valueHashCode = (value != null) ? value.GetHashCode() : 0;
unchecked
{
return (current * _multiplier) + valueHashCode;
}
}
}
which can then be used like this:
public override int GetHashCode()
{
int result = HashCalculator.Add(Prop1);
result = HashCalculator.Add(result, Prop2);
return result;
}
You can create overloads for various small fixed numbers of parameters (2, 3, 4, etc. until you decide to stop), in order to avoid the array allocation, and then have a params overload that only ever needs to be used when there is a particularly large number of operands, at which point the overhead of the array allocation is less likely to be a problem (as it'll be a smaller percentage of the work done).
I can see why it is so tempting to have some kind of helper tool to calc hashes, but in this case efficiency is in great contradiction to convenience. You are trying to have a cookie and eat it and the answer depends on how much cookie you are willing to left over :)
One additional method call? Then it should have signature simmilar to
int HashCode(params int subhashcodes)
but invoking it will be ugly because you need to provide hashcodes of fields as parameters.
One method call and boxing? Then you can change int to object in previous signature to call fields hashcodes inside your method (I'm not fully sure that there will be no boxing in first case - feel free to correct me)
Personally I will stick to writing it by hand (or by Resharper).
After benchmarking it appears that using a struct like the following is almost as efficient as XORing and nicely encapsulates hash codes calculation.
/// <summary>
/// Calculates a hash code based on multiple hash codes.
/// </summary>
public struct HashCode
{
private const int _seed = 5923;
private const int _multiplier = 7481;
/// <summary>
/// Builds a new hash code.
/// </summary>
/// <returns>The built hash code.</returns>
public static HashCode Build() => new HashCode(_seed);
/// <summary>
/// Constructor from a hash value.
/// </summary>
/// <param name="value">Hash value.</param>
private HashCode(int value)
{
_value = value;
}
/// <summary>
/// Builds a new hash code and initializes it from a hash code source.
/// </summary>
/// <param name="hashCodeSource">Item from which a hash code can be extracted (using GetHashCode).</param>
public HashCode(object hashCodeSource)
{
int sourceHashCode = GetHashCode(hashCodeSource);
_value = AddValue(_seed, sourceHashCode);
}
private readonly int _value;
/// <summary>
/// Returns the hash code for a given hash code source (0 if the source is null).
/// </summary>
/// <param name="hashCodeSource">Item from which a hash code can be extracted (using GetHashCode).</param>
/// <returns>The hash code.</returns>
private static int GetHashCode(object hashCodeSource) => (hashCodeSource != null) ? hashCodeSource.GetHashCode() : 0;
/// <summary>
/// Adds a new hash value to a hash code.
/// </summary>
/// <param name="currentValue">Current hash value.</param>
/// <param name="valueToAdd">Value to add.</param>
/// <returns>The new hash value.</returns>
private static int AddValue(int currentValue, int valueToAdd)
{
unchecked
{
return (currentValue * _multiplier) + valueToAdd;
}
}
/// <summary>
/// Adds an object's hash code.
/// </summary>
/// <param name="hashCode">Hash code to which the object's hash code has to be added.</param>
/// <param name="hashCodeSource">Item from which a hash code can be extracted (using GetHashCode).</param>
/// <returns>The updated hash instance.</returns>
public static HashCode operator +(HashCode hashCode, object hashCodeSource)
{
int sourceHashCode = GetHashCode(hashCodeSource);
int newHashValue = AddValue(hashCode._value, sourceHashCode);
return new HashCode(newHashValue);
}
/// <summary>
/// Implicit cast operator to int.
/// </summary>
/// <param name="hashCode">Hash code to convert.</param>
public static implicit operator int(HashCode hashCode) => hashCode._value;
}
which can be used like this:
public override int GetHashCode() => new HashCode(Prop1) + Prop2;
EDIT:
.net core now has such a HashCode struct.

IEnumerable Concat Missing, does not contain a definition for 'Concat'

I have the following Class which inherits IEnumerable
public class LinesEnumerable : IEnumerable<Point>
{
protected readonly IPointSeries _pointSeries;
protected readonly ICoordinateCalculator<double> _xCoordinateCalculator;
protected readonly ICoordinateCalculator<double> _yCoordinateCalculator;
protected readonly bool _isDigitalLine;
/// <summary>
/// Initializes a new instance of the <see cref="LinesEnumerable" /> class.
/// </summary>
/// <param name="pointSeries">The point series.</param>
/// <param name="xCoordinateCalculator">The x coordinate calculator.</param>
/// <param name="yCoordinateCalculator">The y coordinate calculator.</param>
/// <param name="isDigitalLine">if set to <c>true</c> return a digital line .</param>
public LinesEnumerable(IPointSeries pointSeries, ICoordinateCalculator<double> xCoordinateCalculator, ICoordinateCalculator<double> yCoordinateCalculator, bool isDigitalLine)
{
_pointSeries = pointSeries;
_xCoordinateCalculator = xCoordinateCalculator;
_yCoordinateCalculator = yCoordinateCalculator;
_isDigitalLine = isDigitalLine;
}
/// <summary>
/// Returns an enumerator that iterates through a collection.
/// </summary>
/// <returns>
/// An <see cref="T:System.Collections.IEnumerator" /> object that can be used to iterate through the collection.
/// </returns>
public virtual IEnumerator<Point> GetEnumerator()
{
return _isDigitalLine ?
(IEnumerator<Point>)new DigitalLinesIterator(_pointSeries, _xCoordinateCalculator, _yCoordinateCalculator) :
new LinesIterator(_pointSeries, _xCoordinateCalculator, _yCoordinateCalculator);
}
/// <summary>
/// Returns an enumerator that iterates through a collection.
/// </summary>
/// <returns>
/// An <see cref="T:System.Collections.IEnumerator" /> object that can be used to iterate through the collection.
/// </returns>
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
However, when I try to do the following:
linesEnumerable = linesEnumerable.Concat(new[] { new Point(viewportWidth, lastYCoordinate) });
it says 'System.Collections.IEnumerable' does not contain a definition for 'Concat' and the best extension method overload 'System.Linq.Queryable.Concat(System.Linq.IQueryable, System.Collections.Generic.IEnumerable)' has some invalid arguments
I already have System.Linq namespace added
Anybody know why this is happening?
The compiler will give this error when the two collections are of different types T. For example:
List<int> l1 = new List<int>();
List<string> l2 = new List<string>();
var l3 = l1.Concat(l2);
var l4 = l1.Union(l2);
The Concat and Union calls will result in the following compile-time errors respectively:
'List' does not contain a definition for 'Concat' and the best extension method overload 'Queryable.Concat(IQueryable, IEnumerable)' requires a receiver of type 'IQueryable'
'List' does not contain a definition for 'Union' and the best extension method overload 'Queryable.Union(IQueryable, IEnumerable)' requires a receiver of type 'IQueryable'
It is confusing because the message is misleading and VS intellisense recognizes the extension methods. The solution is that l1 and l2 must be lists of the same type T.
Well this won't help you but this question is the top result when you google the error so I'm going to say what my problem was.
I had the following classes:
class Group
class Row : Group
class Column : Group
I was trying to call Concat on an IEnumerable<Row> with an IEnumerable<Column> to get an IEnumerable<Group>. This doesn't work because you can't convert the columns to rows. The solution was to cast my IEnumerable<Row> to IEnumerable<Group>.
e.g. rows.Cast<Group>().Concat(columns)

Is there a C# equivalent of typeof for properties/methods/members?

A classes Type metadata can be obtained in several ways. Two of them are:
var typeInfo = Type.GetType("MyClass")
and
var typeInfo = typeof(MyClass)
The advantage of the second way is that typos will be caught by the compiler, and the IDE can understand what I'm talking about (allowing features like refactoring to work without silently breaking the code)
Does there exist an equivalent way of strongly referencing members/properties/methods for metadata and reflection? Can I replace:
var propertyInfo = typeof(MyClass).GetProperty("MyProperty")
with something like:
var propertyInfo = property(MyClass.MyProperty)
No, unfortunately not. It's been discussed and even named: infoof (pronounced "in-foof" for comedy value) but it's not been implemented... yet. Eric Lippert has a blog post about it.
The closest you can come in C# 3 is to make the compiler generate an expression tree, and then pull it out of that - but that's hardly pleasant.
I've just implemented an equivalent of constructions 'propertyof' 'methodof' 'fieldof' using Syste.Linq.Expressions
so instead of writing
var mi = typeof (string).GetMethod("Concat", new[] {typeof (object), typeof (object)});
you can use:
var mi = ReflectionHelper.MethodOf(() => string.Concat(new object(), new object()));
Why do we need this? because now we safe to refactor method, we use via reflection
listing of helper class (you may need to add some informative exceptions in methods):
/// <summary>
/// Represents a set of helpers for .net reflection
/// </summary>
public static class ReflectionHelper
{
#region Public methods
/// <summary>
/// Gets a MethodInfo object from specified expression
/// </summary>
/// <typeparam name="TResult"></typeparam>
/// <param name="methodExpression"></param>
/// <returns></returns>
public static MethodInfo MethodOf<TResult>(Expression<Func<TResult>> methodExpression)
{
return ((MethodCallExpression)methodExpression.Body).Method;
}
/// <summary>
/// Gets a MethodInfo object from specified expression
/// </summary>
/// <param name="methodExpression"></param>
/// <returns></returns>
public static MethodInfo MethodOf(Expression<Action> methodExpression)
{
return ((MethodCallExpression)methodExpression.Body).Method;
}
/// <summary>
/// Gets a MethodInfo object from specified expression
/// </summary>
/// <param name="methodExpression"></param>
/// <returns></returns>
public static MethodInfo MethodOf<TInstance, TResult>(Expression<Func<TInstance, TResult>> methodExpression)
{
return ((MethodCallExpression)methodExpression.Body).Method;
}
/// <summary>
/// Gets a MethodInfo object from specified expression
/// </summary>
/// <param name="methodExpression"></param>
/// <returns></returns>
public static MethodInfo MethodOf<TInstance>(Expression<Action<TInstance>> methodExpression)
{
return ((MethodCallExpression)methodExpression.Body).Method;
}
/// <summary>
/// Gets a PropertyInfo object from specified expression
/// </summary>
/// <param name="propertyGetExpression"></param>
/// <returns></returns>
public static PropertyInfo PropertyOf<TProperty>(Expression<Func<TProperty>> propertyGetExpression)
{
return ((MemberExpression)propertyGetExpression.Body).Member as PropertyInfo;
}
/// <summary>
/// Gets a PropertyInfo object from specified expression
/// </summary>
/// <param name="propertyGetExpression"></param>
/// <returns></returns>
public static PropertyInfo PropertyOf<TInstance, TProperty>(Expression<Func<TInstance, TProperty>> propertyGetExpression)
{
return ((MemberExpression)propertyGetExpression.Body).Member as PropertyInfo;
}
/// <summary>
/// Gets a FieldInfo object from specified expression
/// </summary>
/// <param name="fieldAccessExpression"></param>
/// <returns></returns>
public static FieldInfo FieldsOf<TProperty>(Expression<Func<TProperty>> fieldAccessExpression)
{
return ((MemberExpression)fieldAccessExpression.Body).Member as FieldInfo;
}
//TODO: ConstructorOf(...)
#endregion //Public methods
}
as I understand we could not use same aproach to getParameterInfo or EventInfo
Another approach to do that, described by Jb Evain, see: http://evain.net/blog/articles/2010/05/05/parameterof-propertyof-methodof?utm_source=feedburner&utm_medium=feed&utm_campaign=Feed%3A+jbevain+%28Jb+in+a+nutshell%29
In c# 6 there's still no infoof but there is nameof:
var propertyInfo = typeof(MyClass).GetProperty(nameof(MyClass.MyProperty))
It's certainly not more terse, but at least it's refactoring friendly.
No, there is no such syntax in c#.

Categories