San Jaisy
San Jaisy

Reputation: 17128

Customize setter property C# 10

I am using C# 10 and want to convert any value that bind to Operator to lowercase

public class Rule
 {
    public string Operator { get; set; }
 }

I can't do creating another property and set the value.

private string _Operator ;
public string Operator 
{
  get            
  {
    return _Operator ;
  }
  set             
  {
    _Operator = value.toLower();
  }
}

Is there any way to directly convert to lowercase whatever bind to public string Operator { get; set; }

Upvotes: 0

Views: 256

Answers (1)

tmaj
tmaj

Reputation: 35135

A. Have a separate property

public string Operator { get; set; }

public string BetterOperator => Operator?.ToLower();

If you have an original class that you cannot fully control (e.g. auto-generated) I'd try with partial classes:

public partial class Rule
{
    public string Operator { get; set; }
}

public partial class Rule
{
    public string BetterOperator => Operator?.ToLower();
}

B. Virtual

Another option could be making the property virtual and using a derived class:

(I switched from classes to records just for a nice Console.WriteLine)

public record Rule
{
    public virtual string? Operator { get; set; }
}

public record RuleExt : Rule
{
    public override string? Operator
    {
        get { return base.Operator; }
        set { base.Operator = value?.ToLower(); }
    }
}

Then the following:

var r = new RuleExt() { Operator = "Plus" };

Print(r);

static void Print(Rule r) => Console.WriteLine(r);

Will print:

RuleExt { Operator = plus }

Upvotes: 1

Related Questions