Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I create accessors on structs to automatically convert to/from other datatypes?

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
like image 792
caesay Avatar asked Mar 01 '10 02:03

caesay


People also ask

Can a struct have methods C#?

Features of C# StructuresStructures can have methods, fields, indexers, properties, operator methods, and events.

Do structs have constructors C#?

struct can include constructors, constants, fields, methods, properties, indexers, operators, events & nested types. struct cannot include a parameterless constructor or a destructor.

Can a struct be null in C#?

In C# a struct is a 'value type', which can't be null.

Can a struct be null?

However, since structs are value types that cannot be null , the default value of a struct is the value produced by setting all value type fields to their default value and all reference type fields to null .


2 Answers

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.

like image 67
Noldorin Avatar answered Sep 30 '22 17:09

Noldorin


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

public static implicit operator string(test value)
{
    return "something else";
}
like image 30
MikeP Avatar answered Sep 30 '22 17:09

MikeP