Flip ‘where’ inheritance constraint for generic methods

The MSDN provides an example for a generic method in C# with a constraint on the generic type of the method. It must derive from T which is the generic type of the surrounding class Bar.

class Bar<T>
{
    void Foo<U>(Data<U> data) where U : T {/*...*/}
}

However it is not possible to compile:

class Bar<T>
{
    void Foo<U>(Data<U> data) where T : U {/*...*/}
}

Which is setting the constraint that U must be a base class of T.
With a little trick it is still possible to have that generic type constraint: by using an extension method.

class Bar<T>
{
    /*...*/
}

class BarExtension
{
   void Foo<T,U>(this Bar<T> bar, Data<U> data) where T : U {/*...*/}
}

Of course this is not as nice as having that method where it belongs to (in the Bar class) but still better than doing a runtime type check.

Flattr this!

Permission to change parameter and return references

When you hold a reference to an object you can change its state by for example calling methods of the object which have side effects or by setting different values for fields or properties. On first sight this is very natural to OO programming but can lead to problems when others do the same with the same object. Imaging you pass a collection to a method as parameter and while the method enqueues the collection for further processing, you keep on changing it. This can lead to behavior you most likely did not intend: You wanted the method to work with the state of the collection it had when you called the method. Instead it will use the state it has at the time of processing. Ideally all parameters your method takes are immutable (like primitive / value types or string) but in reality this will not always be possible.

Do provide clear documentation for a method regarding who has permission to change the content of all referenced objects reachable by reference type parameters after the method returns.

Similar to the (in) parameters the same thoughts apply for the (out) return value.

Do provide clear documentation for a method regarding who has permission to change the content of all referenced objects reachable by the returned value.

Following example illustrates documenting parameters

/// <summary>
/// Creates new customers in database
/// </summary>
/// <param name="customers">List of new customers</param>
/// <remarks>All reference type parameters and their children
/// must not be modified after calling this method.</remarks>
public void CreateCustomersInDatabase(List<customer> customers)
{
// ..
}

In this example it becomes clear why it is important to clarify that none of the reachable objects from any reference type parameter must be changed. Even though the caller might not modify the List he still might change the state of Customer objects referenced by the List. Obviously that is also not wanted by the method.

 

Do always prefer using immutable data structures.

 

Flattr this!