Search code examples
c#.netassignment-operator

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.


Solution

  • 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.