-4

Base class:

protected virtual List<string> Name { get; } = null;

Child class

protected override List<string> Name => new List<string>();// No error

if write equal operator:

protected override List<string> Name = new List<string>();

the compiler raise error:

"The modifier 'override' is not valid for this item"

=> is an anonymous function. In both cases we are assigning value to the Name member. Why is compiler giving error for = operator.

Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
Sravani
  • 59
  • 5
  • 6
    It sounds like you're just asking what an [expression bodied property](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/statements-expressions-operators/expression-bodied-members) is. You're getting a compiler error because an expression bodied property is *very different* from just declaring a field and assigning a value to it. – David Apr 21 '23 at 18:55
  • Maybe this can help [virtual property](https://stackoverflow.com/a/9238902/13448436) – Lazar Đorđević Apr 21 '23 at 18:56
  • You are defining a class. With the lambda operator `=>` you are defining a function that will be used as the get accessor for the `Name` property. With the assignment operator `=`, you could initialize the property as `protected override List Name { get; } = new List();` (similar to the initialization in the base class). – Jonathan Dodds Apr 21 '23 at 19:23

1 Answers1

2

So you have a property in the base class:

// Read-only property which returns List<string> and 
// which is initialized with null 
protected virtual List<string> Name { get; } = null;

It's perfectly legal to override this property into a bit different one:

// Still read-only property which returns List<string> and
// which creates a new instance of List<string> on each call (note =>)
protected override List<string> Name => new List<string>();

But then you try to declare field instead of property, which is illegal:

// Name is a field (note abscence of "get")
// Compiler complains: it's impossible to override a field
protected override List<string> Name = new List<string>();

To correct your code, stick to property, add { get; }:

// Read-only property which returns List<string> and 
// which is initialized with an instance of List<string>
protected override List<string> Name { get; } = new List<string>();
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215