Simple Neural Network Implementation in C#
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn your Machine Learning question into a ready to paste AI prompt, free →
Key Takeaways
- ✓Simple Neural Network runs in O(n*w) time and O(w) space, in C# as in every other language.
- ✓System.Random(seed) gives a deterministic sequence for a fixed seed within a given .NET runtime, and .NET 6 added the process-wide, thread-safe Random.Shared for the common case where a specific seed is not needed.
- ✓Model Layer as a sealed class holding double[] Weights and double[] Biases, and take the Random instance as a constructor parameter rather than newing one internally, exactly so a unit test can inject a fixed-seed Random and assert the exact initial weights.
- ✓The C# trap: The single Random instance threaded through every layer's constructor, the idiom above, must not then be handed to multiple layers being built CONCURRENTLY on separate threads or tasks: System.Random is not thread-safe, and concurrent calls to NextDouble() on the same instance can corrupt its internal state and silently produce wrong or repeated values.
- ✓A Layer designed around IEnumerable<double> for its weights, to 'keep it flexible', forces every element through interface dispatch and, on any code path that stores a weight as object, boxes the double value.
What Simple Neural Network actually is
Simple Neural Network in C#: what you actually reach for
C# implementation
using System;
sealed class Layer
{
public double[] Weights;
public double[] Biases;
public readonly int InSize, OutSize;
public Layer(int inSize, int outSize, Random rng)
{
InSize = inSize; OutSize = outSize;
double scale = Math.Sqrt(2.0 / inSize); // He init
Weights = new double[inSize * outSize];
for (int i = 0; i < Weights.Length; i++) Weights[i] = Gaussian(rng) * scale;
Biases = new double[outSize];
}
static double Gaussian(Random rng)
{
// no Gaussian sampler in the BCL: hand-rolled Box-Muller over NextDouble()
double u = 1.0 - rng.NextDouble();
double v = rng.NextDouble();
return Math.Sqrt(-2.0 * Math.Log(u)) * Math.Cos(2.0 * Math.PI * v);
}
public double[] Forward(ReadOnlySpan<double> input)
{
var output = new double[OutSize];
for (int o = 0; o < OutSize; o++)
{
double sum = Biases[o];
for (int i = 0; i < InSize; i++) sum += input[i] * Weights[o * InSize + i];
output[o] = Math.Max(0, sum); // ReLU
}
return output;
}
}
var rng = new Random(42); // ONE instance, passed to every layer
var layer1 = new Layer(784, 128, rng);
var layer2 = new Layer(128, 10, rng);Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe C#-specific trap
Performance in C#, beyond the O(n*w)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which C# type or library should I use for Simple Neural Network?
System.Random(seed) gives a deterministic sequence for a fixed seed within a given .NET runtime, and .NET 6 added the process-wide, thread-safe Random.Shared for the common case where a specific seed is not needed. There is no Gaussian sampler anywhere in the BCL, so a normal-distributed initializer is hand-rolled Box-Muller over NextDouble(), or, matching the backpropagation page, System.Numerics.Tensors.TensorPrimitives for the bulk elementwise math once the samples exist.
What is the most common C# mistake when implementing Simple Neural Network?
The single Random instance threaded through every layer's constructor, the idiom above, must not then be handed to multiple layers being built CONCURRENTLY on separate threads or tasks: System.Random is not thread-safe, and concurrent calls to NextDouble() on the same instance can corrupt its internal state and silently produce wrong or repeated values. Random.Shared, added in .NET 6, is thread-safe, but it is one single global instance you cannot seed, so parallel-yet-reproducible initialization needs one Random per thread, for example via ThreadLocal<Random>, never Random.Shared and never one instance shared naively across tasks.
How does Simple Neural Network actually perform in C#?
A Layer designed around IEnumerable<double> for its weights, to 'keep it flexible', forces every element through interface dispatch and, on any code path that stores a weight as object, boxes the double value. Keeping weights as double[] or Span<double> throughout, the same idiom the backpropagation page argues for, avoids this entirely and is also a precondition for using TensorPrimitives at all, since those APIs require a contiguous span, not an IEnumerable. Time complexity is O(n*w) and space is O(w).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialWant to try this with a model on your own laptop? Local AI setup guides for Ollama and LM Studio are on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.