C
C#7mo ago
SplikZerys

Delegates

Learn delegates and I can't find any information about the following thing: 1. Why when we declare an instance of delegate with its name in class we can't provide it with one more method outside of its declaration? But it works in method as we can see, 2. Why we CAN add method in an instance of delegate during its declaration? Screenshot and code itself I want to completely understand why it is so
No description
7 Replies
SplikZerys
SplikZerysOP7mo ago
c#
using System.Net.Mime;

namespace ConsoleApp18;
class Program
{
static void Main(string[] args)
{
// 3
// Now we declare in method

Print print;
print = Text;
print += CountSymbols;

// But here it works well
}

// 1
// During declaring the first variable we can add method
// But when trying to add one more it's now working at all
// With 'Cannot resolve symbol 'print' or 'CountSymbols''
public static Print print = Text;
print += CountSymbols;

// 2
// For example, we can only add value in case during declaring variable
public static Print print2;
print2 = Text;

public static void CountSymbols(string text)
{
Console.WriteLine($"Text Length: {text.Length}");
}
public static void Text(string text)
{
Console.WriteLine($"{text}");
}
}
// We can declare delegate in and outside class but not in method
delegate void Print(string text);

c#
using System.Net.Mime;

namespace ConsoleApp18;
class Program
{
static void Main(string[] args)
{
// 3
// Now we declare in method

Print print;
print = Text;
print += CountSymbols;

// But here it works well
}

// 1
// During declaring the first variable we can add method
// But when trying to add one more it's now working at all
// With 'Cannot resolve symbol 'print' or 'CountSymbols''
public static Print print = Text;
print += CountSymbols;

// 2
// For example, we can only add value in case during declaring variable
public static Print print2;
print2 = Text;

public static void CountSymbols(string text)
{
Console.WriteLine($"Text Length: {text.Length}");
}
public static void Text(string text)
{
Console.WriteLine($"{text}");
}
}
// We can declare delegate in and outside class but not in method
delegate void Print(string text);

sibber
sibber7mo ago
2. for the same reason you cant do i = 5; outside of a function im not sure what you mean in 1
Unknown User
Unknown User7mo ago
Message Not Public
Sign In & Join Server To View
sibber
sibber7mo ago
ill also note that initializing fields does count as code execution, but its kind of an exception
Unknown User
Unknown User7mo ago
Message Not Public
Sign In & Join Server To View
sibber
sibber7mo ago
behind the scenes in the compiled code, its done in the (generated) ctor
Unknown User
Unknown User7mo ago
Message Not Public
Sign In & Join Server To View
Want results from more Discord servers?
Add your server