Click here to Skip to main content
15,881,172 members
Articles / Programming Languages / C#
Article

TypeTransmogrifier

Rate me:
Please Sign up or sign in to vote.
3.92/5 (4 votes)
13 Jun 2008CPOL3 min read 34K   19   13
Allows mapping of types to enumerated values.

Background

Occasionally we find ourselves in a situation where we have an object, and we want to determine which of several types of object it is in order to do something with it. For instance, we may have a Control, and if it's a Button we may want to do one thing with it, but if it's a TextBox we may want to do something else with it.

A fast, simple, and reliable way of handling that is:

C#
void F ( object item )
{
    if ( item is Button ) ...
    else if ( item is TextBox ) ...
}

Of great importance here is that this technique handles derived types properly. (It also works with interfaces, the other techniques presented here don't.)

This works very well, but can become unwieldy as more and more tests are added, both in terms of maintenance and performance.

Obviously, a switch would help smooth things out, but we can't use the type directly. The following won't compile:

C#
void F ( object item )
{
    switch ( item.GetType() )
    {
        case Button  : ...
        case TextBox : ...
    }
}

We can use strings with switch statements, so two common techniques are:

C#
void F ( object item )
{
    switch ( item.GetType().Name )
    {
        case "Button"  : ...
        case "TextBox" : ...
    }
}

and

C#
void F ( object item )
{
    switch ( item.GetType().FullName )
    {
        case "System.Windows.Forms.Button"  : ...
        case "System.Windows.Forms.TextBox" : ...
    }
}

There are also some among us who argue against using strings in switch statements; for them I submit the following:

C#
enum Controls 
{ 
    Button 
, 
    TextBox 
... 
}
 
void F ( object item )
{
    if ( Enum.IsDefined ( typeof(Controls) , item.GetType().Name ) )
    {
        switch ( (Controls) Enum.Parse ( typeof(Controls) , item.GetType().Name ) )
        {
            case Controls.Button  : ...
            case Controls.TextBox : ...
        }
    }
}

None of these techniques will handle derived types properly:
When passed an item of a type that derives from Button, but isn't named "Button" it won't pass the test though it probably should (false-negative).

In the first and third snippets, when passed an item of a type that doesn't derive from Button, but is named "Button" it will pass the test and probably cause an InvalidCastException (false-positive).

Therefore, while these techniques may be "good enough" in many cases, they are not completely reliable, so I feel that they are not suitable as general solutions.

Using an EnumTransmogrifier

The idea of using of an enumeration and Enum.Parse is actually pretty good, but it's subject to false-positives because we're limited to using the Name of the type rather than the Fullname. (Because the FullName contains characters that aren't allowed in a simple name.)

Mapping strings to enumeration values is what my EnumTransmogrifier [^] is all about:

C#
enum Controls 
{ 
    [Description("System.Windows.Forms.Button")]
    Button 
, 
    [Description("System.Windows.Forms.TextBox")]
    TextBox 
... 
}
 
EnumTransmogrifier<Controls> controls = new EnumTransmogrifier<Controls>() ;
 
void F ( object item )
{
    Controls control ;
 
    if ( controls.TryParse ( item.GetType().FullName , out control ) )
    {
        switch ( control )
        {
            case Controls.Button  : ...
            case Controls.TextBox : ...
        }
    }
}

That takes care of the false-positives. For the false-negatives we can check the type's BaseType, looping until we either find a match or run out of types to try.

TypeTransmogrifier

A TypeTransmogrifier is similar to an EnumTransmogrifier but it maps enumeration values to types rather than strings:

Update 2008-06-12: The class is now static and does not wrap an EnumTransmogrifier.

C#
public static partial class TypeTransmogrifier<T>
{
    private static class Null{}
    private static System.Type Nullity = typeof(Null) ;
 
    public static readonly System.Type BaseType = typeof(T) ;
 
    public static T DefaultValue ;

    private readonly System.Collections.Generic.Dictionary<System.Type,T> types =
        new System.Collections.Generic.Dictionary<System.Type,T>() ;
 
    private readonly System.Collections.Generic.Dictionary<T,System.Type> values =
        new System.Collections.Generic.Dictionary<T,System.Type>() ;
}

The Null class is used because null is not allowed as a key in a Dictionary.

The constructor iterates the values of the enumeration, accesses the attributes and populates the Dictionaries.

C#
static TypeTransmogrifier
(
) 
{
    if ( !BaseType.IsEnum )
    {
        throw ( new System.ArgumentException ( "T must be an Enum" ) ) ;
    }

    PIEBALD.Attributes.EnumDefaultValueAttribute.GetDefaultValue<T> ( out DefaultValue ) ;

    System.Type atttyp = typeof(PIEBALD.Attributes.TypeTransmogrifierAttribute) ;
        
    System.Type temp ;

    foreach 
    ( 
        System.Reflection.FieldInfo field 
    in 
        BaseType.GetFields
        ( 
            System.Reflection.BindingFlags.Public 
        | 
            System.Reflection.BindingFlags.Static 
        )
    )
    {
        if ( field.FieldType == BaseType )
        {
            foreach 
            ( 
                PIEBALD.Attributes.TypeTransmogrifierAttribute att 
            in 
                field.GetCustomAttributes ( atttyp , false )
            )
            {
                if ( att.Type == null )
                {
                    temp = Nullity ;
                }
                else
                {
                    temp = att.Type ;
                }
                
                if ( types.ContainsKey ( temp ) )
                {
                    throw ( new System.ArgumentException 
                    ( 
                        "Not all the types are unique." 
                    ,
                        field.Name
                    ) ) ;
                }
                
                types [ temp ] = (T) field.GetValue ( null ) ;
                values [ types [ temp ] ] = temp ;
            }
        }
    }
    
    return ;
}

The TryParse method uses the Dictionary of types and also checks the item's BaseType as needed:

C#
public static bool
TryParse
(
    object Subject
,
    out T  Result
)
{
    bool result = false ;
    
    Result = DefaultValue ;
    
    if ( Subject == null )
    {
        if ( result = types.ContainsKey ( Nullity ) )
        {
            Result = types [ Nullity ] ;
        }
    }
    else
    {
        System.Type objtype ;
        
        if ( Subject is System.Type )
        {
            objtype = (System.Type) Subject ;
        }
        else
        {
            objtype = Subject.GetType() ;
        }
    
        while ( !result && ( objtype != null ) )
        {
            if ( result = types.ContainsKey ( objtype ) )
            {
                Result = types [ objtype ] ;
            }
            else
            {
                objtype = objtype.BaseType ;
            }
        }
    }
        
    return ( result ) ;
}

Note that null references will result in a match if the enumeration is set up to allow that. Also, when a System.Type is passed in it will be used directly.

Update 2008-06-12: Added the following two methods.

Call TryParse and throw ArgumentException if it fails.

C#
public static T
Parse
(
    object Subject
)
{
    T result = DefaultValue ;
    
    if ( !TryParse ( Subject , out result ) )
    {
        string typ ;
        
        if ( Subject == null )
        {
            typ = "null" ;
        }
        else
        {
            if ( Subject is System.Type )
            {
                typ = ((System.Type) Subject).FullName ;
            }
            else
            {
                typ = Subject.GetType().FullName ;
            }
        }

        throw ( new System.ArgumentException
        (
            "The supplied type did not translate."
        ,
            typ
        ) ) ;
    }            
    
    return ( result ) ; 
}

Attempt to get the Type associated with the enumeration value.

C#
public static System.Type
GetType
(
    T Value
)
{
    System.Type result = null ;
    
    if ( values.ContainsKey ( Value ) )
    {
        if ( values [ Value ] != Nullity )
        {
            result = values [ Value ] ;
        }
    }
    else
    {
        throw ( new System.ArgumentException
        (
            "The supplied value did not translate."
        ,
            "Value"
        ) ) ;
    }            
    
    return ( result ) ;
}

Using the Code

In the earlier snippet, replace the EnumTransmogrifier with a TypeTransmogrifier and pass the item directly to TryParse:

C#
enum Controls 
{ 
    [Description("System.Windows.Forms.Button")]
    Button 
, 
    [Description("System.Windows.Forms.TextBox")]
    TextBox 
... 
}
 
// EnumTransmogrifier<Controls> controls = new EnumTransmogrifier<Controls>() ;
TypeTransmogrifier<Controls> controls = new TypeTransmogrifier<Controls>() ;
 
void F ( object item )
{
    Controls control ;
 
//    if ( controls.TryParse ( item.GetType().FullName , out control ) )
    if ( controls.TryParse ( item , out control ) )
    {
        switch ( control )
        {
            case Controls.Button  : ...
            case Controls.TextBox : ...
        }
    }
}

TypeDemo.cs

The included TypeDemo.cs file uses the following enumeration:

C#
public enum WinForms
{
    [PIEBALD.Attributes.TypeTransmogrifierAttribute(null)]
    Null
,
    [PIEBALD.Attributes.TypeTransmogrifierAttribute(typeof(System.Windows.Forms.Control))]
    Control
,
    [PIEBALD.Attributes.TypeTransmogrifierAttribute(typeof(System.Windows.Forms.ButtonBase))]
    ButtonBase
,
    [PIEBALD.Attributes.TypeTransmogrifierAttribute(typeof(System.Windows.Forms.Button))]
    Button
} ;

And defines the following classes which could cause false-positives and false-negatives with other techniques:

C#
private class Button {}
private class MyButton : System.Windows.Forms.Button {}

The demo will simply show the results of the TryParse:

C#
private static void
Show
(
    object What
)
{
    bool     res ;
    WinForms typ ;
 
    res = PIEBALD.Types.TypeTransmogrifier<WinForms>.TryParse ( What , out typ ) ;
 
    System.Console.WriteLine ( "{0} {1}" , res , typ ) ;
 
    return ;
}

Show ( null ) ;                                   // True  Null
Show ( new System.DateTime() ) ;                  // False Null
Show ( new System.Windows.Forms.Button() ) ;      // True  Button
Show ( new System.Windows.Forms.RadioButton() ) ; // True  ButtonBase  -- not a false-negative
Show ( new System.Windows.Forms.TextBox() ) ;     // True  Control     -- not a false-negative
Show ( new System.Web.UI.WebControls.Button() ) ; // False Null        -- not a false-positive
Show ( new Button() ) ;                           // False Null        -- not a false-positive
Show ( new MyButton() ) ;                         // True  Button      -- not a false-negative
Show ( typeof(MyButton) ) ;                       // True  Button      -- not a false-negative
Show ( (new MyButton()).GetType() ) ;             // True  Button      -- not a false-negative

History

2008-06-10 First submitted

2008-06-12 Made it static, added use of TypeTransmogrifierAttribute (at leppie's suggestion), added Parse and GetType

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
United States United States
BSCS 1992 Wentworth Institute of Technology

Originally from the Boston (MA) area. Lived in SoCal for a while. Now in the Phoenix (AZ) area.

OpenVMS enthusiast, ISO 8601 evangelist, photographer, opinionated SOB, acknowledged pedant and contrarian

---------------

"I would be looking for better tekkies, too. Yours are broken." -- Paul Pedant

"Using fewer technologies is better than using more." -- Rico Mariani

"Good code is its own best documentation. As you’re about to add a comment, ask yourself, ‘How can I improve the code so that this comment isn’t needed?’" -- Steve McConnell

"Every time you write a comment, you should grimace and feel the failure of your ability of expression." -- Unknown

"If you need help knowing what to think, let me know and I'll tell you." -- Jeffrey Snover [MSFT]

"Typing is no substitute for thinking." -- R.W. Hamming

"I find it appalling that you can become a programmer with less training than it takes to become a plumber." -- Bjarne Stroustrup

ZagNut’s Law: Arrogance is inversely proportional to ability.

"Well blow me sideways with a plastic marionette. I've just learned something new - and if I could award you a 100 for that post I would. Way to go you keyboard lovegod you." -- Pete O'Hanlon

"linq'ish" sounds like "inept" in German -- Andreas Gieriet

"Things would be different if I ran the zoo." -- Dr. Seuss

"Wrong is evil, and it must be defeated." –- Jeff Ello

"A good designer must rely on experience, on precise, logical thinking, and on pedantic exactness." -- Nigel Shaw

“It’s always easier to do it the hard way.” -- Blackhart

“If Unix wasn’t so bad that you can’t give it away, Bill Gates would never have succeeded in selling Windows.” -- Blackhart

"Use vertical and horizontal whitespace generously. Generally, all binary operators except '.' and '->' should be separated from their operands by blanks."

"Omit needless local variables." -- Strunk... had he taught programming

Comments and Discussions

 
Generalis operator Pin
marc_anic12-Jun-08 0:24
marc_anic12-Jun-08 0:24 
GeneralRe: is operator Pin
leppie12-Jun-08 5:38
leppie12-Jun-08 5:38 
GeneralRe: is operator [modified] Pin
PIEBALDconsult12-Jun-08 7:49
mvePIEBALDconsult12-Jun-08 7:49 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.