Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between Marshal.GenerateGuidForType(Type) and Type.GUID?

Type classType = typeof(SomeClass);
bool equal = Marshal.GenerateGuidForType(classType) == classType.GUID;

I haven't found a case that fail this condition.

So why and when should I use the Marshal method instead of simply getting the GUID property?

like image 759
HuBeZa Avatar asked Jan 27 '11 10:01

HuBeZa


2 Answers

see http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.marshal.generateguidfortype.aspx

... GenerateGuidForType provides the same functionality as the Type.GUID property.

So according to documentation they are the same. However, Marshal.GenerateGuidForType works only for RuntimeType objects, while Type.GUID is provided for some other Type implementations as well.

E.g.:


using System;
using System.CodeDom;
using System.Runtime.InteropServices;
using System.Workflow.ComponentModel.Compiler;

namespace Samples
{
    class Program
    {
        static CodeCompileUnit BuildHelloWorldGraph()
        {
            var compileUnit = new CodeCompileUnit();
            var samples = new CodeNamespace("Samples");
            compileUnit.Namespaces.Add(samples);

            var class1 = new CodeTypeDeclaration("Class1");
            samples.Types.Add(class1);

            return compileUnit;
        }


        static void Main(string[] args)
        {
            var unit = BuildHelloWorldGraph();
            var typeProvider = new TypeProvider(null);
            typeProvider.AddCodeCompileUnit(unit);
            var t = typeProvider.GetType("Samples.Class1");
            Console.WriteLine(t.GUID); // prints GUID for design time type instance.
            Console.WriteLine(Marshal.GenerateGuidForType(t)); // throws ArgumentException.
        }
    }
}

like image 61
Konstantin Oznobihin Avatar answered Oct 16 '22 16:10

Konstantin Oznobihin


According to MSDN, "GenerateGuidForType provides the same functionality as the Type.GUID property". It should be safe to use the one that suits you the best.

like image 2
nulltoken Avatar answered Oct 16 '22 14:10

nulltoken