MadBoy
MadBoy

Reputation: 11104

Multiple accessors for same value in c#

I have simple scenario where I have AnotherTest value based on Test value. This works fine most of the time so that whenever I provide Test I am sure to get AnotherTest easily.

public sealed class Transaction {
    public string Test { get;set; }
    public string AnotherTest{
        get {
            int indexLiteryS = Test.IndexOf("S");
            return Test.Substring(indexLiteryS, 4);
        }
    }
}

However I wanted to be able to also set AnotherTest value and be able to read it without having to provide Test value. Is this possible? So kinda 2 types of get based which way it was set. I know I could create 3rdTest but I have some methods that use AnotherTest and other fields and I would have to write overloads of that methods.

Edit:

I read some file supplied by bank. I cut it in pieces put some stuff in Test value and every other field (AnotherTest and similar) of the Transaction gets filled automatically. However later on I would like to read Transaction from SQL that is already in nice format so I don't need to provide Test to get the rest of the fields. I would like to set those fields with set and then be able to use get without setting Test value.

Upvotes: 1

Views: 478

Answers (3)

Loren Pechtel
Loren Pechtel

Reputation: 9093

I would suggest turning the problem over.

It sounds like you're dealing with a big field and subfields within it. Instead, how about promoting those subfields to fields and constructing/deconstructing the big field when it's accessed.

Upvotes: 0

Stefan H
Stefan H

Reputation: 6683

I think this would do what you want it to do:

public sealed class Transaction {
    public string Test { get;set; }
    public string AnotherTest{
        get {
            if (_anotherTest != null)
            {
                return _anotherTest;
            }
            else
            {
                int indexLiteryS = Test.IndexOf("S");
                return Test.Substring(indexLiteryS, 4);
            }
        }
        set {
            _anotherTest = value;
        }
    }
    private string _anotherTest = null;
}

Upvotes: 1

Jay
Jay

Reputation: 57939

Yes, like so:

public string Test { get; set; }

public string AnotherTest
{
   get
   {
      if(_anotherTest != null || Test == null)
         return _anotherTest;

      int indexLiteryS = Test.IndexOf("S")
      return Test.Substring(indexLiteryS, 4);
   }
   set { _anotherTest = value; }
}
private string _anotherTest;

That getter could also be expressed as

return (_anotherTest != null || Test == null)
    ? _anotherTest
    : Test.Substring(Test.IndexOf("S"), 4);

Upvotes: 4

Related Questions