Chapter 21: Razor – C# Variables

Razor – C# Variables — that is, how you declare, use, and work with variables inside .cshtml Razor files when using C#.

This is one of the first things every Razor beginner must master, because almost every dynamic page starts with variables: names, prices, dates, lists, user data, flags, calculations, etc.

I’m going to explain it like we’re sitting together at a table in Charminar area, writing code on paper, running it mentally, and debugging together — very slowly, with lots of real examples.

1. The Golden Rule of Variables in Razor (Write this down!)

In Razor .cshtml files using C#:

  • Variables are declared and used exactly the same way as in normal C# — same rules, same types, same scope rules.
  • The only difference is where you place them:
    • Inside @{ … } code blocks → normal C# variables (most common)
    • Inline with @ → you can use them directly in HTML output

There is no special “Razor variable type” — they are pure C# variables.

2. Three Main Places Where You Meet Variables in Razor

Place 1 – Code Blocks at the Top (Most Common)

HTML

→ Rules inside @{ … }:

  • Use var (implicit typing — most popular) or explicit types (string, int, decimal, etc.)
  • End statements with ;
  • Case-sensitive (city ≠ City)
  • Normal C# scope: variables declared here are available below in the same file (and in layouts/sections if passed via Page or ViewData)

Place 2 – Inline Expressions with @

Once declared, you can use variables anywhere in HTML with just @:

HTML

→ @variableName → Razor evaluates it and prints .ToString() result → @(expression) → use parentheses when it’s a calculation or complex expression

Place 3 – Sharing Variables with Layout / Partial Views

HTML

→ Page is a dynamic object — you can add any property you want (Page.anything = value;)

3. Common Variable Types & How They Look in Razor

Type Declaration Example Output Example Notes / Gotchas
string var name = “Rahul”; @name → Rahul Most common
int var age = 25; @age → 25 Use AsInt() when reading from form
decimal var price = 499.99m; @price.ToString(“C”) → ₹499.99 m suffix for literal
bool var isLoggedIn = true; @(isLoggedIn ? “Yes” : “No”) Ternary is very common
DateTime var now = DateTime.Now; @now.ToString(“dd-MMM-yyyy”) Formatting is important
List<T> var items = new List<string> { “A”, “B” }; @foreach (var i in items) { … } Most used collection
var (implicit) var data = db.Query(…); @data.Count() Razor loves var

4. Full Realistic Example – Mini Product Card Page

HTML

→ Every line shows variables being:

  • Declared (var …)
  • Calculated (discountedPrice = …)
  • Formatted (.ToString(“N2”), .ToString(“C”))
  • Used in conditions (@if (isInStock))
  • Looped (@foreach)
  • Printed (@productName, @discountedPrice, etc.)

5. Teacher Tips & Common Beginner Mistakes

  • Always declare variables before using them in HTML (top-to-bottom execution)
  • Use var most of the time — cleaner and Razor-friendly
  • For money → always use decimal (not double — floating point issues)
  • When reading from forms: int qty = Request[“qty”].AsInt(0); — never trust Convert.ToInt32()
  • Scope: variables in @{ } at top are available everywhere below in the same file
  • Avoid very long code blocks — keep logic clean, move complex code to PageModel (in modern Razor Pages)

Summary – Blackboard Close

ASP.NET Razor – C# Variables means:

  • Declare them exactly like normal C# (var x = value;, string name = “Hyderabad”;, int count = 42;)
  • Use @{ … } blocks at the top of the file for logic & declarations
  • Print/use them anywhere in HTML with simple @variable or @(expression)
  • Share between page & layout using Page.variableName = value;
  • Razor treats them as normal C# variables — no special magic type

Now you can create, calculate, format, loop, and display any data you want!

Next step?

  • Want to see how variables work with forms (reading from Request)?
  • Or variables in loops & conditions with more examples?
  • Or move to @model and strongly-typed variables in Razor Pages?

Just tell me — you’re doing great! Keep coding strong from Hyderabad! 🚀🇮🇳

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *