Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Delegates & guid.newguid()

Tags:

c#

I just started using C# this afternoon, so be a little gentle.

Currently I am working on a type of "template engine" where one of the callbacks needs to generate a globally unique ID. I am using delegates to manage the callbacks.

Currently the code looks like this (though I have also tried an anonymous function & returning NewGuid directly w/o a variable):

static string UID(List<string> p)
    {
        string s = Guid.NewGuid().ToString();
        return s;
    }

Which, when called directly, works fine. However if I try to call it via the delegate (added to a StringDictionary via addCallback("generate UID", new CallbackWrapper(UID))), the program will generate the same GUID regardless of how many times I duplicate it; even though calling the method directly both before & after the event occurs results in a unique ID as expected. I'v

No doubt it's just something simple I've missed, inevitably stemming from me being relatively inexperienced at C#.

Any help would be appreciated.

Thanks.

Well, I've now tried Dictionary with the same result.

CallbackWrapper is just the delegate, it's defined like this:

delegate string CallbackWrapper(List<string> parameters);

The remainder of the work is done in another class, which looks like this:

class TemplateParser
{

    private Dictionary<string, CallbackWrapper> callbackMap;

    public TemplateParser(string directivePrefix, string directiveSuffix)
    {
        ...
        callbackMap = new Dictionary<string,CallbackWrapper>();
    }
    public TemplateParser() : this("<!-- {", "} -->") {}

    {
        callbackMap.Add(name, callback);
    }

    public string parse(string filename)
    {
            ...
            string replacement =
                callbackMap[directiveName](new List<string>(parameters.Split(new string[] { ";", " " }, StringSplitOptions.RemoveEmptyEntries)); 
            ...     
    }
}

I've stripped out the majority of the string handling code to save some space.

like image 615
B.H Avatar asked Feb 14 '11 12:02

B.H


1 Answers

The issue is in your calling code, not in the code itself, nor in the delegate.

Using delegates here definitely works if called correctly.

Furthermore, your code can be slightly simplified:

static string UID(List<string> p)
{
    return Guid.NewGuid().ToString();
}

(The variable is utterly redundant.)

like image 150
Konrad Rudolph Avatar answered Oct 05 '22 23:10

Konrad Rudolph