System.NotSupportedException
A NotSupportedException is thrown when you call a member that a type does not support. It is not a bug in the type, it is how the type says this operation does not make sense here. The message names the problem, such as Collection is read-only or Stream does not support reading.
Unlike NotImplementedException, which means the code is not written yet, this one is a decision: the operation can never work on that instance.
Minimum version: >= 1.1 >= Core 1.0
Statistics
Common causes
The member exists because of an interface or a base class, but the object cannot do what it asks. These are the usual cases.
Changing a read-only or fixed-size collection
Arrays, ReadOnlyCollection<T> and the immutable collections implement IList<T> and ICollection<T>, but they cannot grow. The Add method is there only because of the interface, and throws.
IList<string> items = new List<string>().AsReadOnly();
items.Add("SKU-1"); // NotSupportedException: Collection is read-only.
Work with a collection you can change, and expose the read-only view to the outside:
var items = new List<string>();
items.Add("SKU-1");
IReadOnlyList<string> view = items.AsReadOnly();
Using a stream for something it cannot do
A stream reports what it can do with CanRead, CanWrite and CanSeek. A file opened for writing cannot be read, and a network stream cannot seek or tell its length.
using var stream = File.OpenWrite(Path.GetTempFileName());
var b = stream.ReadByte(); // NotSupportedException: Stream does not support reading.
Open the stream with the access you need, or check the capability first:
using var stream = new FileStream(Path.GetTempFileName(), FileMode.OpenOrCreate, FileAccess.ReadWrite);
if (stream.CanRead)
{
var b = stream.ReadByte();
}
A type that does not implement a member of its base class or interface
Authors throw NotSupportedException when a type has to implement a member but cannot support it. It is also what some libraries throw for things they cannot do, such as an Entity Framework query that cannot be translated to SQL.
public class ReadOnlyCart : IList<string>
{
private readonly List<string> _items = new();
public void Add(string item) => throw new NotSupportedException("The cart is closed");
public string this[int index] { get => _items[index]; set => throw new NotSupportedException(); }
public int Count => _items.Count;
public bool IsReadOnly => true;
public void Clear() => throw new NotSupportedException();
public bool Contains(string item) => _items.Contains(item);
public void CopyTo(string[] array, int arrayIndex) => _items.CopyTo(array, arrayIndex);
public IEnumerator<string> GetEnumerator() => _items.GetEnumerator();
public int IndexOf(string item) => _items.IndexOf(item);
public void Insert(int index, string item) => throw new NotSupportedException();
public bool Remove(string item) => throw new NotSupportedException();
public void RemoveAt(int index) => throw new NotSupportedException();
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() => GetEnumerator();
}
Read the message and the documentation of the type. For an unsupported query, move the part that cannot be translated after AsEnumerable() or ToList(), so it runs in memory. If you write the type yourself, expose the smaller interface instead, such as IReadOnlyList<T>.
How to fix it and prevent it
Use the read-only interfaces
Return IReadOnlyList<T> and IReadOnlyCollection<T> from your own code. They have no Add method, so the compiler tells the caller what they cannot do.
public IReadOnlyList<string> GetSkus() => new List<string> { "SKU-1" };
Check capabilities before you use them
Streams, and some other types, tell you what they support. Check CanRead, CanWrite and CanSeek when the stream comes from the outside.
public long? GetLength(Stream stream) => stream.CanSeek ? stream.Length : null;
Copy to a collection that can change
If you need to add to a collection that you received, create a new one from it. ToList() copies the items to a list that can grow.
IList<string> fixedSize = new[] { "SKU-1", "SKU-2" };
var items = fixedSize.ToList();
items.Add("SKU-3");
How to read the stack trace
The message names what is not supported, and the frame at the top shows the type that refused:
System.NotSupportedException: Collection is read-only.
at System.Collections.ObjectModel.ReadOnlyCollection`1.System.Collections.Generic.ICollection<T>.Add(T value)
at Shop.Services.CartService.AddItem(IList`1 items, String sku) in C:\src\Shop\Services\CartService.cs:line 11
at Program.<Main>$(String[] args) in C:\src\Shop\Program.cs:line 5
The top frame is ReadOnlyCollection<T>.Add, so the type that refused is the collection that was passed in, not your code. The line that called it is line 11 of CartService.cs. Follow the argument back to where the list was created as read-only.
Should you catch it?
Usually no. This exception means that the code asks for something that cannot work, so the fix is to change the code. A catch only hides the bug.
The exception to the rule is code that gets objects of unknown types, such as a library that takes any Stream. There, check the capabilities instead of catching, since that is cheaper and clearer.
Find NotSupportedException before your users do
elmah.io logs every unhandled exception in your .NET application with its stack trace and request details, groups identical errors and notifies you when a new one appears.
Start free trialRelated exceptions
- InvalidOperationException is used when an operation is not valid for the current state of an object.
- ArgumentException is thrown when an argument is not valid.
- Exception is the base class of all exceptions.
Frequently asked questions
What is the difference between NotSupportedException and NotImplementedException?
NotImplementedException says that the code has not been written yet. NotSupportedException says that the operation will never work for this type.
Why does Array.Add or List.AsReadOnly().Add compile?
Because the type implements IList<T>, which has an Add method. The check happens at runtime. Use the read-only interfaces in your own signatures to get a compile error instead.
Why does Entity Framework throw NotSupportedException for my query?
Part of the expression cannot be translated to SQL. Move the filter that uses it after AsEnumerable(), or rewrite it with methods that the provider knows.
Should I throw NotSupportedException from my own code?
Yes, for members that a type must have but cannot support, with a message that says why. Do not use it for code you have not written yet.
Let your AI agent track it down
Connect Claude Code, Cursor, VS Code or Visual Studio to the elmah.io MCP server and ask your agent to look into NotSupportedException for you. For example:
The agent reads the stack trace and request details from elmah.io, finds the code in your repository and proposes a fix. In Claude Code, add the server with one command:
claude mcp add --transport http --client-id claudecode elmahio https://mcp.elmah.io/mcp
The MCP server is included on every plan and is currently in beta. Set up the MCP server.
Further reading
YouTube videos
Answers from Stack Overflow
Use SequenceEqual to check for sequence equality because Equals method checks for reference equality.
var a = ints1.SequenceEqual(ints2);
Or if you don't care about elements order use Enumerable.All method:
var a = ints1.All(ints2.Contains);
The second version also requires another check for Count because it would return true even if ints2 contains more elements than ints1. So the more correct version would be something like this:
var a = ints1.All(ints2.Contains) && ints1.Count == ints2.Count;
In order to check inequality just reverse the result of All method:
var a = !ints1.All(ints2.Contains)
By Selman Genç. Read the original answer on Stack Overflow.
What ckuri said. Just to be clear, you need the following line of code before opening the stream (steps 2,3):
System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
ExcelDataReader - Important note on .NET Core
By default, ExcelDataReader throws a NotSupportedException "No data is available for encoding 1252." on .NET Core.
To fix, add a dependency to the package System.Text.Encoding.CodePages and then add code to register the code page provider during application initialization (f.ex in Startup.cs):
System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);This is required to parse strings in binary BIFF2-5 Excel documents encoded with DOS-era code pages. These encodings are registered by default in the full .NET Framework, but not on .NET Core.
By dawidg. Read the original answer on Stack Overflow.
.NET Core supports only ASCII, ISO-8859-1 and Unicode encodings, whereas .NET Framework supports much more.
However, .NET Core can be extended to support additional encodings like Windows-1252, Shift-JIS, GB2312 by registering the CodePagesEncodingProvider from the System.Text.Encoding.CodePages NuGet package.
After the NuGet package is installed the following steps as described in the documentation for the CodePagesEncodingProvider class must be done to register the provider:
- Add a reference to the System.Text.Encoding.CodePages.dll assembly to your project.
- Retrieve a CodePagesEncodingProvider object from the static Instance property.
- Pass the CodePagesEncodingProvider object to the Encoding.RegisterProvider method.
EncodingProvider registration code example:
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
By ckuri. Read the original answer on Stack Overflow.
I see you are using EF core DbContext in your MovieRepository. So instead of using mock, Using EF Core InMemory database will be a great option for you. This will also reduce the complexity.
Write your GetAllTest() method as follows:
[Fact]
public void GetAllTest()
{
var options = new DbContextOptionsBuilder<MovieDbContext>()
.UseInMemoryDatabase(databaseName: "MovieListDatabase")
.Options;
// Insert seed data into the database using one instance of the context
using (var context = new MovieDbContext(options))
{
context.Movies.Add(new Movie {Id = 1, Title = "Movie 1", YearOfRelease = 2018, Genre = "Action"});
context.Movies.Add(new Movie {Id = 2, Title = "Movie 2", YearOfRelease = 2018, Genre = "Action"});
context.Movies.Add(new Movie {Id = 3, Title = "Movie 3", YearOfRelease = 2019, Genre = "Action"});
context.SaveChanges();
}
// Use a clean instance of the context to run the test
using (var context = new MovieDbContext(options))
{
MovieRepository movieRepository = new MovieRepository(context);
List<Movies> movies == movieRepository.GetAll();
Assert.Equal(3, movies.Count);
}
}
Note: Don't forget to install Microsoft.EntityFrameworkCore.InMemory nuget package as follows:
Install-Package Microsoft.EntityFrameworkCore.InMemory
For more details: Testing with InMemory
By TanvirArjel. Read the original answer on Stack Overflow.
As already stated, Moq does not allow setup of extension methods.
In this case however the source code of the said extension methods are available on Github
ServiceProviderServiceExtensions.
The usual way around an issue like this is to find out what the extension methods do and mock a path safely through it's execution.
The base type in all of this is the IServiceProvider and its object Getservice(Type type) method. This method is what is ultimately called when resolving the service type. And we are only dealing with abstraction (interfaces) then that makes using moq all the more easier.
//Arrange
var serviceProvider = new Mock<IServiceProvider>();
serviceProvider
.Setup(x => x.GetService(typeof(ConfigurationDbContext)))
.Returns(new ConfigurationDbContext(Options, StoreOptions));
var serviceScope = new Mock<IServiceScope>();
serviceScope.Setup(x => x.ServiceProvider).Returns(serviceProvider.Object);
var serviceScopeFactory = new Mock<IServiceScopeFactory>();
serviceScopeFactory
.Setup(x => x.CreateScope())
.Returns(serviceScope.Object);
serviceProvider
.Setup(x => x.GetService(typeof(IServiceScopeFactory)))
.Returns(serviceScopeFactory.Object);
var sut = new ApiResourceRepository(serviceProvider.Object);
//Act
var actual = sut.Get(myIntValue);
//Asssert
//...
Review the code above and you would see how the arrangement satisfies the expected behavior of the extension methods and by extension (no pun intended) the method under test.
By Nkosi. Read the original answer on Stack Overflow.
Source: Stack Overflow