How to use readonly vs const vs static in C#

In C#, readonly, const, and static are keywords used to define variables with different behaviors in terms of mutability, memory allocation, and scope.

Understanding their differences is crucial for writing efficient and maintainable code. In this article we'll take a look at each and see how they are used.

1. const (Constant Values)

A const variable is a compile-time constant, meaning its value must be assigned at declaration and cannot be changed later.

Key Characteristics:

  • Must be assigned at declaration.
  • Stored in the assembly metadata (not allocated memory at runtime).
  • Can only be assigned primitive types, string, or enum values.
  • Cannot be modified after compilation.

Example:

public class MathConstants
{
    public const double Pi = 3.14159;
}

// Usage:
Console.WriteLine(MathConstants.Pi); // Output: 3.14159

Limitations:

  • Since const values are replaced at compile-time, updating a const in a library requires recompiling all dependent projects.
  • Cannot use non-primitive types (e.g., objects, lists).

2. readonly (Runtime Immutable Fields)

A readonly field allows initialization either at declaration or in the constructor but cannot be modified afterward.

Key Characteristics:

  • Can be assigned at declaration or inside a constructor.
  • Its value can change during runtime (but only in the constructor).
  • Works with all data types, including objects.
  • More flexible than const since values are resolved at runtime.

Example:

public class Circle
{
    public readonly double Radius;
    public readonly double Pi = 3.14159;

    public Circle(double radius)
    {
        Radius = radius; // Allowed because it's inside the constructor.
    }
}

// Usage:
Circle c = new Circle(5);
Console.WriteLine(c.Radius); // Output: 5

Best for: Values that should remain constant per instance but need to be assigned dynamically at runtime.


3. static (Shared Across All Instances)

A static variable belongs to the type itself rather than to any instance of the class.

Key Characteristics:

  • Shared across all instances of a class.
  • Cannot be used with instance constructors.
  • Initialized once and persists for the application’s lifetime.
  • Can be combined with readonly or const.

Example:

public class GlobalConfig
{
    public static string ApplicationName = "MyApp";
    public static readonly DateTime StartTime = DateTime.Now;
}

// Usage:
Console.WriteLine(GlobalConfig.ApplicationName); // Output: MyApp

Best for: Global state, caching, configuration values, and utility methods.


Key Differences Summary

Feature const readonly static
Mutability Immutable Immutable (after construction) Mutable
When Set Compile-time Runtime (constructor) Runtime
Memory Usage Stored in metadata Instance-based Type-based (shared)
Can Use Objects? ❌ No ✅ Yes ✅ Yes
Can Change After Initialization? ❌ No ❌ No (after constructor) ✅ Yes

Choosing the Right One:

  • Use const for fixed, compile-time values that will never change.
  • Use readonly for immutable values that need runtime initialization.
  • Use static for class-level data shared across all instances.

Understanding these differences helps you write cleaner, more efficient C# code. Happy coding! 🚀

0
77

Related

When working with SQL Server, you may often need to count the number of unique values in a specific column. This is useful for analyzing data, detecting duplicates, and understanding dataset distributions.

Using COUNT(DISTINCT column_name)

To count the number of unique values in a column, SQL Server provides the COUNT(DISTINCT column_name) function. Here’s a simple example:

SELECT COUNT(DISTINCT column_name) AS distinct_count
FROM table_name;

This query will return the number of unique values in column_name.

Counting Distinct Values Across Multiple Columns

If you need to count distinct combinations of multiple columns, you can use a subquery:

SELECT COUNT(*) AS distinct_count
FROM (SELECT DISTINCT column1, column2 FROM table_name) AS subquery;

This approach ensures that only unique pairs of column1 and column2 are counted.

Why Use COUNT DISTINCT?

  • Helps in identifying unique entries in a dataset.
  • Useful for reporting and analytics.
  • Efficient way to check for duplicates.

By leveraging COUNT(DISTINCT column_name), you can efficiently analyze your database and extract meaningful insights. Happy querying!

0
110

When working with large files, reading the entire file at once may be inefficient or unnecessary, especially when you only need the first few lines.

In C#, you can easily read just the first N lines of a file, improving performance and resource management.

Why Read Only the First N Lines?

Reading only the first few lines of a file can be beneficial for:

  • Quickly checking file contents or formats.
  • Processing large files without consuming excessive memory.
  • Displaying previews or samples of file content.

Reading the First N Lines with StreamReader

Here's a simple and efficient method using C#:

using System;
using System.IO;

class FileReader
{
    /// <summary>
    /// Reads the first N lines from a file.
    /// </summary>
    /// <param name="filePath">The path to the file.</param>
    /// <param name="numberOfLines">Number of lines to read.</param>
    /// <returns>Array of strings containing the lines read.</returns>
    public static string[] ReadFirstNLines(string filePath, int numberOfLines)
    {
        List<string> lines = new List<string>();

        using (StreamReader reader = new StreamReader(filePath))
        {
            string line;
            int counter = 0;

            // Read lines until the counter reaches numberOfLines or EOF
            while (counter < numberOfLines && (line = reader.ReadLine()) != null)
            {
                lines.Add(line);
                counter++;
            }
        }

        return lines.ToArray();
    }

Example Usage

Here's a practical example demonstrating the usage of the method above:

string filePath = "C:\\largefile.txt";
int linesToRead = 10;

string[] firstLines = FileReader.ReadFirstNLines(filePath, firstLinesCount);

foreach (string line in firstLines)
{
    Console.WriteLine(line);
}

Efficient and Shorter Alternative with LINQ

For a concise implementation, LINQ can also be used:

using System;
using System.IO;
using System.Linq;

class FileReader
{
    public static IEnumerable<string> ReadFirstNLines(string filePath, int numberOfLines)
    {
        // Take first N lines directly using LINQ
        return File.ReadLines(filePath).Take(numberOfLines);
    }
}

Usage Example with LINQ Method:

string path = "C:\\largeFile.txt";
int n = 10;

var lines = FileReader.ReadFirstNLines(path, n);

foreach (string line in lines)
{
    Console.WriteLine(line);
}

Best Practices

  • Use File.ReadLines instead of File.ReadAllLines for large files, as it does not load the entire file into memory.
  • Always handle exceptions properly to ensure your application remains stable.
  • For large files, avoid methods like ReadAllLines() which can negatively affect performance.

Final Thoughts

By limiting your reading operations to only the first few lines you actually need, you significantly enhance your application's efficiency and resource management.

0
172

Reading a file line by line is useful when handling large files without loading everything into memory at once.

✅ Best Practice: Use File.ReadLines() which is more memory efficient.

Example

foreach (string line in File.ReadLines("file.txt"))
{
    Console.WriteLine(line);
}

Why use ReadLines()?

Reads one line at a time, reducing overall memory usage. Ideal for large files (e.g., logs, CSVs).

Alternative: Use StreamReader (More Control)

For scenarios where you need custom processing while reading the contents of the file:

using (StreamReader reader = new StreamReader("file.txt"))
{
    string? line;
    while ((line = reader.ReadLine()) != null)
    {
        Console.WriteLine(line);
    }
}

Why use StreamReader?

Lets you handle exceptions, encoding, and buffering. Supports custom processing (e.g., search for a keyword while reading).

When to Use ReadAllLines()? If you need all lines at once, use:

string[] lines = File.ReadAllLines("file.txt");

Caution: Loads the entire file into memory—avoid for large files!

3
273