Home > Blockchain >  For variables that can be declared in each code area
For variables that can be declared in each code area

Time:11-04

I don't know what to define my question. Let's say that the code below names each area A, B, C, some types are declarable and some are impossible. I want to know about this difference.

(The code is just example of a deligate.)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
// Area A

delegate int MyDelegate(int a, int b);
public enum myenum { a,b,c };
class another { }
//int a; you can't 
//void func(int a); you can't

namespace ConsoleApp1
{
    // Area B

    class A
    {
        // Area C

        public int Func(int a, int b) { return a   b; }
    }
    class Program
    {
       
        static void Main(string[] args)
        {
            A a = new A();
            MyDelegate d = new MyDelegate(a.Func);
            d(1,2);
        }
    }
}

Can you tell me about this? Or what should I search for?

I tried to declare a variable in each different area. I think blocked it due to the problem of the global variable, but I want to know the details.

CodePudding user response:

In your example, you can only define types (classes, structures, enums, delegates) in areas A and B. Area A is outside the namespace declaration so any types declared there will be members of the root namespace. Area B is inside the namespace declaration so types declared there will be members of that namespace.

Area C is inside a type (the A class) so you can declare any type members there (nested types, fields, properties, methods, events).

  •  Tags:  
  • c#
  • Related