0

So I was reading through someone else's code and I was wondering if I'm right in thinking that this is just a way to initiate instances of a class easily.

private ExampleClass ex = new ExampleClass();
public ExampleClass Ex => ex;

I've been trying to mimic it - What I'm trying to run is:

class Program
{
    private List<int> testList = new List<int>();
    public List<int> TestList => testList;
    static void Main(string[] args)
    {

        var testList1 = new LambdaPractice(TestList);
        var testList2 = new LambdaPractice(TestList);

        testList1.Print();
        testList2.Print();

    }
}

However, I keep getting an error that in order to use TestList, I have to make TestList and testList both static variables. Why is this not the case in this person's code?

*Print is a function I implemented in the LambdaPractice class that prints out a instance id number.

Chae
  • 163
  • 1
  • 3
  • 12
  • 4
    Code inside a static method cannot access non-static properties. The original code did not require that because it didn't involve static. –  Aug 23 '18 at 16:58
  • Your assumption is not correct. Your first line of code instantiates an object and stores it in a private field. Your second line of code is just a property called `Ex` that only returns the value of the field. See [What is the => assignment in C# in a property signature](https://stackoverflow.com/questions/31764532/what-is-the-assignment-in-c-sharp-in-a-property-signature) That property does not make it "easier" to instantiate an object. –  Aug 23 '18 at 17:01

1 Answers1

0

I was wondering if I'm right in thinking that this is just a way to initiate instances of a class easily.

No, it is actually a short form for a get-only property that returns the value of the specified lambda. (Also called an expression-bodied member)

// This
public ExampleClass Ex => ex;
// is the same as
public ExampleClass Ex { get { return ex; } }

However, I keep getting an error that in order to use TestList, I have to make TestList and testList both static variables. Why is this not the case in this person's code?

As the error implies, you cannot access non-static class members from a static method. You either need to make the method non-static, or the lists static. It is hard to tell but, I would assume that the code you are referring to is in fact not static.

Some more information:

Static members Expression-bodied members

Wouter
  • 538
  • 6
  • 15