user2740190
user2740190

Reputation:

Avoiding overwriting properties on an object

I create an object like this:

MyObjectClass obj = new MyObjectClass();
foreach( .... )
{
   if( condition1 )
     FillMyObjectWith(obj, "hello", "", "");
   if( condition2)
    FillMyObjectWith(obj, "" , "hello" , "");
}
/////

private void FillMyObjectWith(MyobjectClass obj, string val1, string val2, string val3)
{
  obj.Field1 = val1;
  obj.Field2 = val2;
  obj.Field3 = val3;
}

Notice I have not used an "else" for if conditions because in that for each loop there are cases that both conditions can also be true, so when condition1 is True I pass "hello" to Field1 and pass blank to the other two fields, when condition2 is true I pass "hello" to Field2 and blank to the rest of the fields. The problem is if both conditions are true the last call overwrites the "hello" value of one of the fields with empty string. How can I avoid this situation?

Upvotes: 0

Views: 52

Answers (3)

Bobak_KS
Bobak_KS

Reputation: 554

Looks like you are only setting one value on each condition and leaving the rest to blank so one way is to change your method signature to only accept three arguments. One carries the value you want to set and one is an Enumeration that you flag it to show where is the value is getting assigned then in your method check for that Enum and assign the value based on that.

FillMyObjectWith(MyobjectClass obj, string val1, Enum )

Upvotes: 1

Jason Foglia
Jason Foglia

Reputation: 2531

You can try this:

private void FillMyObjectWith(MyobjectClass obj, string val1, string val2, string val3)
    {
        if (!string.IsNullOrEmpty(val1))
            obj.Field1 = val1;
        if (!string.IsNullOrEmpty(val2))
            obj.Field2 = val2;
        if (!string.IsNullOrEmpty(val3))
            obj.Field3 = val3;
    }

or

private void FillMyObjectWith(MyobjectClass obj, string val1, string val2, string val3)
    {
        obj.Field1 = val1 ?? string.Empty;
        obj.Field2 = val2 ?? string.Empty;
        obj.Field3 = val3 ?? string.Empty;
    }

Upvotes: 3

001
001

Reputation: 13533

You can do it like this:

foreach( .... )
{
   if ( condition1 && condition2)
      FillMyObjectWith(obj, "hello", "hello", "");
   else if( condition1 )
      FillMyObjectWith(obj, "hello", "", "");
   else if( condition2)
      FillMyObjectWith(obj, "" , "hello" , "");
}

Upvotes: 2

Related Questions