Generic math (overview), generic attributes (when relevant)
Emulate generic math without modern features: pass an ops-provider or delegates, constrain types carefully, and simulate "generic attributes" via Type parameters.
Generic math (overview), generic attributes (when relevant) is a free C# Academy lesson on CoddyKit. This is lesson 2 of 3. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the C# Academy learning path, and your progress syncs across the web and the CoddyKit app. The C# Academy course includes 3 lessons in total.
Generic math on C# 6
Goal: Write numeric algorithms generically on C# 6.
- No static abstract operators on T
- Workarounds: ops-provider interface or small delegates
- For annotations, use attributes with Type parameters
Ops-provider pattern
Provide Zero and Add via an interface. The generic algorithm calls those methods instead of using + on T.
using System;
using System.Collections.Generic;
public interface INumericOps<T>
{
T Zero { get; }
T Add(T a, T b);
}
public sealed class IntOps : INumericOps<int>
{
public int Zero { get { return 0; } }
public int Add(int a, int b) { return a + b; }
}
public sealed class DoubleOps : INumericOps<double>
{
public double Zero { get { return 0.0; } }
public double Add(double a, double b) { return a + b; }
}
public class Program
{
static T Sum<T>(IEnumerable<T> items, INumericOps<T> ops)
{
T acc = ops.Zero;
foreach (T x in items) acc = ops.Add(acc, x);
return acc;
}
public static void Main(string[] args)
{
int s1 = Sum(new int[] {1,2,3}, new IntOps());
double s2 = Sum(new double[] {1.5, 2.0}, new DoubleOps());
Console.WriteLine("Sum int = " + s1);
Console.WriteLine("Sum double = " + s2);
}
}
Average with helpers
For operations you cannot express generically (like division), pass a small converter or extra delegate.
using System;
using System.Collections.Generic;
public interface INumericOps<T>
{
T Zero { get; }
T Add(T a, T b);
}
public sealed class DoubleOps : INumericOps<double>
{
public double Zero { get { return 0.0; } }
public double Add(double a, double b) { return a + b; }
}
public class Program
{
static double Average<T>(IEnumerable<T> items, INumericOps<T> ops, Func<T,double> toDouble)
{
T acc = ops.Zero;
int count = 0;
foreach (T x in items) { acc = ops.Add(acc, x); count++; }
if (count == 0) throw new ArgumentException("Empty sequence", "items");
// convert with a delegate for division
return toDouble(acc) / count;
}
public static void Main(string[] args)
{
double avg = Average<double>(new double[] {2.0, 4.0, 6.0}, new DoubleOps(), delegate(double d) { return d; });
Console.WriteLine("Avg = " + avg);
}
}
Delegate-based fold
Delegates keep it minimal: pass a seed and a combine function. Good for tiny utilities.
using System;
public class Program
{
static T Fold<T>(T[] xs, T seed, Func<T,T,T> combine)
{
T acc = seed;
for (int i = 0; i < xs.Length; i++) acc = combine(acc, xs[i]);
return acc;
}
public static void Main(string[] args)
{
int sum = Fold<int>(new int[] {1,2,3}, 0, delegate(int a, int b) { return a + b; });
double sumD = Fold<double>(new double[] {1.5, 2.5}, 0.0, delegate(double a, double b) { return a + b; });
Console.WriteLine("Sum ints = " + sum);
Console.WriteLine("Sum doubles = " + sumD);
}
}
Attribute workaround
No true generic attributes in C# 6. Pass a Type to the attribute to indicate the related generic type.
using System;
using System.Reflection;
// C# 6 cannot declare generic attributes. Workaround: pass a Type.
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public sealed class ValidatorForAttribute : Attribute
{
public Type TargetType { get; private set; }
public ValidatorForAttribute(Type targetType) { TargetType = targetType; }
}
public sealed class Customer { public string Name; }
[ValidatorFor(typeof(Customer))]
public sealed class CustomerValidator
{
public bool IsValid(Customer c) { return c != null && !string.IsNullOrEmpty(c.Name); }
}
public class Program
{
public static void Main(string[] args)
{
Type t = typeof(CustomerValidator);
object[] attrs = t.GetCustomAttributes(typeof(ValidatorForAttribute), false);
if (attrs.Length > 0)
{
ValidatorForAttribute a = (ValidatorForAttribute)attrs[0];
Console.WriteLine("Validator targets: " + a.TargetType.Name);
}
}
}
Tips & choices
Tips:
- Prefer an ops-provider for reusable numeric algorithms.
- Use delegates for tiny helpers (combine, convert).
- For annotations, pass Type in attributes and read via reflection.
Generic math workaround
Recap
Recap: Without modern generic math, pass ops or delegates to your algorithms. For annotations, use attributes that carry a Type and read it via reflection.
Learn C# with an AI tutor — free
Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.
- Courses
- 93
- Lessons
- 346
Frequently Asked Questions
Is the “Generic math (overview), generic attributes (when relevant)” lesson free?
Yes — the full text of “Generic math (overview), generic attributes (when relevant)” is free to read here on the web. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the C# Academy course, upgrade to CoddyKit PRO. The C# Academy course includes 3 lessons in total.
What will I learn in “Generic math (overview), generic attributes (when relevant)”?
Emulate generic math without modern features: pass an ops-provider or delegates, constrain types carefully, and simulate "generic attributes" via Type parameters. You practise C# Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start C# Academy?
No prior experience is required. C# Academy on CoddyKit is structured for beginners through advanced learners, so you can start here or from the beginning and move at your own pace. This is lesson 2 of 3.
How long does the “Generic math (overview), generic attributes (when relevant)” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this C# Academy lesson?
Yes. Every C# Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- unmanaged, notnull, new() (C# 6 emulation)
- Generic math (overview), generic attributes (when relevant)
- Reusable generic utilities