views:

87

answers:

2

Is it possible to extend primitive types such as System.String and System.Int32 (IE: integer) in .Net 4 and if so how?

To be more specific, I am aware of the concept of partial classes but this doesnt seem to be the answer. Also I find that System.String is not inheritable and Int32 is a structure.

Lastly I am interested in knowing both a VB.Net and C# answer to the above question.

Thanks all..

+7  A: 

You cannot extend them directly - the String class is sealed, for example, and as you noted value type wrappers (such as Int32) are normally structs.

You can write extension methods (C#, VB.NET) to them, that's what they are there for.

Another option, is to write a wrapper around these, exposing all of their properties and adding more functionality.

Oded
Why the downvote?
Oded
+1  A: 

Just as additional info (Oded is right already on the other stuff):

There are no "primitive types" in .Net. Only classes and value types (called structures in C#) (and all are decendents of object).

However you cannot inherit from value types (like int, byte, ...) and you cannot inherit from sealed classes (like string).

Foxfire
sry but that's inaccurate not all types derives from objecthttp://blogs.msdn.com/b/ericlippert/archive/2009/08/06/not-everything-derives-from-object.aspx
Rune FS
I never wrote that ALL types derive from object. But classes and value types DO! Citation from YOUR linked page: "A great many types do derive from object. All value types, including enums and nullable types, derive from object."
Foxfire