find a location for property in a new city

Tuesday 17 April 2012

What to do with LastIndexOf unexpected ArgumentOutOfRangeException behaviour

Using string.LastIndexOf(char value, int startIndex, int count); started giving me some behaviour I wasn't expecting when it started giving me an ArgumentOutOfRangeException Exception with a description of: "Count must be positive and count must refer to a location within the string/array/collection."

Let me give you an example:

var message = ".NET is unusually faultless!";
var maxSearch = 16;
var count = message.LastIndexOf('l', 0, maxSearch);
var newMsg = message.Substring(0, count);

This should work right? What could be wrong with this? Well according to IntelliSense "Reports the index position of the last occurrence of the specified Unicode character in a substring within this instance. The search starts at a specified character position and examines a specified number of character positions." Hmm.. Okay. And the count parameter that I am getting wrong? "The number of character positions to examine." Seems legit.

I decided to disassemble .NET to have a peep at what's going on internally... Have I found a bug in .NET?! Can't tell because the method is extern, so I cannot look at it. I instead did some experimenting and worked it out.

How to properly use LastIndexOf

Turns out I was just using it incorrectly and blaming my tools. Although I am convinced some blame lies with IntelliSense for forgetting to mention that LastIndexOf searches backwards through the string! Should I have known that? I don't know. Anyway this is what I should have written:

var message = ".NET is unusually faultless!";
var maxSearch = 16;
var count = message.LastIndexOf('l', maxSearch, maxSearch);
var newMsg = message.Substring(0, count);

The startIndex parameter should be at the last point you want to search backwards from. The count then specifies the amount of chars for your search to go back through.

Maybe I'm just being stupid or maybe it is just that Console.WriteLine(newMsg);

Follow britishdev on Twitter

48 comments:

  1. This is such an informative article and very clearly written. Every single thought and idea is direct to the point. Perfectly laid out. Thank you for taking your time sharing this to you readers. http://scarprin.biz/

    ReplyDelete
  2. This has to be one of my favorite posts! And on top of thats its also very helpful topic for newbies. Thanks a lot for informative information!
    bar sets with stools

    ReplyDelete
  3. Very helpful indeed. I stumbled over the exact same thing and am glad to know why.

    ReplyDelete
  4. Great post! I am so happy I have found your site. I already have the best essays site ever and now I finally have the best developing site ever as well! Thank you for posting!

    ReplyDelete
  5. Wholesale printed custom perfume boxes with the highest quality and affordable prices. Free worldwide Delivery and free Custom Perfume Boxes design.

    ReplyDelete
  6. Buy online wholesale printed custom candle boxes and packaging at easy prices and shipping worldwide, with 24/7 customer support. Get a free custom quote now!!

    ReplyDelete
  7. Blackbird packaging provide you with any size, shape design, lipstick boxes sooner than any other packaging competitor in the market

    ReplyDelete
  8. Packaging town is a one stop solution for the short-run cbd face oil boxes, Wholesale Custom Boxes needs and supplies. At affordable prices. Request a free quote now.

    ReplyDelete
  9. Packaging town is a one stop solution for the short-run cream boxes needs and supplies. At affordable prices. Request a free quote now.

    ReplyDelete
  10. The information you have posted is very useful. The sites you have referred was good. Thanks for sharing.
    Reference:
    Web Design Minneapolis

    ReplyDelete
  11. Packaging town is a one stop solution for the short-run kraft business card boxes needs and supplies. At affordable prices. Request a free quote now.

    ReplyDelete
  12. MATLAB, which stands for Matrix Laboratory, is a high-performance language. You might find yourself looking for
    MATLAB assignment help online if you’re not familiar with its functionalities. In this article, we’ll look at some of the necessary toolboxes that MATLAB offers. If you familiarise yourself with these, then finalising those assignments will be a piece of cake.

    Neural network toolbox
    A neural network toolbox is a string of algorithms that try to establish a connection between data, similar to how the human brain works. You must have read about neurons when searching for your science essay homework help online. The word ‘neural’ comes from ‘neuron’. You can use this tool to perform functions like classification, regression, weather forecasting, and many more.

    https://cooljonny.com/blog/clarasmith/Five-Major-Toolboxes-Available-in-MATLAB

    ReplyDelete
  13. Buy online sweatshirts from wild goat clothing. get free shipping

    ReplyDelete
  14. buy electronics online from alfatah at best prices. get free shipping

    ReplyDelete
  15. buy custom soap boxes online from packaging town at best prices. Get Free shipping

    ReplyDelete
  16. buy business card boxes wholesale from packaging town at best prices. Get free shipping.

    ReplyDelete
  17. Shop from a wide variety of Local and Imported hair masks online available at Al-Fatah. Shop hair masks and hair moisturizers in wide variety from favorite brands today available under one roof at Al-Fatah. Shop the best for your Hair. Avail Free Delivery on order above 1000pkr in selected cities only.

    ReplyDelete
  18. Buy lawn collection 2021 online from Ilaha Clothing at best prices.get free shipping.

    ReplyDelete
  19. buy pret collection 2021 online from Ilaha clothing at best prices. Get free shipping.

    ReplyDelete
  20. Blackbird packaging provide you with any size, shape design, wholesale cookie boxes wholesale sooner than any other packaging competitor in the market

    ReplyDelete
  21. Packaging town is a one stop solution for the short-run custom pillow boxes needs and supplies. At affordable prices. Request a free quote now.

    ReplyDelete
  22. insulins online online from Medisense.pk. Get free shipping.

    ReplyDelete
  23. buy cosmetics online from alfatah at best prices delivered at your doorstep. get free delivery

    ReplyDelete
  24. buy gym wear online pakistan online from dshred at easy prices delivered at your doorstep. Get free shipping

    ReplyDelete
  25. buy active wear online pakistan online from dshred at best prices delivered at your doorstep. Get free shipping

    ReplyDelete
  26. buy reflective vest online from dshred at easy prices delivered at your doorstep. get free shipping

    ReplyDelete
  27. buy leggings for girls online from dshred at easy prices delivered at your doorstep. Get free shipping

    ReplyDelete
  28. Now You can get best quality multivitamins in pakistan online from medisense where all kind of supplements and multivitamins are available. Quick delivery.

    ReplyDelete
  29. Buy best quality blood pressure machine in Pakistan online at affordable prices from medisense. Quick Delivery

    ReplyDelete
  30. Buy mens gym trousers online from Dshred at best prices delivvered at your doorstep. Get free shipping

    ReplyDelete
  31. Buy men for shorts online from ndure at best prices delivered at your doorstep. Get free shipping.

    ReplyDelete
  32. Buy grocery online in Pakistan at best prices delivered at your doorstep. Get free shipping

    ReplyDelete
  33. buy tissue boxes online from Al-Fatah at best prices delivered at your doorstep. Get free shipping.

    ReplyDelete
  34. When the temperature lowers and the wind picks up, you crave something cozy to keep you warm and safe. If you need to go out for a fun evening with your best friends, a day with relatives, or a formal lunch with professional colleagues under such conditions, you hunt for fashionable garments that will keep you warm. With the best winter suits for women, we've got you covered.
    This extensive choice of winter textiles are produced with the finest of detailing, charming patterns, and trendy colours to provide you with the appropriate seasonal hues. They have the best for everyone, from embroidered to unstitched, solid colours to bright designs.
    So, let's embark on a quest to find the best dresses for girls to slay the winter days!
    pakistani clothes online

    ReplyDelete
  35. If you are looking for Pakistani luxury pret then buy a party wear dress online from Seran. Trending Fashion.

    ReplyDelete
  36. Every other distinguishing function of the
    Heritage Montessori method is that it emphasizes a studying environment. The reading takes area based totally mostly on each toddler’s unique capability and wishes. This holistic method has made a huge distinction in the lives of many children and is designed to capture a little one’s unique character thru way of celebrating their skills.
    https://armourguards.blogspot.com/2022/04/heritage-montessori-daycare.html

    ReplyDelete
  37. best cake providers, the custom of offering gifts online has turned into a well known custom as of now. Via looking on the different famous web crawlers one can undoubtedly reveal the various internet based sites to purchase fresh flowers

    https://armourguards.wordpress.com/2022/04/21/order-cakes-flowers-online-at-best-price/

    ReplyDelete
  38. Traditional or Luxury office furniture focus on modern and more superior looks. Providing fancy and variation in designs

    office furniture abu dhabi
    office furniture dubai

    ReplyDelete
  39. Writing in lsmschool.com, childcare blogger Beth Swanson says the benefit of children playing group sports activities consequences in a experience of network and shared obligation for outcome. man or woman sports activities, consisting of running, swimming or golfing can help domesticate a infant’s independence and resilience. but that doesn’t suggest they’ll be by myself. Even sports that require character performances require running with coaches and other athletes, such as on track teams in which man or woman performances can have an effect on a crew final results. choosing between a team sport or person game will ultimately rely upon your toddler’s athletic choice.

    ReplyDelete
  40. The break out sport has worked its way to the top! All video games are in-house and are a result of the hard work of a diffusion of experts. From scenic artists to robot engineers, the get away organization has outdone itself in creating immersive best escape room in north texas ! https://northtexasescaperooms.com/

    ReplyDelete
  41. you can assist keep your vehicle going for walks securely and successfully at some point of the blistering summer months. in particular, guarantee your car is experiencing trendy pleasant renovation for all 12 months insurance.
    Get a unfastened, no-dedication quote online today at rogermotors.com and comfortable your car with a first-rate vehicle warranty.

    https://moxzo.in/

    ReplyDelete
  42. At some stage in the summer season and school vacations you can also sign up your infant in skill-constructing camps that train kids a while 7-13 the basics of mountain climbing. The fitness center also encourages households to climb on their personal terms, however note that youngsters underneath the age of 14 must be supervised by means of an adult chaperone at all times.

    https://unitedrocks.org/

    ReplyDelete
  43. To pick out the proper display protector, you need to find the right one on your stereo version. Regardless of what kind of radio you're the usage of, pick the improved glass display screen protector for car .https://armourguards.co.in/

    ReplyDelete
  44. It can seem bizarre to claim that watching a fit in a sports bar offers viewers get right of entry to to all the movement; nevertheless, it’s true. Looking a game in a stadium way your subject of vision is constrained to what facet of the space you are on. Moreover, you may get distracted by your rowdy buddies, or your view may be obstructed via the enormously tall human beings in the front of you. At a sports bar, you get a blow-by means of-blow account of what’s going on throughout the sport. You get views from all sides so you’re now not left questioning what occurred whilst a controversial name is made a referee. https://woodysfrisco.com/

    ReplyDelete
  45. Good Work. Multiwoodae offers a variety of home Furniture and office furniture like table, chairs, at competitive prices with different design choices, sizes and colors to suit your needs.
    best home furniture

    ReplyDelete
  46. This blog is unlike anything I've ever seen. It's very entertaining to read. One of the most helpful websites I've ever seen is this blog, which is also a great helpful website.


    Sam David | Online Homeschooling

    ReplyDelete
  47. Karachi's pint-sized fashion stars are stealing the show in high-end wedding attire. A rising trend worth noting! Kids Clothing

    ReplyDelete