3

Let's say we have a string which its length is very big, let's say even bigger than max_int.

string str="this should contain a long string";

if I want to reach to the str[100000000000].

How should I do it?

When I try to put an index which its type isn't int I get the following error:

The best overloaded method match for 'string.this[int]' has some invalid arguments

Lior
  • 5,841
  • 9
  • 32
  • 46

4 Answers4

3

You can't. I don't believe you can have an object that takes more than 2^32 bytes anyway, so you really won't run into this.

According to this post the maximum CLR object size is 2GB, which affirms my statement.

Community
  • 1
  • 1
itsme86
  • 19,266
  • 4
  • 41
  • 57
2

The maximal size of a single object was 2GB prior .NET 4.5, so you could never have a string that big, so there was no purpose in trying to use an index this large.


In .NET 4.5, you can increase that limit. Quote from MSDN:

"By default, when you run a 64-bit managed application on a 64-bit Windows operating system, you can create an object of no more than 2 gigabytes (GB). However, in the .NET Framework 4.5, you can increase this limit. For more information, see the gcAllowVeryLargeObjects element."

However, most containers still have interfaces based on int and even for arrays this won't help...

"The maximum number of elements in an array is UInt32MaxValue."

...which is 4,294,967,295 which is still smaller than 100,000,000,000 you proposed.


Do you really need to have that much continuous memory? Why not split your data to smaller chunks?

Branko Dimitrijevic
  • 50,809
  • 10
  • 93
  • 167
1

You need to implement custom array that supports large range of indexes.

All normal .Net types (like String, Array, List) support only integers for indexing. This is partially due to restriction on maximum continuous allocation size - so your custom class need to chunk data to support such indexes.

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
1

You can use Array.GetValue to get index of array that larger than int.

Ekk
  • 5,627
  • 19
  • 27