Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

basic types e.g. int

Status
Not open for further replies.

Chrissirhc

Programmer
May 20, 2000
926
GB
Hi,

My main programming language was Java and I just saw something odd in c# code.

int x = 5
x.toString()

How can you have a method on a basic type. Or are there no basic types in c #.

Please excuse me I am brand new to this. Laymans terms will be great.

Thanks

Chris
 
[tt]int[/tt] is a basic type, but it can be boxed into an object if you treat it like one.
 
What exactly is boxed?

The compiler knows that it is a basic type but when you use it like an object when coding it treats it like an object?

 
Boxing is wrapping a basic type in an object. The compiler automatically generates code to do this for you if you treat the basic type as an object.

There's a cost associated with doing this, so if you're worried about performance you would want to do it manually. I'm not sure if the compiler would optimize to a single boxing operation for code like

[tt]int x = 5;
Console.WriteLine("{0}", x);
Console.WriteLine("{0}", x);[/tt]

([tt]Console.WriteLine()[/tt] has several overloaded definitions. The one used in the code above takes a format string and any number of objects, so [tt]int x[/tt] needs to be boxed for the call.)
 
int is just a shortcut for the struct System.Int32.
So because it is a struct it has inherited from System.Object and therefore it has a ToString() method.

Every class or struct has this function and it is good to overload it so that you get your own string representation of your class.

In the case of System.Int32 the designers has implemented the ToString() method to return the equivalent string representation of the integer value.

Larsson
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top