Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why and when there are things I can not do in CLASS SCOPE in C#?

well... I'm confused about what can I do and what I can't do in CLASS SCOPE.

For example

=========================

class myclass
{


  int myint = 0;

  myint = 5; *// this doesnt work. Intellisense doesn't letme work with myint... why?*

  void method()
  {
    myint = 5; *//this works. but why inside a method?*
  } 
}

==================================

class class1
{ 
 public int myint;
}

class class2
{
  class1 Z = new class1();

  Z.myint = 5; *//this doesnt work. like Z doesnt exists for intellisense*

 void method()
  {
    Z.myint = 5; *//this Works, but why inside a method?*
  }
}

Thats I make so many mistakes, I dont understand what works on class scope and what doesnt work.

I know that there are local varaibles and its life cycle. But I dont understand the so well the idea.

like image 799
user396808 Avatar asked Jan 25 '26 11:01

user396808


1 Answers

A class can only contain declarations, initializations, and methods. It cannot contain statements of its own.

class MyClass
{
    int x; // a declaration: okay
    int y = 5; // a declaration with an initialization: okay
    int GetZ() { return x + y; } // a method: okay

    x = y; // a statement: not okay
}
like image 186
JSBձոգչ Avatar answered Jan 28 '26 00:01

JSBձոգչ