简体   繁体   中英

How to change an object property passed as a parameter?

I want to pass an object to a method, however during this I want to change a property of said object. The way I do it now is like this:

MyClass someClass= someClasses.FirstOrDefault(s => s.Propert1. == "1");
someClass.Property1 = 2;
MyMethod(someClass);

However I dont want to do the extra step of creating a variable and then setting the property.

MyMethod(someClasses.FirstOrDefault(s => s.Propert1. == "1")/*.ChangeProperty()?*/); //This is where I would like to change Property1's value.

Is this good practice, if at all possible?

I don't see any reason to do this on a single line. This code looks absolutely fine:

MyClass someClass= someClasses.FirstOrDefault(s => s.Propert1. == "1");
someClass.Property1 = 2;
MyMethod(someClass);

If you want, you could add an extension method that does this:

// put this in a static class
static T WithNewPropertyValue<T>(this T t, Action<T> action) where T : class
{
    action(t);
    return t;
}

And call it like this

MyMethod(someClasses.FirstOrDefault(s => s.Propert1 == "1").WithNewPropertyValue(x => x.Propert1 = "2"));

But I feel like this decreases the readability of the code.

You can do it with the extension method which changes a property and returns changed object :

public static MyClass WithProperty2(this MyClass source, int value)
{
   if (source != null)  // make sure you handle null
     source.Property2 = value;

   return source;
}

Now you have a fluent API to do one-liners (which does not make your code much more maintainable):

MyMethod(someClasses.FirstOrDefault(s => s.Propert1. == "1").WithProperty2(42))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM