troubleshooting Question

How could I best 'extend' the sealed built-in System.String class?

Avatar of siteatis
siteatis asked on
13 Comments1 Solution599 ViewsLast Modified:

I'm very new to C# and OO methodology, and stuck on something I suspect is actually very simple.

I'm writing code that needs to be able to perform operations equivalent to VB's Left$(), Mid$() and Right$() on strings; that is, extract parts of the string WITHOUT complaining if unable to fully comply (due to requested substring being partly or wholly outside the string, for example).

All I can find in the built-in libraries is System.String.Substring, which does throw exceptions when unable to fully comply, and which also doesn't look like it can be made to (tidily) provide a service equivalent to Right$().

So first I thought I'd derive my own class from System.String. No joy, of course; it's sealed (and having read the reasons why, I don't really mind). I thought of writing a separate code module for utility functions like this, but I think they would have to be prefixed with their class name to call them, e.g:

using MyRatherUnwieldyUtilityNamespace;
foo = MyRatherUnwieldyClassThatEncapsulatesVariousStaticUtilityFunctions.Left(myString,3)

which seems rather cumbersome and not very OO-friendly. I was looking for something more like:

foo = myString.Left(3)    ... or even ...
foo = Left(myString,3)    ... if necessary.

The only other way I can think of is to wrap System.String in my own class... which I like except that as far as I can see it would mean overriding (overwriting? hiding?) a zillion constructors, and EITHER overriding all other System.String functionality I want to use OR accepting an extra layer of indirection in order to call it, i.e.

foo = mySuperImprovedString.Left(3) // My new functionality - easy to use - great!
foo = mySuperImprovedString.wrappedString.Length // Existing String functionality - boo, not so great.

I want to make good code that I can reuse over and over again. Is there a better, or even standard, technique that people use to write this kind of simple extra functionality in C#?

Join the community to see this answer!
Join our exclusive community to see this answer & millions of others.
Unlock 1 Answer and 13 Comments.
Join the Community
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 13 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros