Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type conversion from string to User defined type

I have a string type to be assigned to owner of type 'User'. My method GetFullName returns the name in a 'string' format and i need to assign it to owner of type 'User'

def.Owner = uf.GetFullName(row["assignedto"].ToString());

Any suggestions would be helpful,

like image 463
superstar Avatar asked Nov 28 '25 19:11

superstar


1 Answers

So you need something like:

public class User
{
    ...

    public static implicit operator User(string x)
    {
        return new User(x);
    }
}

Personally, I'm not a fan of implicit conversions, however. You say that you "need" to assign it this way... what's wrong with an explicit constructor or static method call? Or perhaps an extension method (ToUser) on string?

like image 74
Jon Skeet Avatar answered Nov 30 '25 08:11

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!