How to declare temporary variables as C# expressions?

declare variable in class c#
variable declaration in c#
declare public variable in c#
c# set class variable

Is there a way to declare temporary variables in expressions for reusing intermediary results?

The motivation is to still be able to use fluent style call chains and expression bodied methods when you need to use a calculated result more than once in logic or transformations e.g.

public static string Foo(IBar bar)
{
    var result = bar.LongCalculation();

    return result.HasError
        ? throw new Exception()
        : result.ToString();
}

I thought I might be able to use let/select linq query keywords but it doesn't seem possible without a from clause e.g.

public static string Foo(IBar bar) =>
    let result = bar.LongCalculation()                
    select result.HasError
        ? new Exception()
        : result.ToString();

You could use an Extension method:

public static class LongCalculationExtensions
{
    public static ILongCalculationResult ThrowIfHasError(this ILongCalculationResult result)
    {
       if(result.HasError) throw new Exception("Your exception here");

       return result;
    }
}

Then you could use it like this:

public static string Foo(IBar bar) => bar.LongCalculation().ThrowIfHasError().ToString();   

What's New in C# 7.0, Discards are temporary, write-only variables used in assignments when you The list of members that can be authored using expressions has grown. You can now declare out variables in the argument list of a method call,  C# 7.0 Tips : Directly throw Exception as an Expression – Throw expressions in C# 7.0. We have all seen, one of the very frequent uses of the Out parameter was Converts the string representation of a number. With the help of out variable, now we can directly declare like below. bool success = int.TryParse(Console.ReadLine(), out int result);

My preferred approach is Timothy Shields answer here:

How to "let" in lambda expression?

Create an extension-method similar to F#'s pipe operator:

public static class FunctionalExtensions
{
    public static TResult Pipe<T, TResult>(this T value, Func<T, TResult> func) =>
        func(value);
}

And call it like this

public static string Foo(IBar bar) =>
    bar.LongCalculation()
       .Pipe(result => result.HasError
           ? throw new Exception()
           : result.ToString();

Implicitly typed local variables, Local variables can be declared without giving an explicit type. the variable from the expression on the right side of the initialization statement  Is there a way to declare temporary variables in expressions for reusing intermediary results? The motivation is to still be able to use fluent style call chains and expression bodied methods when you need to use a calculated result more than once in logic or transformations e.g.

My previous answer for Pipe required a lambda, a better solution with less overhead is to take advantage of an inline out declaration:

public static class FunctionalExtensions
{
    public static T Assign<T>(this T o, out T result) =>
        result = o;
}

And call it like this

public static string Foo(IBar bar) =>
    bar.LongCalculation()
       .Assign(out var result)
       .HasError
           ? throw new Exception()
           : result.ToString();

Is an inline temporary variable recommended in a return statement , The temporary variable is customers and to inline it means replacing its only use with the initialization expression. There's no such thing as an "inline temporary  Temporary tables and table variables, both have their own pros and cons. We need to decide which one to use and when. Let us compile the list for differences. ⇒ Table variable (@table) is created in the memory. Whereas, a Temporary table (#temp) is created in the tempdb database.

Temporary Variables, In addition, system functions often obtain a temporary variable to return the result of variables to hold values that are the result of evaluating expressions. It is common to want to create a temporary variable with a form that mimics that of COM Object Creation · C++ Client Code Sample · C# Code Sample · Sample IDL​  A variable is nothing but a name given to a storage area that our programs can manipulate. Each variable in C# has a specific type, which determines the size and layout of the variable's memory the range of values that can be stored within that memory and the set of operations that can be applied to the variable.

.NET 4 Wrox PDF Bundle: Professional ASP.NET 4, Professional C# 4, , NET 4, Professional C# 4, VB 2010 Programmer's Ref, WPF Programmer's Ref, Professional or the result of an expression into a procedure, there is no variable to pass by reference, so Visual Basic must create its own temporary variable. You declare the out variable where you use it, not on another line above. No need to assign an initial value. By declaring the out variable where it's used in a method call, you can't accidentally use it before it is assigned. Tuples. C# provides a rich syntax for classes and structs that is used to explain your design intent.

Professional Refactoring in C# & ASP.NET, Because in C# you can initialize the variable in the declaration statement, you have the variable with the expression itself by inlining the temporary variable. Temp Variables are created using a “DECLARE” statement and are assigned values using either a SET or SELECT command. After declaration, all variables are initialized as NULL, unless a value is provided as part of the declaration. This acts like a variable and exists for a specific batch of query execution.

Comments
  • Why you don't call a method in your expression bodied method like LongCalculationSafe? Then you could use whatever code you need there.
  • Why do you want to use an expression bodied method? It's just syntax sugar that can be used when the body is a one-liner. If you need multiple lines, just use the regular method syntax.
  • I prefer the functional flowing style - it's the direction c# is going in and interested to know if it has a solution - it's frustrating to have to rewrite a method to be cury braced because of a detail in the logic/transformation needs to reuse a temporary.
  • LINQ makes no sense here. LINQ is effectively a "better foreach" in the sense that it works on collections and iterates over them. But that's not the case here, you're working with a singular result object. LINQ only deals with collection iteration so even if you hacked it in (e.g. by putting your singular object in a list), it wouldn't serve a meaningful purpose.
  • Interesting thanks. This is good for handling specifc cases that are frequent but not the general case. btw the extension method can use throw expressions so can be expression bodied too.