Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a subclass in C#?

Tags:

How do I create a subclass in C# for ASP.NET using Visual Studio 2010?

like image 831
Neel Desai Avatar asked Nov 22 '10 13:11

Neel Desai


People also ask

What is a subclass in C sharp?

Sub Class: The class that inherits the other class is known as subclass(or a derived class, extended class, or child class). The subclass can add its own fields and methods in addition to the superclass fields and methods.

How do you declare a subclass in C++?

Declaring a subclass or derived class is as easy as declaring a superclass. By using a colon (:) after class (subclass) name, one can indicate that it (subclass) has been derived from another class (superclass).

Why do we need a subclass?

Using subclasses has several advantages: Reuse of code: Through inheritance, a subclass can reuse methods that already exist in a superclass. Specialization: In a subclass you can add new methods to handle cases that the superclass does not handle. You can also add new data items that the superclass does not need.

How do you inherit a class into another class in C#?

Inheritance (Derived and Base Class) In C#, it is possible to inherit fields and methods from one class to another. We group the "inheritance concept" into two categories: Derived Class (child) - the class that inherits from another class. Base Class (parent) - the class being inherited from.


2 Answers

Do you mean this?

public class Foo {}  public class Bar : Foo {} 

In this case, Bar is the sub class.

like image 120
Herman Cordes Avatar answered Oct 12 '22 19:10

Herman Cordes


Here is an example of writing a ParentClass and then creating a ChildClass as a sub class.

using System;  public class ParentClass {     public ParentClass()     {         Console.WriteLine("Parent Constructor.");     }      public void print()     {         Console.WriteLine("I'm a Parent Class.");     } }  public class ChildClass : ParentClass {     public ChildClass()     {         Console.WriteLine("Child Constructor.");     }      public static void Main()     {         ChildClass child = new ChildClass();          child.print();     } } 

Output:

 Parent Constructor. Child Constructor. I'm a Parent Class. 

Rather than rewriting yet another example of .Net inheritance I have copied a decent example from the C Sharp Station website.

like image 42
Brian Scott Avatar answered Oct 12 '22 17:10

Brian Scott