Search Results for

    Show / Hide Table of Contents

    Specifying Types using TypeSets

    Even if the AssertionsDefinition class provides much flexibility when specifying the type to include in the assertion, there are some scenarios that are either hard to express or where the intention is ambiguous.

    Consider the following example (where DerivedClass1 is derived from BaseClass and DerivedClass2 is derived from DerivedClass1):

    AssertionsDefinition ad = new AssertionsDefinition();
    
    ad.NoNewInstances( typeof( BaseClass  ), true );
    ad.AllowNewInstances( typeof( DerivedClass1 ), true );
    ad.MaxNewInstances( typeof( DerivedClass2 ), 5 )
    

    In this case, it is not clear what happens if there are, for instance, 10 new instances of DerivedClass2. It is allowed by the AllowInstances call, but since 10 new instances exist, the MaxNewInstances should fail. As mentioned previously, the AllowXXX and MaxXXX assertions take precedence over the NoXXX assertions, but the precedence between AllowXXX and MaxXXX is not defined.

    To resolve this ambiguity, DerivedClass2 should not be included in the AllowNewInstances call. This can be accomplished by using a TypeSet. The TypeSet class is an immutable class that is used to define a set of Types by adding or removing types from another TypeSet. Two predefined TypeSets are available, TypeSet.Empty (containing no types) and TypeSet.All (containing all loaded types).

    The Add and Subtract methods can be used to create a new TypeSet with the specified types added or removed. For example, the following code can be used to create a TypeSet that contains the BaseClass type and all types derived from it, except the DerivedClass2 type.

    // Start with an empty TypeSet;
    TypeSet ts = TypeSet.Empty;
    // Add DerivedClass1 and all its derived classes to a
    // new TypeSet
    ts = ts.Add( typeof( DerivedClass1 ), true );
    // Remove DerivedClass2
    ts = ts.Subtract( typeof( DerivedClass2 ) );
    

    Using the above example, the assertions can be rewritten as:

    AssertionsDefinition ad = new AssertionsDefinition();
    
    TypeSet ts = TypeSet.Empty;
    ts = ts.Add( typeof( DerivedClass1 ), true );
    ts = ts.Subtract( typeof( DerivedClass2 ) );
    
    ad.NoNewInstances( typeof( BaseClass  ), true );
    ad.AllowNewInstances( ts );
    ad.MaxNewInstances( typeof( DerivedClass2 ), 5 )
    

    For more information about the TypeSet class, see the .NET Memory Profiler API Reference documentation.

    In This Article
    Back to top

    © Copyright 2002-2020. SciTech Software AB.
    For information about .NET Memory Profiler, see the product site at https://memprofiler.com