1

I created an extension method for generating string from System.Guid like this.

public static class Fnk
{

    public static string Guid(bool dash = true)
    {
        return dash ? System.Guid.NewGuid().ToString() : System.Guid.NewGuid().ToString("N");
    }
}

I am using it like Fnk.Guid(). I wonder that, is it possible to call it like string.Guid()? If yes, how?

Habip Oğuz
  • 921
  • 5
  • 17
  • 1
    `this sting variableName` must be the first argument. In your code you just return a guid value based on condition – Pavel Anikhouski Mar 03 '20 at 12:01
  • 2
    An extension-method has a `this`-kewyord for the param. Your code is no extension-method. – MakePeaceGreatAgain Mar 03 '20 at 12:01
  • Do you want to parse string to guid? what will the string.Guid() method do? – mustafa Mar 03 '20 at 12:03
  • 3
    Also, Guid already has an option for generating a dash-less string. `Guid.NewGuid().ToString("N")` – Silvermind Mar 03 '20 at 12:04
  • I'm sorry, but I don't understand what's the point of this. [`Guid` has an overload of `ToString` that takes in a string as a format specifier](https://learn.microsoft.com/en-us/dotnet/api/system.guid.tostring?view=netframework-4.8#System_Guid_ToString_System_String_) - use `"N"` to remove the dashes. – Zohar Peled Mar 03 '20 at 12:06
  • Thanks to everyone who warned me. I fixed the dash. – Habip Oğuz Mar 07 '20 at 18:37

1 Answers1

8

Is it possible to call it like string.Guid()

No. Extension methods allow static methods to be called as if they're instance methods. You're trying to write a static method and allow it to be called as if it's a static method on an unrelated type.

That isn't supported - at least not as of C# 8.

Writing genuine extension methods targeting string is entirely feasible. For example:

public static class PointlessExtensions
{
    public static HasEvenLength(this string text) => (text.Length & 1) == 0;
}

Called as:

bool result1 = "odd".HasEvenLength(); // False
bool result2 = "even".HasEvenLength(); // True
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194