Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# value assignment to object reference directly

Person p = "Any Text Value";

Person is a class.

Is this anyway possible in C#.

I answered as no, but according to the interviewer this is possible. He didn't gave me any clues also.

like image 259
Amit Dhanuka Avatar asked Mar 06 '23 11:03

Amit Dhanuka


1 Answers

You can achieve this using an implicit conversion. It could be argued that this would be an abuse of an implicit conversion, given that it's not obvious exactly what "Any Text Value" should represent in this case. Here's an example of the code that would make your example succeed:

public class Person
{
    public string Name { get; set; }

    public static implicit operator Person(string name) =>
        new Person { Name = name }; 
}

Here's a .NET Fiddle example.

like image 73
Kirk Larkin Avatar answered Mar 15 '23 00:03

Kirk Larkin