tags:

views:

65

answers:

3

implicit and explicit conversion of one reference type to other reference type?? please take an example to make answer more effective.

+6  A: 

As has already been stated, it's completely unclear what you're actually asking... but it's easy to given an example of a couple of types which do this.

Here's an implicit conversion from string to XName:

XName name = "foo";

This is declared in XName, like this:

public static implicit operator XName (string expandedName)
{
    // Implementation
}

And here's an explicit conversion from XElement to string:

XElement element = new XElement(name, "some content");
string value = (string) element;

This is declared in XElement, like this:

public static explicit operator string (XElement element)
{
    // Implementation
}

Now, what was it you actually wanted to know?

Jon Skeet
thank you jon ..
ashish
+2  A: 

Here is an example of defining and using explicit and implicit casts/conversions from one class to another.

class Foo
{
    public static explicit operator Bar(Foo foo)
    {
        Bar bar = new Bar();
        bar.Name = foo.Name;
        return bar;
    }

    public string Name { get; set; }
}

class Bar
{
    public static implicit operator Foo(Bar bar)
    {
        Foo foo = new Foo();
        foo.Name = bar.Name;
        return foo;
    }

    public string Name { get; set; }
}

class Program
{
    static void Main()
    {
        Bar bar = (Bar)(new Foo() { Name = "Blah" }); // explicit cast and conversion
        Foo foo = bar; // implicit cast and conversion
    }
}
Anthony Pegram
+2  A: 

Implicit conversion is where you assume that the compiler or the program will convert your value for you:

int myInt = 123;
object myObj = myInt;

Explicit conversion is where you specify 'explicitly' in the code that you want it converted:

int myInt = 123;
object myObj = (object)myInt; //Here you specify to convert to an object
Mike Webb