views:

110

answers:

3

is it possible to do something like the following:

struct test
{
   this
   {
      get { /*do something*/ }
      set { /*do something*/ }
   }
}

so that if somebody tried to do this,

test tt = new test();
string asd = tt; // intercept this and then return something else
+2  A: 

You can define implicit and explicit conversion operators to and from your custom type.

public static implicit operator string(test value)
{
    return "something else";
}
MikeP
+6  A: 

Conceptually, what you want to do here is in fact possible within .NET and C#, but you're barking up the wrong tree with regards to syntax. It seems like an implicit conversion operator would be the solution here,

Example:

struct Foo
{
   public static implicit operator string(Foo value)
   {
      // Return string that represents the given instance.
   }

   public static implicit operator Foo(string value)
   {
      // Return instance of type Foo for given string value.
   }
}

This allows you to assign and return strings (or any other type) to/from objects of your custom type (Foo here).

var foo = new Foo();
foo = "foobar";
var string = foo; // "foobar"

The two implicit conversion operators don't have to be symmetric of course, though it's usually advisable.

Note: There are also explicit conversion operators, but I think you're more after implicit operators.

Noldorin
@Noldorin, My struct is non-static, i have no issues with the string asd = foo, but how does foo = string work
Tommy
@sniperX: you must create a new instance of Foo, based on the string.
Shog9
Yes, Shog9 is right. If you don't want to expose the constructor directly, there's no problem with just making it private/protected.
Noldorin
A: 

Expanding on MikeP's answer you want something like:

public static implicit operator Test( string value )
{
    //custom conversion routine
}

or

public static explicit operator Test( string value )
{
    //custom conversion routine
}
Thomas