create a subclass with a constructor in csharp

To create a subclass with a constructor in C#, you can use the concept of inheritance.

Here's an example:

main.cs
public class ParentClass
{
    public int ParentProperty { get; set; } 

    public ParentClass(int parentProperty)
    {
        ParentProperty = parentProperty;
    }
}

public class ChildClass : ParentClass
{
    public int ChildProperty { get; set; }

    public ChildClass(int parentProperty, int childProperty) : base(parentProperty)
    {
        ChildProperty = childProperty;
    }
}
393 chars
20 lines

In this example, we have a ParentClass with a constructor that takes an integer parameter. The ChildClass is a subclass of ParentClass and has an additional property called ChildProperty.

When creating a constructor for ChildClass, we use the : base(parentProperty) syntax to call the parent constructor and pass in the parent property value. We can then set the value of ChildProperty as needed.

Now we can create an instance of ChildClass and pass in values for both the parent and child properties:

main.cs
ChildClass example = new ChildClass(5, 10);
44 chars
2 lines

This creates a new instance of ChildClass with ParentProperty set to 5 and ChildProperty set to 10.

gistlibby LogSnag