Moslem Ben Dhaou
Moslem Ben Dhaou

Reputation: 7005

How to reference a method return value in a subsequent method?

I am just wondering if there is a way to simplify this code:

var myStr = GetThatValue();
myStr = myStr.Substring(1, myStr.Length - 2); // remove first and last chars

into this:

// how to get hold of GetThatValue return value?
var myStr = GetThatValue().Substring(1, hereWhat.Length - 2);

I though about this keyword but it does not work in this context. It will reference the class instance as expected.

Upvotes: 2

Views: 87

Answers (3)

romanoza
romanoza

Reputation: 4862

You can try this way (using a temporary variable):

string temp;
var myStr = (temp = GetThatValue()).Substring(1, temp.Length - 2);

or (even shorter):

string myStr = (myStr = GetThatValue()).Substring(1, myStr.Length - 2);

It works too. You have to change var to string while declaring the myStr variable.

Upvotes: 3

ASh
ASh

Reputation: 35646

another altenative - make an extension method:

public static class Util
{
    public static string Trim(this string input, int headTrim, int tailTrim)
    {
        return input.Substring(headTrim, input.Length - headTrim - tailTrim);
    }
}

usage:

var str = GetThatValue().Trim(1, 1);

one-line solution (just for excercise)

regex to remove 1st and last char

string result = Regex.Replace(Regex.Replace(GetThatValue(), "^.", ""), ".$", "");

Upvotes: 0

David
David

Reputation: 218798

Nope. The alternative is this:

var myStr = GetThatValue().Substring(1, GetThatValue().Length - 2);

Which, as you can see, invokes GetThatValue() twice. So if that operation is expensive or returns different values then it probably shouldn't be re-invoked.

Even if it's not an expensive operation, this is exactly a textbook case of what variables are for... storing values.


It's possible to have a scenario where this is perfectly acceptable, though. Consider C#'s properties, which are really just syntactic sugar over classic getter/setter methods. If we look at those getters in a traditional Java sense, we might have something like this:

private thatValue;
public string GetThatValue() { return someString; }

// later...
var myStr = GetThatValue().Substring(1, GetThatValue().Length - 2);

In this case it's not an expensive operation, nor would it return different values. (Threading notwithstanding.) In this case there's no discernible logical difference between using the variable vs. the method, as the method is simply a wrapper for a class-level variable.

In fact, this approach is often used when the getter has some logic which should always wrap the access to that variable, even for private-only members.

Upvotes: 6

Related Questions