Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is `ClassA c = new ClassB` declaration possible?

Tags:

c#

I wonder if this is possible at all in C#:

ClassA c = new ClassB();

I get it why the right part has to have the class name, but then the left part doesn't have to have the class name (var c = new Anything()), so my guess is that it may be possible to create an instance of some class in this unusual way by explicitly typing the names of different (probably connected somehow) classes on the left and right of this expression. Am I wrong?

like image 710
user1306322 Avatar asked Jun 18 '26 15:06

user1306322


1 Answers

Well you could have something like

public interface ITADA
{
}

public class BaseTADA : ITADA
{
}

public class TADA : BaseTADA
{
}

and then

ITADA t1 = new TADA();
BaseTADA t2 = new TADA();
TADA t3 = new TADA();

This also allows you to do

List<ITADA> list = new List<ITADA>() 
        { 
            new TADA(), 
            new BaseTADA()
        };

You should have a look at

Polymorphism (C# Programming Guide)

like image 127
Adriaan Stander Avatar answered Jun 20 '26 04:06

Adriaan Stander



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!