Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extending primitive types

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..

like image 481
Maxim Gershkovich Avatar asked Jun 03 '26 17:06

Maxim Gershkovich


2 Answers

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.

like image 103
Oded Avatar answered Jun 06 '26 08:06

Oded


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).

like image 43
Foxfire Avatar answered Jun 06 '26 07:06

Foxfire



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!