Top 15 Underutilized Features of .NET Part 2

Top 15 Underutilized Features of .NET Part 2

In this article, I’m going to share with you even more underutilized features of C# language (underutilized). If you missed the first publication you should check it- Top 15 Underutilized Features of .NET

After so many comments about the previous title of the article -  “Top 15 Hidden Features of C#”, I decided to change it to the current one. Thank you all for the suggestions. My initial intent was not to mislead you. The original idea about the article came up from a Stack Overflow discussion with a similar title, so I decided not to change it because people were already familiar with the topic. But for the sake of all past and future critics I am changing the title.

You could share your most preferred but not so well known parts of .NET in the comments. I will include them in the future next part of the series. Also, you can vote in the poll that can be found at the end of the article for your most favorite “underutilized/oft-forgotten/arcane/hidden” feature of C#.

Underutilized Features of .NET

1. dynamic Type

The dynamic type enables the operations in which it occurs to bypass compile-time type checking. Instead, these operations are resolved at run-time.

Note: Type dynamic behaves like type object in most circumstances. However, operations that contain expressions of type dynamic are not resolved or type checked by the compiler. The compiler packages together information about the process, and that information is later used to evaluate the operation at run-time. As part of the process, variables of type dynamic are compiled into variables of type object. Therefore, type dynamic exists only at compile-time, not at run-time.

dynamic dynamicVariable;
int i = 20;
dynamicVariable = (dynamic)i;
Console.WriteLine(dynamicVariable);

string stringVariable = "Example string.";
dynamicVariable = (dynamic)stringVariable;
Console.WriteLine(dynamicVariable);

DateTime dateTimeVariable = DateTime.Today;
dynamicVariable = (dynamic)dateTimeVariable;
Console.WriteLine(dynamicVariable);

// The expression returns true unless dynamicVariable has the value null.
if (dynamicVariable is dynamic)
{
    Console.WriteLine("d variable is dynamic");
}

// dynamic and the as operator.
dynamicVariable = i as dynamic;

// throw RuntimeBinderException if the associated object doesn't have the specified method.
// The code is still compiling successfully.
Console.WriteLine(dynamicVariable.ToNow1);

As you can see from the examples, you can assign variables from different types to a single dynamic object. You can check if a variable is of type dynamic using the ‘is’ operator. If a requested property is non-existing as on the last line of the example, a new RuntimeBinderException is thrown.

2. ExpandoObject

Represents an object whose members can be dynamically added and removed at run-time. This is one of my favorite underutilized features of .NET framework.

dynamic samplefootballLegendObject = new ExpandoObject();

samplefootballLegendObject.FirstName = "Joro";
samplefootballLegendObject.LastName = "Beckham-a";
samplefootballLegendObject.Team = "Loko Mezdra";
samplefootballLegendObject.Salary = 380.5m;
samplefootballLegendObject.AsString = new Action(
            () =>
            Console.WriteLine("{0} {1} {2} {3}",
            samplefootballLegendObject.FirstName,
            samplefootballLegendObject.LastName,
            samplefootballLegendObject.Team,
            samplefootballLegendObject.Salary)
            );

You can not only add properties to the expando objects, but you can also add methods and delegates. In the example, I have added new AsString method through a new Action.

3. Nullable.GetValueOrDefault Method

float? yourSingle = –1.0f;
Console.WriteLine(yourSingle.GetValueOrDefault());
yourSingle = null;
Console.WriteLine(yourSingle.GetValueOrDefault());
// assign different default value
Console.WriteLine(yourSingle.GetValueOrDefault(–2.4f));
// returns the same result as the above statement
Console.WriteLine(yourSingle ?? –2.4f);

Retrieves the value of the current Nullable object, or the object’s default value. It is faster than ?? operator.

If you don’t specify a default value as a parameter to the method, the default value of the used type is going to be used.

You can use it to create a dictionary safe Get method (return the default value if the key is not present instead of throwing an exception).

public static class DictionaryExtensions
{
    public static TValue GetValueOrDefault<TKey, TValue>(this Dictionary<TKey, TValue> dic, TKey key)
    {
        TValue result;
        return dic.TryGetValue(key, out result) ? result : default(TValue);
    }
}

The usage is straightforward.

Dictionary<int, string> names = new Dictionary<int, string>();
names.Add(0, "Willy");
Console.WriteLine(names.GetValueOrDefault(1));

4. ZipFile in .NET

Provides static methods for creating, extracting, and opening zip archives.

string startPath = Path.Combine(string.Concat(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "\\Start"));
string resultPath = Path.Combine(string.Concat(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "\\Result"));
Directory.CreateDirectory(startPath);
Directory.CreateDirectory(resultPath);
string zipPath = Path.Combine(string.Concat(resultPath, "\\", Guid.NewGuid().ToString(), ".zip"));
string extractPath = Path.Combine(string.Concat(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "\\Extract"));
Directory.CreateDirectory(extractPath);

ZipFile.CreateFromDirectory(startPath, zipPath);

ZipFile.ExtractToDirectory(zipPath, extractPath);

5. C# Preprocessor Directives

5.1. #warning

#warning lets you generate a level one warning from a specific location in your code.

#if LIVE
#warning A day without sunshine is like, you know, night.
#endif

5.2. #error

#error allows you to make an error from a particular location in your program.

#error Deprecated code in this method.

5.3. #line

#line lets you modify the compiler’s line number and (optionally) the file name output for errors and warnings.

#line 100 "Pandiculation"
int i;    // CS0168 on line 101
int j;    // CS0168 on line 102
#line default
char c;   // CS0168 on line 288
float f;  // CS0168 on line 289

5.4. #region

#region enables you to specify a block of code that you can expand or collapse when using the outlining feature of the Visual Studio Code Editor.

#region Thomas Sowell Quote
Console.WriteLine("It takes considerable knowledge just to realize the extent of your own ignorance.");
#endregion

6.  Stackalloc

The stackalloc keyword is used in an unsafe code context to allocate a block of memory on the stack.

The following example calculates and displays the first 20 numbers in the Fibonacci sequence. Each number is the sum of the previous two numbers. In the code, a block of memory of sufficient size to contain 20 elements of type int is allocated on the stack, not the heap. The address of the block is stored in the pointer fib. This memory is not subject to garbage collection. Therefore, it does not have to be pinned (by using fixed). The lifetime of the memory block is limited to the life of the method that defines it. You cannot free the memory before the method returns.

static unsafe void Fibonacci()
{
    const int arraySize = 20;
    int* fib = stackalloc int;
    int* p = fib;
    *p++ = *p++ = 1;
    for (int i = 2; i < arraySize; ++i, ++p)
    {
        *p = p[–1] + p[–2];
    }
    for (int i = 0; i < arraySize; ++i)
    {
        Console.WriteLine(fib);
    }
}

The sole reason to use stackalloc is performance (either for computations or interop). By using stackalloc instead of a heap allocated array, you create less GC pressure (the GC needs to run less). You don’t need to pin the arrays down, it’s faster to allocate than a heap array.

To set this compiler option in the Visual Studio development environment

  1. Open the project’s Properties page.
  2. Click the Build property page.
  3. Select the Allow Unsafe Code check box.

7. Execute VB code via C#

Generates and calls Office Visual Basic macros from a C# .NET Automation client.

I used it in the past to fetch and display data from popular internet Analytics in Excel.

private static string GetMacro(int macroId, int row, int endCol)
{
    StringBuilder sb = new StringBuilder();
    string range = "ActiveSheet.Range(Cells(" + row + "," + 3 +
        "), Cells(" + row + "," + (endCol + 3) + ")).Select";
    sb.AppendLine("Sub Macro" + macroId + "()");
    sb.AppendLine("On Error Resume Next");
    sb.AppendLine(range);
    sb.AppendLine("ActiveSheet.Shapes.AddChart.Select");
    sb.AppendLine("ActiveChart.ChartType = xlLine");
    sb.AppendLine("ActiveChart.SetSourceData Source:=" + range);
    sb.AppendLine("On Error GoTo 0");
    sb.AppendLine("End Sub");

    return sb.ToString();
}

private static void AddChartButton(MSExcel.Workbook workBook, MSExcel.Worksheet xlWorkSheetNew,
    MSExcel.Range currentRange, int macroId, int currentRow, int endCol, string buttonImagePath)
{
    MSExcel.Range cell = currentRange.Next;
    var width = cell.Width;
    var height = 15;
    var left = cell.Left;
    var top = Math.Max(cell.Top + cell.Height – height, 0);
    MSExcel.Shape button = xlWorkSheetNew.Shapes.AddPicture(@buttonImagePath, MsoTriState.msoFalse,
        MsoTriState.msoCTrue, left, top, width, height);

    VBIDE.VBComponent module = workBook.VBProject.VBComponents.Add(VBIDE.vbext_ComponentType.vbext_ct_StdModule);
    module.CodeModule.AddFromString(GetMacro(macroId, currentRow, endCol));
    button.OnAction = "Macro" + macroId;

}

8. volatile

The volatile keyword indicates that a field might be modified by multiple threads that are executing at the same time. Fields that are declared volatile are not subject to compiler optimizations that assume access by a single thread. This ensures that the most up-to-date value is present in the field at all times.

volatile bool shouldPartyContinue = true;

public static unsafe void Main(string[] args)
{
    Program firstDimension = new Program();
    Thread secondDimension = new Thread(firstDimension.StartPartyInAnotherDimension);
    secondDimension.Start(firstDimension);
    Thread.Sleep(5000);
    firstDimension.shouldPartyContinue = false;
    Console.WriteLine("Party Grand Finish");
}

private void StartPartyInAnotherDimension(object input)
{
    Program currentDimensionInput = (Program)input;
    Console.WriteLine("let the party begin");
    while (currentDimensionInput.shouldPartyContinue)
    {
    }
    Console.WriteLine("Party ends :(");
}

If the variable shouldPartyContinue is not marked as volatile, the program will never finish if it is executed in Release.

9. global::

The ability to access a member of the global namespace is useful when the member might be hidden by another entity of the same name. This is one of my favored underutilized features of .NET.

public static unsafe void Main(string[] args)
{
    global::System.Console.WriteLine("Wine is constant proof that God loves us and loves to see us happy. -Benjamin Franklin");
}

public class System { }

// Define a constant called 'Console' to cause more problems.
const int Console = 7;
const int number = 66;

10. DebuggerDisplayAttribute

Determines how a class or field is displayed in the debugger variable windows.

[DebuggerDisplay("{DebuggerDisplay}")]
public class DebuggerDisplayTest
{
    private string squirrelFirstNameName;
    private string squirrelLastNameName;

    public string SquirrelFirstNameName
    {
        get
        {
            return squirrelFirstNameName;
        }
        set
        {
            squirrelFirstNameName = value;
        }
    }

    [DebuggerBrowsable(DebuggerBrowsableState.Collapsed)]
    public string SquirrelLastNameName
    {
        get
        {
            return squirrelLastNameName;
        }
        set
        {
            squirrelLastNameName = value;
        }
    }

    public int Age { get; set; }

    private string DebuggerDisplay
    {
        get { return string.Format("{0} de {1}", SquirrelFirstNameName, SquirrelLastNameName); }
    }
}

In the above example, the method DebuggerDisplay will be used to calculate the value that is going to be presented in the Debugger window.

Also, you can use different C# expressions directly in the attribute.

[DebuggerDisplay("Age {Age > 0 ? Age : 5}")]
public class DebuggerDisplayTest
{
    private string squirrelFirstNameName;
    private string squirrelLastNameName;

    public string SquirrelFirstNameName
    {
        get
        {
            return squirrelFirstNameName;
        }
        set
        {
            squirrelFirstNameName = value;
        }
    }

    [DebuggerBrowsable(DebuggerBrowsableState.Collapsed)]
    public string SquirrelLastNameName
    {
        get
        {
            return squirrelLastNameName;
        }
        set
        {
            squirrelLastNameName = value;
        }
    }

    public int Age { get; set; }

    private string DebuggerDisplay
    {
        get { return string.Format("{0} de {1}", SquirrelFirstNameName, SquirrelLastNameName); }
    }
}

If the age property is larger than zero, the actual age is going to be displayed otherwise five is used.

11. DebuggerStepThroughAttribute

Instructs the debugger to step through the code instead of stepping into the code.


public class DebuggerDisplayTest
{
    private string squirrelFirstNameName;
    private string squirrelLastNameName;

    public string SquirrelFirstNameName
    {
        get
        {
            return squirrelFirstNameName;
        }
        set
        {
            squirrelFirstNameName = value;
        }
    }

    [DebuggerBrowsable(DebuggerBrowsableState.Collapsed)]
    public string SquirrelLastNameName
    {
        get
        {
            return squirrelLastNameName;
        }
        set
        {
            squirrelLastNameName = value;
        }
    }

    public int Age { get; set; }

    private string DebuggerDisplay
    {
        get { return string.Format("{0} de {1}", SquirrelFirstNameName, SquirrelLastNameName); }
    }
}

12. Conditional

It makes the execution of a method dependent on a preprocessing identifier. The Conditional attribute is an alias for ConditionalAttribute, and can be applied to a method or an attribute class.

public static unsafe void Main(string[] args)
{
    StartBugsParty();
}

[Conditional("LIVE")]
public static void StartBugsParty()
{
    Console.WriteLine("Let the bugs free. Start the Party.");
}

In order the above code to be executed #define LIVE should be added at the beginning of the C# file.

13. using Directive VS 2015

You can access static members of a type without having to qualify the access to the type name.

First add the following using clauses.

using static System.Math;
using static System.Console;
WriteLine(Sqrt(42563));

A using-alias directive cannot have an open generic type on the right-hand side. For example, you cannot create a using alias for a List, but you can create one for a List.

using IntList = System.Collections.Generic.List<int>;
IntList intList = new IntList();
intList.Add(1);
intList.Add(2);
intList.Add(3);
intList.ForEach(x => WriteLine(x));

Personally I believe that the last feature makes the code a little bit unreadable, so I suggest you to think twice before use it.

14. Flags Enum Attribute

It is also important to note that Flags does not automatically make the enum values powers of two. If you omit the numeric values, the enum will not work as one might expect in bitwise operations because by default the values start with 0 and increment.

When you retrieve the value, you are bitwise AND’ing the values.

Note: You cannot use the None enumerated constant in a bitwise AND operation to test for a flag because the result is always zero. However, you can perform a logical, not a bitwise, comparison between the numeric value and the None enumerated constant to determine whether any bits in the numeric value are set.

15. Dynamically Compile and Execute C# Code

15.1. CodeDOM

The CodeDOM provides types that represent many common types of source code elements. You can design a program that builds a source code model using CodeDOM elements to assemble an object graph. This object graph can be rendered as source code using a CodeDOM code generator for a supported programming language. The CodeDOM can also be used to compile source code into a binary assembly.

15.2. Roslyn

The .NET Compiler Platform (“Roslyn”) provides open-source C# and Visual Basic compilers with rich code analysis APIs. It enables building code analysis tools with the same APIs that are used by Visual Studio.

First you need to install the NuGet package Microsoft.CodeAnalysis.

You can find the whole source code and useful examples in the project’s official GitHub page.

To execute the generated code, you can use the following method.

Related Articles

Development, Resources

Most Complete NUnit Unit Testing Framework Cheat Sheet

An essential part of every UI test framework is the usage of a unit testing framework. One of the most popular ones in the .NET world is NUnit. However, you can

Most Complete NUnit Unit Testing Framework Cheat Sheet

Development

Assert DateTime the Right Way MSTest NUnit C# Code

NUnit has added built-in support for this using the keyword Within.

Assert DateTime the Right Way MSTest NUnit C# Code

Development

Optimize C# Reflection Up to 10 Times by Using Delegates

Developers love reflection because it can save them numerous hours of boilerplate code. But developers also know reflection is slow and it should be used with c

Optimize C# Reflection Up to 10 Times by Using Delegates

Development, Resources

Most Complete MSTest Unit Testing Framework Cheat Sheet

An essential part of every UI test framework is the usage of a unit testing framework. One of the most popular ones in the .NET world is MSTest. However, you ca

Most Complete MSTest Unit Testing Framework Cheat Sheet

Development

Dynamic – A Bad Practice Turned Great

I had just upgraded My Tested ASP.NET to be compatible with version 2.2 of ASP.NET Core, when the server-side technology upgraded to version 3.0. I had to re-do

Dynamic – A Bad Practice Turned Great

Development

Specification-based Test Design Techniques for Enhancing Unit Tests

The primary goal of most developers is usually achieving 100% code coverage if they write any unit tests at all. In this test design how-to article, I am going

Specification-based Test Design Techniques for Enhancing Unit Tests
Anton Angelov

About the author

Anton Angelov is Managing Director, Co-Founder, and Chief Test Automation Architect at Automate The Planet — a boutique consulting firm specializing in AI-augmented test automation strategy, implementation, and enablement. He is the creator of BELLATRIX, a cross-platform framework for web, mobile, desktop, and API testing, and the author of 8 bestselling books on test automation. A speaker at 60+ international conferences and researcher in AI-driven testing and LLM-based automation, he has been recognized as QA of the Decade and Webit Changemaker 2025.