0

I need to incrementally increase GUID, which I successfully achieved using this

But now, I want to make it through the Increment operator ++ because I want my code to look pretty and concise.

My code:

public class GuidOps
{
    public static Guid operator ++(Guid input)
    {
        return input.Increment(); //Increment works as intended here
    }
}

That doesn't work because the type required for the ++ operator must the type of the class where the operator is declared.

enter image description here

Obviously I cannot override declaration of GUID itself

Do you think it is possible to define ++ on GUIDs ?

Community
  • 1
  • 1
AstroSharp
  • 1,872
  • 2
  • 22
  • 31
  • 1
    Why do you need to increase the `Guid`? What's the use case for this? – Sean Jun 06 '16 at 16:16
  • 1
    Don't do this...it's a confusing behavior and completely unexpected. Guids are not an incremental type and overriding it is beyond bizarre. Note that **pretty** and **concise** is only acceptable in the context of **readable** and **maintainable**. – David L Jun 06 '16 at 16:17

2 Answers2

1

Because Guid is sealed, the only way to do something even remotely close to this is to create a wrapper which in turn updates a Guid property on the wrapper. However, it comes with a few disclaimers...

  1. This is terribly confusing and dumb. Don't do it. Nothing about this behavior is expected or reasonable. It will lead to maintainability issues
  2. This still doesn't actually add the incrementor operator to the Guid definition itself; it only adds the operator to the wrapper. Now we've added abstraction for abstraction's sake and solved nothing. The code is less readable.

That said, the following will get you close to at least overriding the operator and to point out the issues that arise from trying to make code too clever:

public class GuidWrapper
{
    public Guid GuidInstance { get; set; } = Guid.NewGuid();

    public static GuidWrapper operator ++(GuidWrapper input)
    {
        input.GuidInstance = input.GuidInstance.Increment();
        return input;
    }
}

var wrapper = new GuidWrapper();
var guid = wrapper.GuidInstance;
var guid2 = wrapper++.GuidInstance;
David L
  • 32,885
  • 8
  • 62
  • 93
1

this is not possible to do cause GUID is a sealed structure

vadzvnik
  • 59
  • 4