jitm
jitm

Reputation: 2597

Is there a syntax for creating an anonymous subclass in C#?

Can I create instance of abstract class in C#/.net like in Java ?

Additional Info

I think a lot of us does not understand what do I mean? So, In java I can create abstract class like this :

Simple abstract class :

/**
 * @author jitm
 * @version 0.1
 */
public abstract class TestAbstract
{
    public abstract void toDoSmth();
}

Code where I've create instance of abstract class

/**
 * @author jitm
 * @version 0.1
 */
public class Main {
    public static void main(String[] args) {
        TestAbstract testAbstract = new TestAbstract() {
            @Override
            public void toDoSmth() {
                System.out.println("Call method toDoSmth");
            }
        };
    }
}

Can I to do in c# something like this ?

Upvotes: 14

Views: 4783

Answers (4)

Peter L
Peter L

Reputation: 3343

Alternative: An init property of type Func<>

I needed to unit test a class that used a TcpClient (which is hard to mock). This is what I used...

In the class to be tested:

public Func<string, int, CancellationToken, Task> CheckConnectivityAsync { get; init; } =
    async (host, port, cancellationToken) =>
    {
        using var tcpClient = new TcpClient();
        // etc.
    };

In the unit test class constructor:

    _testSubject = new MyClass(context)
    {
        CheckConnectivityAsync = _mockCheck.Object
    };

With the right package names you could tighten the accessibility of the property (instead of using public).

Upvotes: 0

Struan
Struan

Reputation: 655

Your example uses an anonymous implemention for an abstract class. C# does not support the anonymous implementation, so you need to create another one that extends it.

public abstract class TestAbstract { }

public class AnotherTest : TestAbstract { }

Upvotes: -3

Pablo Grisafi
Pablo Grisafi

Reputation: 5047

Neither in Java nor in C# you can create an instance of an abstract class. You will always need to create a concrete class that inherits from the abstract class. Java lets you do it without naming the class, using anonymous classes. C# does not give you that option.

(Edited to show a delegate as a replacement. I don't have access to VS here, so it may not compile, but this is the idea )

Usually in Java when you use an abstract class with a single abstract method (SAM) what you are really trying to achieve is to pass some code as a parameter. Let's say you need to sort an array of objects based on the class name, using Collections.sort(Collection, Comparator) (I know Comparator is an interface, but it is the same idea) Using an anonymous class to avoid extra typing, you can write something like

   Comparator<Object> comparator = new Comparator<Object>{
        @Override
        public int compare(Object o1, Objecto2) {
            return o1.getClass().getSimpleName().compareTo(o2.getClass().getSimpleName()));
        }//I'm not checking for null for simplicity
   } 
   Collections.sort(list, comparator)

In C# 2.0 and beyond you can do pretty much the same using the Comparison<T> delegate. A delegate can be thought as a function object, or in java words, a class with a single method. You don’t even need to create a class, but only a method using the keyword delegate.

Comparison<Object> comparison = delegate(Object o1, Object o2)
{
    return o1.class.Name.CompareTo(o2.class.Name);        
};

list.sort(comparison);

In C# 3.0 and beyond you can write even less code using lambdas and type inference:

list.sort((o1, o2) => o1.class.Name.CompareTo(o2.class.Name))

Anyway, if you are migrating code form java to c# you should read about delegates...in many of cases you will use delegates instead of anonymous classes. In your case, you are using a method void toDoSmth(). There is a delegate called Action which is pretty much the same thing, a method with no parameters and no return.

Upvotes: 9

Justin Niessner
Justin Niessner

Reputation: 245419

No. Not directly. The closest you can come (assuming you have the following class structure):

public abstract class AbstractClass
{
}

public class ChildClass : AbstractClass
{ 
}

Is:

AbstractClass instance = new ChildClass();

Upvotes: 8

Related Questions