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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With