search

The following article provides an outline for Composition C#. There are two types of relationships in between classes in C#. The first type of relationship is called “is a relationship,” and it uses an inheritance mechanism. The second kind of relationship is the relationship between two classes, and it has two subtypes. The first type is called “has a relationship.”

In this type of relationship, one or greater than one object of a different class is declared in the related class. Here come two more divisions, which are aggregation and composition. In aggregation, the nested objects can independently exist in the class without being an integral part of the class. On the other hand, in composition, the nested objects or a singular nested object supplements the class, which makes the class inconceivable without their or its existence.

Syntax of Composition in C#

Given below is the syntax mentioned:

class Training
{
// class body
}
public class Course
{
Project project = new Project();
// body
}

Working of Composition in C#

  • Composition in C# is a way of creating a relationship between two classes that one or greater than one nested objects are a part of the related class, and the logical existence of class becomes impossible without the nested objects.
  • For example, if we consider a class called Car, then it should have one instance of class “Engine.” Moreover, it should also have four other instances of the class “Wheel.”
  • Now, if we eliminate any of these instances, then the Car won’t function.

Examples of Composition C#

Given below are the examples of Composition C#:

Example #1

If the training class is considered, which is describing two courses. Now, the courses are being used for describing the course class. Therefore, the training class cannot exist without the two-course instances as both of these instances are part of the course class. Moreover, both of these instances of the course class are also a part of the training class.

Code:

using System;
using static System.Console;
namespace EDUCBA
{
class Course
{
public double M;
public double A;
}
class Training
{
public Course course1 = null;
public Course course2 = null;
}
class Career
{
public Course[] courses;
public Training[] trainings;
public Career()
{
courses = null;
trainings = null;
}
public void Print()
{
WriteLine(" Courses Data is represented below:");
for (int b = 1; b
<p><strong>Output:</strong></p>
<p><img  src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/172534707960531.jpg?x-oss-process=image/resize,p_40" class="lazy" alt="Composition C#" ></p>
<h4 id="Example">Example #2</h4>
<p>In this example, both of the classes created are regular classes; however, the course class is using an instance from the project class inside it. This is the same way in which one function is called inside another. Using inheritance, we can have access to each and everything from the Project class. However, using composition, only the code specified by us can be accessed. Here, we can access the Project class indirectly.</p>
<p><strong>Code:</strong></p>
<pre class="brush:php;toolbar:false">using System;
namespace EDUCBA
{
class Training
{
static void Main(string[] args)
{
Course courses = new Course();
courses.Bought();
Console.ReadLine();
}
}
public class Project
{
public void Log(string aboutus)
{
Console.WriteLine(aboutus);
}
}
public class Course
{
Project project = new Project();
public void Bought()
{
project.Log("\n If you want to upskill your career. \n If you want to do something out of the box. \n If you have passion to explore new advanced technologies. \n If you want to be best. \n We at EDUCBA are here to help. \n Feel free to reach us on +91-8800880140 / +91-7738666252. \n Visit our website www.educba.com to know more......");
}
}
}

Output:

Composition C#

Example #3

In this example, the structure of the composite design is explained. It helps in understanding the classes used for composition and the roles of those classes. Moreover, it also explains how the elements of the pattern are related to each other.

Code:

using System;
using System.Collections.Generic;
namespace EDUCBA
{
abstract class Training
{
public Training() { }
public abstract string Project();
public virtual void Add(Training training)
{
throw new NotImplementedException();
}
public virtual void Remove(Training training)
{
throw new NotImplementedException();
}
public virtual bool IsCourse()
{
return true;
}
}
class DataScience : Training
{
public override string Project()
{
return "DataScience";
}
public override bool IsCourse()
{
return false;
}
}
class Course : Training
{
protected List<training> _children = new List<training>();
public override void Add(Training training)
{
this._children.Add(training);
}
public override void Remove(Training training)
{
this._children.Remove(training);
}
public override string Project()
{
int m = 1;
string result = "Dream Career(";
foreach (Training training in this._children)
{
result += training.Project();
if (m != this._children.Count + 2)
{
result += "-";
}
m--;
}
return result + ")";
}
}
class Input
{
public void InputCode(Training data_analysis)
{
Console.WriteLine($"OUTPUT: \n {data_analysis.Project()}\n");
}
public void InputCode2(Training training1, Training training2)
{
if (training1.IsCourse())
{
training1.Add(training2);
}
Console.WriteLine($"OUTPUT: \n {training1.Project()}");
}
}
class Program
{
static void Main(string[] args)
{
Input client = new Input();
DataScience data_analysis = new DataScience();
Console.WriteLine("INPUT: \n Best Course to Upgrade Career:");
client.InputCode(data_analysis);
Course vr = new Course();
Course career1 = new Course();
career1.Add(new DataScience());
career1.Add(new DataScience());
Course career2 = new Course();
career2.Add(new DataScience());
vr.Add(career1);
vr.Add(career2);
Console.WriteLine("\nINPUT: \n Trendy Dream Career Right Now:");
client.InputCode(vr);
Console.Write("\nINPUT: Lets Upgrade and start your dream career jouney: \n");
client.InputCode2(vr, data_analysis);
}
}
}</training></training>

Output:

Composition C#

Conclusion

On the basis of the above article, we understood the concept of composition in C#. We went through multiple examples for understanding the application of composition in C# coding.

The above is the detailed content of Composition C#. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
C# and the .NET Runtime: How They Work TogetherC# and the .NET Runtime: How They Work TogetherApr 19, 2025 am 12:04 AM

C# and .NET runtime work closely together to empower developers to efficient, powerful and cross-platform development capabilities. 1) C# is a type-safe and object-oriented programming language designed to integrate seamlessly with the .NET framework. 2) The .NET runtime manages the execution of C# code, provides garbage collection, type safety and other services, and ensures efficient and cross-platform operation.

C# .NET Development: A Beginner's Guide to Getting StartedC# .NET Development: A Beginner's Guide to Getting StartedApr 18, 2025 am 12:17 AM

To start C#.NET development, you need to: 1. Understand the basic knowledge of C# and the core concepts of the .NET framework; 2. Master the basic concepts of variables, data types, control structures, functions and classes; 3. Learn advanced features of C#, such as LINQ and asynchronous programming; 4. Be familiar with debugging techniques and performance optimization methods for common errors. With these steps, you can gradually penetrate the world of C#.NET and write efficient applications.

C# and .NET: Understanding the Relationship Between the TwoC# and .NET: Understanding the Relationship Between the TwoApr 17, 2025 am 12:07 AM

The relationship between C# and .NET is inseparable, but they are not the same thing. C# is a programming language, while .NET is a development platform. C# is used to write code, compile into .NET's intermediate language (IL), and executed by the .NET runtime (CLR).

The Continued Relevance of C# .NET: A Look at Current UsageThe Continued Relevance of C# .NET: A Look at Current UsageApr 16, 2025 am 12:07 AM

C#.NET is still important because it provides powerful tools and libraries that support multiple application development. 1) C# combines .NET framework to make development efficient and convenient. 2) C#'s type safety and garbage collection mechanism enhance its advantages. 3) .NET provides a cross-platform running environment and rich APIs, improving development flexibility.

From Web to Desktop: The Versatility of C# .NETFrom Web to Desktop: The Versatility of C# .NETApr 15, 2025 am 12:07 AM

C#.NETisversatileforbothwebanddesktopdevelopment.1)Forweb,useASP.NETfordynamicapplications.2)Fordesktop,employWindowsFormsorWPFforrichinterfaces.3)UseXamarinforcross-platformdevelopment,enablingcodesharingacrossWindows,macOS,Linux,andmobiledevices.

C# .NET and the Future: Adapting to New TechnologiesC# .NET and the Future: Adapting to New TechnologiesApr 14, 2025 am 12:06 AM

C# and .NET adapt to the needs of emerging technologies through continuous updates and optimizations. 1) C# 9.0 and .NET5 introduce record type and performance optimization. 2) .NETCore enhances cloud native and containerized support. 3) ASP.NETCore integrates with modern web technologies. 4) ML.NET supports machine learning and artificial intelligence. 5) Asynchronous programming and best practices improve performance.

Is C# .NET Right for You? Evaluating its ApplicabilityIs C# .NET Right for You? Evaluating its ApplicabilityApr 13, 2025 am 12:03 AM

C#.NETissuitableforenterprise-levelapplicationswithintheMicrosoftecosystemduetoitsstrongtyping,richlibraries,androbustperformance.However,itmaynotbeidealforcross-platformdevelopmentorwhenrawspeediscritical,wherelanguageslikeRustorGomightbepreferable.

C# Code within .NET: Exploring the Programming ProcessC# Code within .NET: Exploring the Programming ProcessApr 12, 2025 am 12:02 AM

The programming process of C# in .NET includes the following steps: 1) writing C# code, 2) compiling into an intermediate language (IL), and 3) executing by the .NET runtime (CLR). The advantages of C# in .NET are its modern syntax, powerful type system and tight integration with the .NET framework, suitable for various development scenarios from desktop applications to web services.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)