In java we can derived the class from abstract class in function itself. Can we do for C# also?

In Java we can derive the class from abstract class in function itself.

Can we do the same thing for C#?

public class A {
     public final static A d = new A();
    protected abstract class M {
        public int getValue() {
            return 0;
        }
    }

    protected static M[] c = null;
     public final static void Foo() {
        if (c == null) {
            M[] temp = new M[] {
                d.new M() {
                    public int getValue() {
                        return 1;
                    }
                },
                d.new M() {
                    public int getValue() {
                        return 2;
                    }
                },
                d.new M() {
                    public int getValue() {
                        return 3;
                    }
                }
            };
            c = temp;
        }
    }
}
Jon Skeet
people
quotationmark

No, there's no equivalent of anonymous inner classes in C#.

Typically for single-method abstract classes or interfaces, you'd use a delegate in C# instead, and often use a lambda expression to create instances.

So something similar to your code would be:

public class A 
{
    public delegate int Int32Func();

    private static Int32Func[] functions;

    // Note: this is *not* thread safe...
    public static void Foo() {
        if (functions == null) {
            functions = new Int32Func[]
            {
                () => 1,
                () => 2,
                () => 3
            };
        }
    }
}

... except that I'd use Func<int> instead of declaring my own delegate type.

people

See more on this question at Stackoverflow