Ok question title is far from being self-explanatory. I see myself doing this often:
From this answer:
public static class Equality<T>
{
public static IEqualityComparer<T> CreateComparer<K>(Func<T, K> keySelector)
{
return new KeyEqualityComparer<K>(keySelector);
}
class KeyEqualityComparer<K> : IEqualityComparer<T>
{
readonly Func<T, K> keySelector;
public KeyEqualityComparer(Func<T, K> keySelector)
{
this.keySelector = keySelector;
}
public bool Equals(T x, T y)
{
----
}
public int GetHashCode(T obj)
{
....
}
}
}
What did I do: There is an implementation detail KeyEqualityComparer<T, K>
which I had to call:
new KeyEqualityComparer<Person, int>(p => p.ID);
By nesting it as a private class, not only did I hide the implementation (the public constructor of internal class is obscure now), but got a better syntax:
Equality<Person>.CreateComparer(p => p.ID);
Note here that I haven't inherited nested class from the parent class (which is static).
Or sometimes I see myself doing this:
public abstract class Equater<T> : IEqualityComparer<T>
{
public static Equater<T> Create<TKey>(Func<T, TKey> keySelector)
{
return new Impl<TKey>(keySelector);
}
public abstract bool Equals(T x, T y);
public abstract int GetHashCode(T obj);
class Impl<TKey> : Equater<T>
{
readonly Func<T, TKey> keySelector;
public Impl(Func<T, TKey> keySelector)
{
this.keySelector = keySelector;
}
public override bool Equals(T x, T y)
{
----
}
public override int GetHashCode(T obj)
{
....
}
}
}
Another similar one here
public class Accessor<S>
{
public static Accessor<S, T> Create<T>(Expression<Func<S, T>> memberSelector)
{
return new GetterSetter<T>(memberSelector);
}
class GetterSetter<T> : Accessor<S, T>
{
public GetterSetter(Expression<Func<S, T>> memberSelector) : base(memberSelector)
{
}
}
}
public class Accessor<S, T> : Accessor<S>
{
Func<S, T> Getter;
Action<S, T> Setter;
public bool IsReadable { get; private set; }
public bool IsWritable { get; private set; }
public T this[S instance]
{
get
{
if (!IsReadable)
throw new ArgumentException("Property get method not found.");
return Getter(instance);
}
set
{
if (!IsWritable)
throw new ArgumentException("Property set method not found.");
Setter(instance, value);
}
}
protected Accessor(Expression<Func<S, T>> memberSelector) //access not given to outside world
{
----
}
}
Note that in these two cases I inherited from wrapping class. So now not only did I get the benefits of the former but I can also maintain a list like this:
List<Equater<Person>> { persons with different implementations };
Its helping me from time to time. So I'm curious to know if there is a name for this pattern?