Dynamic ViewState in ASP.Net WebForms – Part 2
In previous post I showed an approach combining DynamicObject with ViewState for accessing ViewState members using dynamic properties instead of string indexes. However that approach had some disadvantages:
- It is tied some a concrete base page class.
- It does not have all the properties/methods of StateBag class
- Mixing ViewState and ViewBag can be confusing for new developers.
In order to overcome these issues I made several changes to the DynamicViewState class.
First of all I changed the constructor to accept a StateBag instance instead of Page class so that the DynamicViewState class does not need to be nested inside base page class. Secondly I added all the interfaces which are implemented by StateBag. This makes it fully compatible with StateBag class so we can simply rename the new property in base page class from ViewBag to ViewState. This way you can leave the old code that uses ViewState and use the new approach for all new code. Here is a sample snippet:
public partial class SamplePage : BasePage
{
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
ViewState.loadCount++;
loadLabel.Text = string.Format("Load count: {0}", ViewState.loadCount);
}
else
{
ViewState["loadCount"] = 0;
loadLabel.Text = "Load count: 0";
}
}
}
Getting started with DynamicViewState
If you would like to use DynamicViewState in your code the simplest way for getting it is using Nuget package available at Dynamic ViewState Nuget package. Once you add the package to your project simply change the base class of your pages to BasePage and that is all you need. Source code is available at github.
Performance Benchmarks
In a comment to previous post Jalpesh Vadgama asked about performance impact. I ran benchmark to compare dynamic implementation with ordinary ViewState usage. As expected dynamic implementation is slower but the difference is quite small:
- Average milliseconds with dynamic: 0.0003
- Average milliseconds without dynamic: 0.00016
As you can see dynamic access is twice slower compared to ordinary ViewState usage.

I’m a backend engineer and software architect with 17+ years of .NET, mostly in banking and fintech: payment and transaction processing, public APIs, and the internal platforms other teams build on. I’ve led teams and a platform unit, and I stay hands-on in the code, increasingly through AI coding agents like Claude Code and Codex.
Alongside that, I build open-source .NET libraries and developer tools with 46M+ NuGet downloads: DuckDB.NET, EntityFramework.Exceptions, EFCore.Visualizer and others. That work sits where .NET meets the database: native interop, Native AOT extensions for DuckDB and PostgreSQL, and tooling that makes query plans easier to debug. I also speak about .NET and databases at conferences like NDC, KCDC and .NET Conf.