Data Structures & Algorithms
This section outlines the data structures and algorithms employed within the generic-math-examples
codebase.
Data Structures
List<T>
: Used to store sequences of elements, providing flexibility for dynamic resizing and element access. Source:Program.cs
- Example:
List<int> ints = new() { 1, 2 };
- Example:
IEnumerable<T>
: Represents a sequence of values that can be iterated over. Source:RomanNumeral.cs
- Example:
public static T SumNoNo(this IEnumerable source) { T sum = default; foreach (T v in source) { sum += v; } return sum; }
- Example:
Algorithms
Sum<T>
: Calculates the sum of a sequence of values that implement theINumber
interface. Source:Program.cs
- Example:
static T Sum(IEnumerable values) where T : INumber { T result = T.Zero; foreach (var value in values) { T number = T.Create(value); result += number; } return result; }
- Example:
InvariantParse<T>
: Parses a string into a specified type using invariant culture. Source:Program.cs
- Example:
void Blah() { var name = InvariantParse("Fred"); var number = InvariantParse("42"); Console.WriteLine(name); Console.WriteLine(number); }
- Example:
Create<T>
: Creates a new instance of a typeT
from a specified value. Source:Program.cs
- Example:
Numeral.Create('0');
- Example:
Usage Examples
- Summing Integers:
Console.WriteLine(Sum(ints));
- Summing Roman Numerals:
Console.WriteLine(Sum(numerals));
- Summing Decimals:
Console.WriteLine(Sum(decimals));
Key Principles
- Generics: The codebase extensively utilizes generics to achieve type safety and code reusability.
- Interfaces: Interfaces like
INumber
define contracts for specific functionalities, enabling polymorphism and flexible data handling. - Extensions Methods: The
SumNoNo
extension method demonstrates the use of extensions to add functionality to existing types.
Top-Level Directory Explanations
obj/ - Temporary directory that stores compiled intermediate files during the build process.
obj/Debug/ - Temporary directory for debug versions of the compiled intermediate files.
obj/Debug/net6.0/ - Temporary directory for debug versions of the compiled intermediate files for .NET 6.0.