Skip to main content

What is the purpose of the volatile keyword?

Mid C#
Quick Answer volatile tells the compiler and CPU not to cache a variable รขโ‚ฌโ€ always read it fresh from memory. Without it, the CPU might cache a value in a register and miss updates from another thread. Use for simple shared flags. For anything complex, use lock or Interlocked instead.

Answer

The volatile keyword tells the compiler that a variable may be modified by multiple threads.

It prevents certain optimizations and ensures every read returns the most recent value.

S
SugharaIQ Editorial Team Verified Answer

This answer has been peer-reviewed by industry experts holding senior engineering roles to ensure technical accuracy and relevance for modern interview standards.

Want to bookmark, take notes, or join discussions?

Sign in to access all features and personalize your learning experience.

Sign In Create Account

Source: SugharaIQ

Ready to level up? Start Practice