Home > database >  Why is string concatenation not executed when using a field rather than an expression-bodied propert
Why is string concatenation not executed when using a field rather than an expression-bodied propert

Time:06-08

Why does the following code outputs "STRING_PART_1\STRING_PART_2"

class Program
{
    static void Main(string[] a)
    {
        Console.WriteLine(DummyClass.Property1);
    }
}

internal class DummyClass
{
    public static string Property1 => "STRING_PART_1\\"   Property2;
    public static string Property2 => "STRING_PART_2";
}

But the following code outputs "STRING_PART_1" ?

class Program
{
    static void Main(string[] a)
    {
        Console.WriteLine(DummyClass.Property1);
    }
}

internal class DummyClass
{
    public static string Property1 = "STRING_PART_1\\"   Property2;
    public static string Property2 = "STRING_PART_2";
}

What difference should I expect using an attribute (=) rather than an expression => ?

CodePudding user response:

This code:

public static string Property1 => "STRING_PART_1\\"   Property2;

is equivalent to this:

public static string Property1
{
    get => "STRING_PART_1\\"   Property2;
}

So when you access this property the getter is called (which calls the getter of Property2 inside).

These are not even properties - fields (not really matters in your case):

public static string Property1 = "STRING_PART_1\\"   Property2;
public static string Property2 = "STRING_PART_2";

The initialization order is: Property1 then Property2.

When you initialize Property1 the Property2 is not initialized yet (null) and this is the reason of your output.

When you change the declaration order to:

public static string Property2 = "STRING_PART_2";
public static string Property1 = "STRING_PART_1\\"   Property2;

you'll get desired result because Property2 is initialized before Property1.

CodePudding user response:

When you switch Property2 with Property1 while using = it will output STRING_PART_1\STRING_PART_2.

So the lambda expressions ignoring the order of the variables while the normal operations are not.

  • Related