0

Why is it not possible to assign a class Non-static Data Member Variable with another Variable? For ex:

class A { 
   bool firstFlag=false; 
   bool secondFlag=firstFlag; // Showing Error.
   void SomeMethod(){} 
}
ProgrammingLlama
  • 36,677
  • 7
  • 67
  • 86
sss
  • 7
  • 2
  • you could have it return a calculated value, i.e. secondFlag will always return the value stored in firstFlag, with syntax `bool secondFlag => firstFlag;`, but that's not the actual answer to your question – AndrewP Oct 22 '18 at 04:09
  • 1
    Possible duplicate of [A field initializer cannot reference the nonstatic field, method, or property](https://stackoverflow.com/questions/14439231/a-field-initializer-cannot-reference-the-nonstatic-field-method-or-property) – mjwills Oct 22 '18 at 12:55

2 Answers2

0

Answer is OOPS :-)

firstFlag & secondFlag both are Class DataMembers. By definition you can only access them in Member Methods or Constructors.

To do what you need - try this:

internal class A
{
   bool firstFlag = false, secondFlag = false;
}
Prateek Shrivastava
  • 1,877
  • 1
  • 10
  • 17
  • You can assign a literal value and at the time the constructor is executed those values are assigned as default values. – 4ndy Oct 22 '18 at 04:30
-2

Thanks to the discussion on : A field initializer cannot reference the nonstatic field, method, or property

Please refer The C# Language Specification Section 10.5.5.2 Instance Field Initialization states - A variable initializer for an instance field cannot reference the instance being created. Thus, it is a compile-time error to reference "this" in a variable initializer.( hence it is a compile-time error for a variable initializer to reference any instance member through a simple-name).

sss
  • 7
  • 2
  • 1
    In these instances, rather than write an answer, just click `close` under your question and mark it as a duplicate. – mjwills Oct 22 '18 at 13:03