HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Linking GUIDs to enums

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
linkingguidsenums

Problem

While working with DirectShow, I came across the need to easily recognize different known 'sets' of GUIDs. E.g.: There are different GUIDs to indicate the possible time formats: None, Byte, Field, Frame, MediaTime, Sample. Working with enums instead of GUIDs would be a lot more useful in my opinion.

I decided to write the following abstract wrapper class which allows linking GUIDs to enums. You need to extend from it with the enum you want to expose as a type parameter.

```
///
/// An abstract class to represent a set of GUIDs as an enum.
///
/// An enum to use for the type to expose.
abstract class AbstractGuidEnum
{
///
/// The internal GUID.
///
public Guid Guid
{
get; private set;
}

///
/// The enum type for this GUID.
///
public T Type
{
get;
private set;
}

///
/// Specifies whether the GUID is known as a specific type or not.
///
public bool IsKnownType
{
get; private set;
}

///
/// List matching GUIDs with the enum types.
///
private static Dictionary m_typeList;

///
/// Create a new GUID enum wrapping the given GUID.
///
///
protected AbstractGuidEnum( Guid guid )
{
Guid = guid;
if ( IsGuidKnownType( guid ) )
{
IsKnownType = true;
Type = GetType( guid );
}
else
{
IsKnownType = false;
}
}

///
/// Create a new GUID enum for the specified type.
///
///
protected AbstractGuidEnum( T type )
{
Type = type;
Guid = GetGuid( type );
}

///
/// Call to make sure the list of types is initialized.
///
private void InitializeTypes()
{
if ( m_typeList == null )
{
m_typeList = new Dictionary();
FillTypeList( m_typeList );
}
}

public bool IsGuidKnownType( Guid guid )
{

Solution

I would avoid casting the same thing more then once. You can simply use as, it will return null if the object is not of the correct type.

public override bool Equals( object obj )
{
    AbstractGuidEnum guidObj = obj as AbstractGuidEnum;
    if ( guidObj == null )
    {
        return false;
    }

    return Guid.Equals( guidObj.Guid );
}


If you are going to have an equals method, it might be good to implement IEquatable and IEquatable.

I don't see anywhere that AbstractGuidEnum.Type, Guid, and IsKnowType are set, other then the constructor. If that is the case, I would make them into properties with backing fields and make the backing fields readonly.

Code Snippets

public override bool Equals( object obj )
{
    AbstractGuidEnum<T> guidObj = obj as AbstractGuidEnum<T>;
    if ( guidObj == null )
    {
        return false;
    }

    return Guid.Equals( guidObj.Guid );
}

Context

StackExchange Code Review Q#1371, answer score: 6

Revisions (0)

No revisions yet.