[Mono-dev] Template and assignment operator in C#

Jonathan Pryor jonpryor at vt.edu
Fri Apr 28 07:03:53 EDT 2006

On Thu, 2006-04-27 at 17:20 -0700, Rusmin Susanto wrote:
> 1. Is there any trick in C# similar to Expression Template in C++ to
> avoid pairwise evaluation? 

No yet.  Expression Templates are possible in C++ because templates are
a turing-complete sub-language within C++; C++ templates were never
designed to support expression templates, it was just a discovery that
expression templates were possible within the C++ template system.

C# generics do not contain such flexibility (by design).

C# 3.0 may be able to support something similar (maybe), via the
Expression<T> classes, which causes the compiler to generate an
Expression<T> tree instead of IL for a given expression, e.g.

	Expression<T> e = x => x + 1;

This is to permit DLINQ to grab the actual expression entered by the
user and convert it to SQL.

It's conceivable that this mechanism could be used to "fake" expression
templates, allowing some method to examine the actual expression and
optimize it for your particular classes.

However, this would only be possible within C# 3.0, which isn't
finalized (or otherwise remotely close to shipping).

> 2. Is template processed at compile time or run time in C#? I know
> that in C++ it's processed at compile time.

It depends on what you mean by "processed."

Generic types are "processed" by the C# compiler (compile time) to
ensure type safety, checking that e.g. strings are actually inserted
into a List<string>.

Generic types are "processed" by the JIT compiler as well (run time)
when "inflating" the class (producing the actual List<string> type for
use at runtime).  This permits optimal code reuse (List<string> uses the
same JITed code as List<object> and List<OtherReferenceTypes>) across
assemblies, while the C++ approach requires code duplication between
> 3. I know that in C# the assignment operator '=' for object will copy
> the reference of rhs to the lhs.
> How about if we need to define an assignment operator for an object
> that needs to copy the value of member variables (not reference) of
> rhs to lhs?
> How do we tell C# to copy value, not reference?

You don't use the assignment operator, you use a method:

	lhs.Assign (rhs); // or Copy, or some other method name...

Ultimately, this is what C++/CLI is doing for you "under the covers" as

 - Jon

More information about the Mono-devel-list mailing list