Simple CSV parsing patterns
Parse CSV lines: naive Split for simple files, safe TryParse for numbers, then a small quote-aware splitter for commas inside quotes.
Simple CSV parsing patterns is a free C# Academy lesson on CoddyKit. This is lesson 3 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.
CSV parsing overview
Aim: Parse small CSV reliably.
- Start with simple Split for no-quotes files
- Use TryParse for numbers
- Handle quoted fields with a tiny scanner
Naive split (no quotes)
For no-quote CSV, a simple Split works and is easy to read.
using System;
public class Program
{
public static void Main(string[] args)
{
// Simple: no quotes, commas separate fields
string line = "Apple,10,2.5";
string[] parts = line.Split(','); // naive split
Console.WriteLine("Name = " + parts[0]);
Console.WriteLine("Qty = " + parts[1]);
Console.WriteLine("Price= " + parts[2]);
}
}
Safe numeric parsing
Use Trim and TryParse with a culture (e.g., InvariantCulture) to avoid crashes on bad data.
using System;
using System.Globalization;
public class Program
{
public static void Main(string[] args)
{
string line = "Banana, 7, 1.99";
string[] p = line.Split(',');
string name = p[0].Trim();
int qty;
double price;
bool okQty = Int32.TryParse(p[1].Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out qty);
bool okPrice = Double.TryParse(p[2].Trim(), NumberStyles.Float, CultureInfo.InvariantCulture, out price);
Console.WriteLine("Parsed: " + name + " | ok=" + (okQty && okPrice) + " -> " + qty + " x " + price);
}
}
Why naive split fails
Quoted fields may contain commas; a plain Split will break the field into pieces.
using System;
public class Program
{
public static void Main(string[] args)
{
// Name has a comma inside quotes; naive split breaks it
string line = "\"Orange, Blood\",12,3.40";
string[] parts = line.Split(','); // wrong: splits inside the quoted name
Console.WriteLine("Parts found = " + parts.Length); // 4, not 3
foreach (string s in parts) Console.WriteLine("[" + s + "]");
}
}
Quote-aware split
A small scanner toggles inQuotes and ignores commas inside quotes; it also handles doubled quotes ("").
using System;
using System.Collections.Generic;
using System.Text;
public class Program
{
// Splits a CSV line handling quotes and doubled "" inside quoted fields.
static List<string> SplitCsvLine(string line)
{
List<string> fields = new List<string>();
StringBuilder sb = new StringBuilder();
bool inQuotes = false;
for (int i = 0; i < line.Length; i++)
{
char c = line[i];
if (c == '\"')
{
if (inQuotes && i + 1 < line.Length && line[i + 1] == '\"')
{
// Escaped quote ("") inside a quoted field
sb.Append('\"');
i++; // skip next quote
}
else
{
inQuotes = !inQuotes; // toggle
}
}
else if (c == ',' && !inQuotes)
{
fields.Add(sb.ToString());
sb.Length = 0; // reset
}
else
{
sb.Append(c);
}
}
fields.Add(sb.ToString());
return fields;
}
public static void Main(string[] args)
{
string line = "\"Orange, Blood\",12,\"He said \"\"Hi!\"\"\"";
List<string> parts = SplitCsvLine(line);
Console.WriteLine("Fields = " + parts.Count);
foreach (string f in parts) Console.WriteLine("[" + f + "]");
}
}
From CSV to objects
Combine the splitter with TryParse and minimal cleanup to build typed objects safely.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
public sealed class Product
{
public string Name;
public int Quantity;
public double Price;
}
public class Program
{
static List<string> SplitCsvLine(string line)
{
List<string> fields = new List<string>();
StringBuilder sb = new StringBuilder();
bool inQuotes = false;
for (int i = 0; i < line.Length; i++)
{
char c = line[i];
if (c == '\"')
{
if (inQuotes && i + 1 < line.Length && line[i + 1] == '\"')
{ sb.Append('\"'); i++; }
else { inQuotes = !inQuotes; }
}
else if (c == ',' && !inQuotes)
{ fields.Add(sb.ToString()); sb.Length = 0; }
else
{ sb.Append(c); }
}
fields.Add(sb.ToString());
return fields;
}
static bool TryParseProduct(string line, out Product p)
{
p = null;
List<string> f = SplitCsvLine(line);
if (f.Count < 3) return false;
string name = f[0].Trim().Trim('\"');
int qty;
double price;
bool okQty = Int32.TryParse(f[1].Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out qty);
bool okPrice = Double.TryParse(f[2].Trim(), NumberStyles.Float, CultureInfo.InvariantCulture, out price);
if (!okQty || !okPrice) return false;
p = new Product { Name = name, Quantity = qty, Price = price };
return true;
}
public static void Main(string[] args)
{
string[] lines = new string[]
{
"\"Orange, Blood\",12,3.4",
"Apple,10,2.5",
"\"He said \"\"Hi\"\"\",1,0.0"
};
List<Product> list = new List<Product>();
foreach (string line in lines)
{
Product p;
if (TryParseProduct(line, out p)) list.Add(p);
}
foreach (Product p in list)
{
Console.WriteLine(p.Name + " -> " + p.Quantity + " @ " + p.Price);
}
}
}
Quoted fields rule
Recap
Recap: Use simple Split for no-quote CSV, parse numbers with TryParse, and switch to a quote-aware scanner when fields may contain commas.
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 “Simple CSV parsing patterns” lesson free?
Yes — the full text of “Simple CSV parsing patterns” 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 “Simple CSV parsing patterns”?
Parse CSV lines: naive Split for simple files, safe TryParse for numbers, then a small quote-aware splitter for commas inside quotes. 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 3 of 3.
How long does the “Simple CSV parsing patterns” 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
- System.IO (paths, streams)
- JSON with System.Text.Json (opt-ins, converters)
- Simple CSV parsing patterns