-3

is this possible?

string wellFormattedGuidAsString = ...;
Guid guid = wellFormattedGuidAsString;

...
Method(wellFormattedGuidAsString ); 
void Method(Guid id) { ... } 

I tried with explicit and implicit cast.

public static implicit operator Guid(string str)
{
    Guid guid;
    Guid.TryParse(str, out guid);
    return guid;
}
Jared Lovin
  • 543
  • 9
  • 24
Nerf
  • 938
  • 1
  • 13
  • 30

2 Answers2

0

You cannot create implicit and explicit operators outside of the desired object.

What you can do instead is :

public static class StringEx
{
    public static Guid ToGuid(this string str) 
    {
        Guid guid;
        Guid.TryParse(str, out guid);
        return guid;
    }
}

And later on you can use it like :

string mestring = " ... ";
Guid guid = mestring.ToGuid();

EDIT:

There's another way (of course there is) which is a bit useless but I'll post it here :

Make a class that will wrap string

public class StringWrapper
{
    string _string;

    public StringWrapper(string str)
    {
        _string = str;
    }

    public static implicit StringWrapper operator(string str)
    {
        return new StringWrapper(str);
    }

    public static implicit string operator(StringWrapper strWrapper)
    {
        return strWrapper._string;
    }

    public static implicit Guid operator(StringWrapper strWrapper)
    {
        Guid guid;
        Guid.TryParse(str, out guid);
        return guid;
    }

    public static implicit StringWrapper operator(Guid guid)
    {
        return guid.ToString();
    }
}

And this useless class let's you do something like this:

string str = "..";
Guid guid = (StringWrapper)str;
mrogal.ski
  • 5,828
  • 1
  • 21
  • 30
-2

Just overload your method:

void Method(Guid id) { ... } 
void Method(string guid) {
    Guid _guid;
    Guid.TryParse(guid, out _guid);
    Method(_guid);
}
maraaaaaaaa
  • 7,749
  • 2
  • 22
  • 37