Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Can a class have virtual constructor??

If yes, why it is required?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
235 views
Welcome To Ask or Share your Answers For Others

1 Answer

no, a class cannot have a virtual constructor.

It doesn't make sense to have a virtual constructor. The order in which objects are constructed in C# is by constructing derived classes first, so the derived constructor is always called since the class you want to call is well known at the time of construction.

The other thing is, if you actually type this code out, you can quickly see that it makes very little sense at all

If you had:

public class BaseClass 
{
    public virtual BaseClass()
    {
    }
}

and then

public class InheritedClass : BaseClass
{
    //overrides baseclass constructor but why would you do this given that the     
    //constructor is always going to be called anyway??
    public override InheritedClass()
    {
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...