[Mono-dev] Lang Theory Question

Robert Jordan robertj at gmx.net
Sat Feb 2 07:57:33 EST 2008


Scott Peterson wrote:
> I'm a sucker for syntactic sugar. There is one little trick which I've
> been trying and failing to do - it turns about to be impossible - but
> as a language theory exercise, I thought I'd work out what would be
> needed to let me do this thing.
> 
> One nice thing about nullable types is the non-standard behavior of
> the assignment (=) operator. For example:
> 
> int? val = 5;
> val = 6;
> 
> is shorthand for:
> 
> Nullable<int> val = new Nullable<int> (5);
> val.Value = 6;
> 
> I am working with a struc similar to Nullable and I'd like to be able
> to use the assignment operator in a similar way. Unfortunately, the
> assignment (=) operator cannot be overloaded. The struct, SchemaEntry,
> is used to store and retrieve configuration data from some backend
> (gconf, the Windows registry, an XML file, &c.). Here's essentially
> how I currently use the struct:
> 
> SchemaEntry<int> entry = new SchemaEntry<int> ("DbVersion");
> int version = entry.Get ();
> if (version < 2) {
>     MigrateDb ();
>     entry.Set (2);
> }
> 
> I would like to be able to do the above with this code:
> 
> SchemaEntry<int> entry = new SchemaEntry<int> ("DbVersion");
> int version = entry;
> if (version < 2) {
>     MigrateDb ();
>     entry = 2;
> }

Use implicit cast operators:

	public static implicit operator T(SchemaEntry<T> entry)
	{
		return entry.Get ();
	}

	public static implicit operator SchemaEntry<T>(T v)
	{
		SchemaEntry<T> x = new SchemaEntry<T> ();
		x.Set(v);
		return x;
	}


> I can think of a few possible solutions:
> 1) Require that the two parameters to the overload function be of
> different types. This would still allow the safe use of generics (as
> with SchemaEntry).
> 2) Stipulate that any use of the assignment operator inside of an
> assignment operator overload function will perform a standard bitwise
> copy.
> 3) I had other solutions, but I actually think these two cover it pretty nicely.

Since C# is standardized, there is no straightforward way to do
add such language extensions.

Robert




More information about the Mono-devel-list mailing list