views:

54

answers:

4

Hi,

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,

+3  A: 

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?

Jon Skeet
so do i need to create a constructor for User class ?
superstar
if you need a constructor, than you have to create one...
codymanix
A: 

You can overload the explicit/implicit operators.
Take a look here

Itay
+1  A: 

@Jon's answer will do what you want, but you may want to look into the repository pattern for managing the creation of domain objects. That'll solve the bigger problem of making sure the code that uses the domain objects doesn't become wrapped around the axle just managing their lifetimes and serialization/deserialization. Let the repository take care of such concerns and focus on your domain logic.

David Gladfelter
+1  A: 

There is a solution with conversion operator, however, I'd personally prefer a static class method like User.FromString(string s) that parses the string and constructs a User instance. This way the code with be more readable and much easier to understand

Gobra