C# Programming Illustrated Guide For Beginners & Intermediates by William Sullivan

C# Programming Illustrated Guide For Beginners & Intermediates by William Sullivan

Author:William Sullivan
Language: eng
Format: epub
Tags: C sharp programming, object oriented programming, C# & Operators, Learn Coding Fast, Hands on Project, Constants, Data types, Operators & Compiler, jump statement, Arrays & Lists, Loops & Variables & Literals, C# strings, polymorphism, flow statements, Absolute Beginners Guide, Practical Examples
Publisher: Healthy Pragmatic Solutions Inc
Published: 2019-08-17T00:00:00+00:00


Constructor Overloading

You can have more than one constructor per class. The names of all the constructors will always be exactly the same as the name of the class; the difference lies in the numbers and types of parameters. Having more than one constructor in a class refers to constructor overloading. Let’s see this in action:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

namespace MyProgram

{

class Program

{

static void Main(string[] args)

{

// Creating Object of the Airplane Class

AirPlane plane1 = new AirPlane("Airbus", "A-380");

AirPlane plane2 = new AirPlane();

// Accessing class members from plane1 object

Console.WriteLine(plane1.planeMake);

Console.WriteLine(plane1.planeModel);

// Accessing class members from plane2 object

Console.WriteLine(plane2.planeMake);

Console.WriteLine(plane2.planeModel);

Console.ReadKey();

}

}

class AirPlane

{

public string planeMake;

public string planeModel;

public AirPlane(string make, string model)

{

planeMake = make;

planeModel = model;

}

public AirPlane()

{

planeMake = "Lockhead Martin";

planeModel = "F-16";

}

public void StartPlane()

{

Console.WriteLine("Plane Started");

}

public void StopPlane()

{

Console.WriteLine("Plane Stopped");

}

}

}

In the script above, we have two constructors in our “AirPlane” class, one of the constructors is parameterized while the other constructor doesn’t accept any parameters.

In the “Main” method, we create two objects of the “AirPlane” class: plane1 and plane2. The former is created using the parameterized constructor while the latter is created using the simple non-parameterized constructor. The output of the script above looks like this:



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.