Ant's
Ant's

Reputation: 13811

If I use Delegates, I need those methods to be static?

I have a C# code like this:

using System;
delegate int anto(int x);
class Anto 
{
    static void Main()
    {
        anto a = square;
        int result = a(3);
        Console.WriteLine(result);
    }
    static int square(int x)
    {
        return x*x;
    }
}

which output's : 9. Well I'm a novice in C#, so I started to play around with this code and so when I remove the static keyword from the square method, then I'm getting error like this:

An object reference is required to access non-static member `Anto.square(int)'
Compilation failed: 1 error(s), 0 warnings

what causes this error? So if I use delegates I need the method to be static?

I run this code here

Thanks in advance.

Upvotes: 0

Views: 139

Answers (4)

BLUEPIXY
BLUEPIXY

Reputation: 40145

Static methods may be called from before creating an instance, you must be a static method.

Can be written as follows, if necessary

anto a = (x)=>x*x ;

Upvotes: 0

Austin Salonen
Austin Salonen

Reputation: 50215

It's required to be static because it's used in a static method. You'd need an instance of Anto to make your example work.

var myAnto = new Anto();
anto a = myAnto.square;

This is untested and may not compile based on the protection level of Anto.square.

Upvotes: 3

Mark Byers
Mark Byers

Reputation: 838186

It doesn't need to be static. You can assign a non-static method to a delegate, but if it is non-static then you need to instatiate an object of type Anto:

Anto anto = new Anto();
anto a = anto.square;

It's rather pointless here though since the method doesn't access any of the instance members. It makes more sense that it is static.

Upvotes: 2

Kieren Johnstone
Kieren Johnstone

Reputation: 42003

Because Main is static, it can only reference other static members. If you remove static from square, it becomes an instance member, and in the static context of Main, there is no instance of any object, so instance members aren't 'valid'.

Thankfully there's nothing crazy going on with delegates, it's just the way static works - it indicates members are global to a type and not an instance of that type.

Upvotes: 3

Related Questions