failedtofail
Member
- Joined
- Jun 16, 2022
- Messages
- 20
- Programming Experience
- Beginner
Hi
I have 3 classes, viz. MyClass1, My Class2, MyClass3 (note - did not bother with Constructors for MyClass 2 and 3 here). I was playing around instantiating MyClass2 and MyClass3 in MyClass1 and calling on methods in MyClass2 and 3. Got it to work but noticed something:
Following code works:
However, when I put the assignment statements in MyMethod outside the method then errors result:
This tells me that assignment statements need to be encapsulated in a method or getters/setters of properties (which I suppose are methods as well).
Can someone please explain why the assignment statement cannot be on its own in a class?
Thanks.
I have 3 classes, viz. MyClass1, My Class2, MyClass3 (note - did not bother with Constructors for MyClass 2 and 3 here). I was playing around instantiating MyClass2 and MyClass3 in MyClass1 and calling on methods in MyClass2 and 3. Got it to work but noticed something:
Following code works:
C#:
class MyClass1
{
private int age;
private string _name;
public MyClass1()
{
//Constructor code
}
public string Name
{
get { return _name; }
set
{
//code here to validate UI input for example
Object2.FuntionA();
}
}
public int MyMethod()
{
age = Object2.FuncB();
Object2.variable1 = Object3.FuncA();
}
MyClass2 Object2 = new MyClass2();
MyClass3 Object3 = new MyClass3();
}
However, when I put the assignment statements in MyMethod outside the method then errors result:
C#:
class MyClass1
{
private int age;
private string _name;
public MyClass1()
{
//Constructor code
}
public string Name
{
get { return _name; }
set
{
//code here to validate UI input for example
Object2.FuntionA();
}
}
public int MyMethod()
{
// come code
}
age = Object2.FuncB(); // Wrong - error
Object2.variable1 = Object3.FuncA(); // Wrong - error
MyClass2 Object2 = new MyClass2();
MyClass3 Object3 = new MyClass3();
This tells me that assignment statements need to be encapsulated in a method or getters/setters of properties (which I suppose are methods as well).
Can someone please explain why the assignment statement cannot be on its own in a class?
Thanks.