Amit Dhanuka
Amit Dhanuka

Reputation: 53

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.

Upvotes: 4

Views: 67

Answers (2)

Matthew Watson
Matthew Watson

Reputation: 109577

This can be done using implicit like so:

using System;

namespace Demo
{
    public sealed class Person
    {
        public Person(string name)
        {
            Name = name;
        }

        public static implicit operator Person(string name)
        {
            return new Person(name);
        }

        public string Name { get; }
    }

    static class Program
    {
        static void Main()
        {
            Person person = "Fred";

            Console.WriteLine(person.Name);
        }
    }
}

However, explicit conversion is preferred - you should generally only use implicit for things like inventing a new numeric type such as Complex.

Upvotes: 3

Kirk Larkin
Kirk Larkin

Reputation: 93083

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.

Upvotes: 4

Related Questions