Hi Guys
NP108 Declaring Objects
Usually when we declare an object, type and constructor method holds the same name. But in the following program it is not, please explain the reason.
Object someObject = new StringReader("This is a StringReader");
Thank you
using System;
using System.IO;
class MainClass
{
public static void Main()
{
Object someObject = new StringReader("This is a StringReader");
if (someObject is TextReader)
{
Console.WriteLine(
"is: someObject is a TextReader or a derived class");
}
}
}
/*
is: someObject is a TextReader or a derived class
*/
Posted Jul 26, 2008, 5:52 PM
Thank you for your explanation.
AlanPosted Jul 26, 2008, 5:42 PM
Hey Maha, thought I'd make another of my rare appearances :)
The rules on implicit conversions are complicated but there's always an implicit conversion:
1. From any derived type to its parent (or an ancestor) type.
2. From any type to System.Object which is the ultimate parent of all types.
3. From any type to an interface type, if the type implements the interface.
It's also possible to create a user defined implicit conversion from one type to another.
Finally, there are implicit conversions defined between the numeric types. Broadly, a type with a smaller range can be implicitly converted to a type with a larger range. So, int can be converted to long and long can be converted to double without the need for a cast even though there's no inheritance relationship between these types.
Posted Jul 26, 2008, 4:58 PM
According to your explanation name of some classes are subjected to implicit conversion. Is there any way to find out name of the classes available for implicit conversion?
Bechir BejaouiPosted Jul 26, 2008, 12:30 PM
object x = new streamReader(); it is also possible to convert classes implicitly like class1 x = new class2(); we use that in order to profit from the extended methods within the derived class but class2 should be derived type from class1 else and in the contrast case you will recieve a runtime error that indicates that the implicit conversion is impossible