Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C# class property with "two types"

I there any way in c# to create a property which will be basically a bool but can be set via string?
What I want to achive is simple:

string stringValue = "true";
object.BoolValue = stringValue ;
bool boolValue = object.BoolValue;

My idea was using get; set; but it always crashes on conversion. I can convert that string in object constructor but what if I want to change it later? Do I need a separate method for conversion (it is not only "true"/"false" but in that setter there should be a list of true values and false values and the rest is argument exception)?

Thanks for any ideas on how to achive this.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

UPDATE: Code from OPs comment

private bool _readOnly;

public bool ReadOnly {
    get => _readOnly;
    set => _readOnly = Convert.ToBoolean(value);
}

public DeviceProperty(string readOnly) {
    ReadOnly = readOnly;
}

>Solution :

You can’t modify built-in types but you can create a new type that defines Implicit Operator inside and you can set both string and bool to this type.
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/user-defined-conversion-operators

Also you can define an Explicit operator too, to cast your object to both of types without actually casting.

public struct MyBoolString
{
    private bool _value;

    public static implicit operator MyBoolString(bool value)
    {
        return new MyBoolString { _value = value };
    }

    public static implicit operator bool(MyBoolString value)
    {
        return value._value;
    }

    public static implicit operator MyBoolString(string value)
    {
        return new MyBoolString { _value = bool.Parse(value) };
    }

    public static implicit operator string(MyBoolString value)
    {
        return value._value.ToString();
    }
}

Then you can use it like that

MyBoolString myBoolString = "true";
myBoolString = true;

bool myBool = myBoolString;
string myString = myBoolString;

And as a property:

public MyBoolString Foo { get; set; }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading