Linq – deferred ^ immediate execution

update — java 8 streams …

(I feel this is a low-level but popular question…)

– if an operation returns a single value (aka aggregates) then ImmEx. ([[c# indepth]]  P281)

– if an operation returns another sequence, then defEx ([[c# indepth]]  P281)

– ToList() — ImmEx

– sort uses ImmEx in SQL. Ditto Linq — [[c# indepth]]  P369

– regular SQL Select with multiple output rows? Uses defEx. As you retrieve one row, all subsequent rows are subject to change.

– SQL Select with a single-row output? probably ImmEx.


emit == Select() IEnumerable ext method

students.Select(student => student.Age) // Simplest example. From a SEQUENCE of students, emits a sequence of ints.

students.Select(student => new {owner = student, pet = …….}) // emits a sequence of pets

Can we assume Select() always emits a sequence of a homogeneous type? I would think so

c# attribute on method arg – usage

I feel attributes on method param is a rarely used feature. I feel it is meant for reflection or documentation. presents a simple usage of this feature, whereby runtime reflection extracts the additional information contained in the attribute value. You can then act on the information.

It also shows that an override method can “add” such attributes.

argument validation — presents a practical usage — argument validation. For example, you can mark an argument as NotNull

Here’s another usage, but I don’t remember if I tested it successfully.

Make ViewModel get key events only when its host tab is on top

In a tabbed GUI, I have a distinct ViewModel object for each tab. For e.g., tab3 is backed by vm3 object. In it I have a keyboard event handler to manipulate a lot of private data in the vm3 object (and update screen). This handler should fire when Tab 3 is on top. However, vm3 object has no way to tell if Tab3 is on top. MVVM in action.

My Solution: the “code-behind” Mainpage.xaml.cs ctor to register a private this.Handle3 to the this.KeyUp event, where this.Handle3 has access to the Tab3 object, so long as Mainpage.xaml exposes the Tab3 as a field via x:Name.

Handle3() checks if Tab3 is on top and then directly calls vm3.handler. Feasible because Mainpage.xaml.cs has a reference to vm3.

This relies on the code-behind as the melting pot. A quick and dirty solution.

an event inherited from interface->abstract class->concrete class

In this class hierarchy, the event is declared in interface ICommand, then declared abstract in the abstract class, finally implemented in the concrete classes.
Note the abstract must declare it.
    abstract public class TanBinRelayCommand: ICommand{
        private Action methodToExecute;
        private Func<bool> isEnabled;
        public TanBinRelayCommand(Action methodToExecute, Func<bool> isEnabled)
            this.methodToExecute = methodToExecute;
            this.isEnabled = isEnabled;
        #region ICommand members

        /// who subscribes to this event? I think the command binding (or other objects in the xaml)

        bool ICommand.CanExecute(object obj) {
            if (this.isEnabled == null) return true;
            return this.isEnabled.Invoke();
        void ICommand.Execute(object obj)
            if (this.methodToExecute != null)
        abstract public event EventHandler CanExecuteChanged;

a simple c# SaxParser – NamespaceTolerant

Note: like an istream, the reader has an internal position pointer. reader.Name can return the name of either an element or an attribute, depending on the position.
Note: one common iteration idiom uses Read(), which advances the pointer to the next start/end tag??.  Like a subway express train, it won’t stop at the attributes – local stops.

        /// It’s not easy to find a SAX parser in c#
        /// It’s not easy to find a xml parser that tolerates undeclared namespaces
        /// Here’s a solution

        private static void SaxParser_NamespaceTolerant(string arg_xmlFullStr)
            using (XmlTextReader reader = new XmlTextReader(
                                         new StringReader(arg_xmlFullStr)))
                reader.Namespaces = false; //ignore undeclared namespaces
                while (reader.Read())
                    if (string.IsNullOrWhiteSpace(reader.Name)) continue;
                    if (reader.IsStartElement())
                        if (reader.HasAttributes)
                            while (reader.MoveToNextAttribute())
                                Dump(“\t” + reader.Name + “=” + reader.Value);

c# DYNAMIC – TryCall_method1 on an Unidentified object#src

With dynamic type, we can try-call an arbitrary method m1(), which need not exist in any public interface. Behaviour — If the underlying type exposes m1, it is invoked. If unavailable you get a run time error, not a compile time error.

One usage idea — Instead of calling the standard ToString() on the unknown object, we want to try-call ToStringXml(), and pray the underlying type supports it. Traditionally, If we have a few types to add ToStringXml(), we would prefer compile-time type check by introducing an interface IXmlDumper. However, if you have 55 types that could pass into TryCall() and 33 of them exposes ToStringXml(), you may need to cast to IXmlDumper then call ToStringXml(). Worse, you would need to edit source code for the 33 types!

With dynamnic type, basically the compile-time type check is postponed to run time. Compile time type check would need m1() declared in the type C, like —

C c = new C(); c.m1();

But if we use dynamic, and type-check at run time, then we don’t need m1() exposed on any public interface —

small c# trick to log the current value of a field

Suppose you want to log (“StaticOrNonStaticField_AgeInConfig = ” + StaticOrNonStaticField_AgeInConfig), but you anticipate renaming on this field. When anyone uses any IDE to renames it next month, you want the log message to change automatically. Here’s a trick

public static string GetMemberName(Expression<Func> expr){
var body = ((MemberExpression)expr.Body);
return body.Member.Name;

Log.Info(GetMemberName(() => StaticOrNonStaticField_AgeInConfig) + ” == ” + StaticOrNonStaticField_AgeInConfig);

1 or 2 nameless classes generated for each yield block

If a (possibly static) method or getter has “yield”, then I call it (loosely) a “yield method” — officially an “iterator-method”. A yield method must return aa) IEnumerator or bb) IEnumerable.

–aa) If a “yield-method” has return type IEnumerator, then exactly 1 unnamed class generated. The yield-method return value is an instance of this unnamed class.

* This class implements IEnumerator

–bb) If a “yield-method” has return type IEnumerable, then 2 unnamed classes. The first (outside) class implements IEnumerable, so the yield-method return value is this type. This outside class implements the mandatory GetEnumerator() method returning an IEnumerator. GetEnumerator() return value is an instance of the other (inside) class.

* the 1st class implements IEnumerable

* the 2nd class implements IEnumerator

Here's a potential confusion. Say you write an IEnumerable subclass. In it you write a GetEnumerator() returning an IEnumerator. Is this the aa case or the bb case? Actually aa.

Q1: when is such a class instantiated?

A: every invocation of the yield method would instantiate an instance of 1 or 2 classes. The IEnumerator object is stateful, so you hold on to that object throughout the iteration. You don't call the yield method 55 times to hit the 55 items — you call Current/MoveNext 55 times.

Q2: but when exactly is the yield method invoked?

A: Invoked at the initialization of the foreach. The only way to use a yield-method is a foreach loop.

See P101 [[c# precisely]]

linq – a scratch seeking an itch

The more I read about linq2collection, the more convinced I feel that it’s not strictly necessary. Old fashioned for-loops are
cleaner and easier to read. Exception handling is cleaner. Branching is cleaner. Mid-stream abort is cleaner.

A linq proponent may say OO was not strictly necessary (compared to procedural), and relational DB was not strictly necessary
(compared to non-relational DB) but offer real values and so is linq. Here’s my argument, focusing on linq2collections.

– I feel this is a local implementation choice, not a sweeping, strictly enforced architectural choice. As such, a particular method
can choose not to use linq.
– Another comparison is ORM. Once ORM is chosen in a project, you can hardly choose not to use it in one particular method. Linq is
more flexible, less enforced and more “sociable”.

A java guy has no such tool but is perfectly productive, until java 8 streams…

I feel linq gained mindshare on the back of c# success. If F#, python or delphi invents such a cool feature, it would remain a niche feature. I don’t see another language embracing linq, until java 8

Neverthless, we must master linq for the sake of job interviews. This is somewhat comparable to c++ multiple inheritance – not used
widely but frequently quizzed by interviewers.

c# lambda/closure executes when #again

The increment below is not executed when CLR executes Line #2 which sets up the thread. It’s executed only when the thread gets the “driver’s seat“, which doesn’t happen when Line #2 executes.

int x = 0; //#1
ThreadPool.QueueUserWorkItem(() => x++); //#2

The void lambda is more like a standalone method. This method is not executed when it seeds the new thread. It’s executed only when the thread runs.

More specifically, this lambda is more like a nameless closure —

Action myClosure = (() => x++);

c# DYNAMIC expando object (ExOb) – phrasebook

dynamic – better assign the exob instance to a dynamic variable. If you use a ExpandoObject variable, you lose a lot of features but i won’t elaborate …

javascript/python/perl – in these languages, a class instance is conceptually(?) and physically(?) a dictionary of name-value pairs. Exob is somewhat similar.

name-value pairs — In an exob instance, a field is (obviously) name-value pair. Ditto for a runtime-created method. The “value” is basically a (possibly void) lambda expression.

Emit — is the traditional technique to create a brand new class at run time and “emit” IL code into it. Exob is newer and simpler. I guess it’s more practical.

Finalize()/dtor ^ Dispose()

c# dtor is different from c++ dtor.

–some keywords
manual — Dispose() is NOT automatically invoked like Finalize(). Upper-layer programmers should but often forget to call it (Murphy’s law)
** defensive — better include a call to Dispose() in the dtor. Note dtor calling Dispose, not the other way round.

deterministic — Dispose(). You can control when it takes place. For serious resource management, use Dispose, since Finalize() may be pending for a long time on the finalizer thread.

Q: So what resource release should I put into Dispose()?
A: eg: window handlers (HWND), database connections… For these resources, Finalize() is another layer of defence. See P210 [[C# For Java Programmers]] for an HWND example.

–[[accellerated C# 2010]] has a concise coverage of the finalizer pitfall. Here are a few pointers.
Any class with a custom dtor must implement IDisposable, according to this book.

The finalizer thread calls Finalize() on each thread in the finalizer queue. Finalize() method is virtual but not overridable in c# (despite some confusing MSDN articles). Instead, you define a dtor like in c++, and Finalize() would invoke your dtor before all base dtors, just like c++.

See also

If you need to do anything in the dtor, it’s often better done in Dispose(). There is more than 1 reason to avoid custom dtor, so much so that I don’t see any good reason to ever do it.

c# REF parameter – pointer reseat

After using “ref” keyword for a while, I slowly realized it’s only useful if inside the method you reseat the pointer. Suppose the  caller of method m1() has a variable ovar and the object is at address 0x3. This is passed into m1 as parameter “pvar”.

If m1() reassigns to pvar, then you probably should use “ref” keyword
If m1() never reassigns to pvar, then you need not (and should NOT) use “ref” keyword

These are the guidelines for the common scenario, where pvar is class-type, so pvar is a pointer-VARIABLE (not a mere address; not a pointer-object). When pvar is reassigned, the behavior depends
** ref param? ovar is also reseated to a new address 0x7
** non-ref param? ovar is unaffected.

The much less common scenario is a struct-type method parameter. I feel most developers aren’t familiar, so better avoid it.
** ref, with assignment to pvar? ovar’s fields are completely overwritten and replaced. Note ovar still refers to (NOT “points to”) the object at 0x3.
** ref, with editing on pvar.field1? field1 of the object at 0x3 is modified.
** non-ref, with assignment to pvar? no effect on ovar, the change is local to the method
** non-ref, with editing on pvar.field1? ditto

c# programmatically retrieve file path of runtime objects

From a Method object you can get the host Type object.

From a Type object you can get the host Assembly object.

From Assembly object you can get the physical assembly file.

1) (tested) Assembly.GetExecutingAssembly().Location; // gives the dll fullpath
1c) new T().GetType().Assembly; //returns the Assembly object. Works even though T is a template dummy type!

2) Process.GetCurrentProcess().MainModule.FileName

3) AppDomain.CurrentDomain.BaseDirectory; // Similar to 1)

c# regex-match backslashes in strings

My suggestion — First find a “safe” character that’s guaranteed not to show up in the original string, like “_”. Replace all back slashes. Then proceed.

Problem with backslashes is the unnecessary complications. Here I want to match “one-or-more backslashes”. In the end I need to put 4 bachslashes in the pattern to represent that “one”.

var ret = Regex.Replace(@”any number of\\\backslashes”, “(.+\\\\+)?(.+)”, “$1 – $2”);

Alternatively, I could use @ to reduce the complexity @”(.+\\+)?(.+)”

Disappointingly the @ does a partial job. We still need 2 strokes — Confusing! I’d rather just remember one simple rule and avoid the @ altogether

delegate instance is passed by value@@

myEvent += myDelegate;

Q: Is myDelegate passed by reference?
A: No. member-wise copying. In other words, each item in the delegate inv list is passed in (by reference?).
A: No. The invocation list (say 2 callbacks) are appended to myEvent’s internal inv list, and new list is ReBound to myEvent internal delegate variable.

That’s a short answer. For the long answer, we need to forget events and callbacks and focus on pure delegates as list objects holding simple “items”. Suppose dlg1 variable points to address1, and dlg2 points to address2.

dlg1 += dlg2 // translates to
dlg1 = Delegate.Combine(dlg1, dlg2). // Note: re-binding dlg1

Now dlg1 points to newly allocated address11. At this address there’s a new-born delegate object whose inv list is

[item1 at addr1,
item2 at addr1 …
itemN at addr1,
item1 at addr2,
item2 at addr2, ….
itemM at addr2]

According to, some of the items could be duplicates — Legal.

30 seconds after the Combine() operation, suppose dlg2 is subsequently modified (actually re-bound). Instead of 2 callbacks at addr2, variable dlg2 [1] now points to addr22 with 5 callbacks. However, this modification doesn’t affect the inv list at addr11, which dlg1 now points to.

Therefore, we can safely say that in a Combine() operation the RHS delegate’s inv list is copied-over, passed by value or “pbclone”.

[1] like all java reference variables, a c# delegate variable is a 32-bit pointer object. As explained in, the compiler is likely to allocate 32 bit of heap for this 32-bit object.

VAR vs DYNAMIC in c# — first look

If you declare AND initialize a variableA of “var” type, compiler figures out the exact type of this variableA. Say it’s Account. This variableA will be this type forever. In fact, compiler must get enough info to infer the exact type of variableA. Otherwise compile time error.

If variableB is declared “dynamic” type, then you can declare it without initializing. Then at run time you can assign an Account object to it, subsequently assign an integer to it. The actual type of variableB is mutable at run time. This is a bold departure from c++/java, where every variable’s type is always immutable.

You can get run time error (not compile time) with variableB, if you reference a member of variableB and the member doesn’t exist at time of evaluation, which is run time. Put another way, Evaluation is NOT at compile time. See simple example at In this sense, dynamic type is more lenient than Object type as “evaluation” is postponed to the very last moment at run time.

Dynamic type was designed for COM objects.

Only local variables can be “var”, but dynamic can be fields, method params etc.

double meanings (c#): new, using, yield

In C#, a number of keywords are given 2 unrelated meanings.

using — typedef
using — name space import
——– unrelated to ———–
using — resource management (IDisposable)
Yield() — static method Thread.Yield()
——– unrelated to ———–
yield — iterator
new MyClass() — on class types
new MyStruct() — on struct types
** does NOT necessarily hit heap; See P55 [[c#preciely]]
** doesn’t return pointer;
** entirely optional. Only needed if you want to call the ctor of the struct.
**** without new, a value type object is created uninitialized when you declare the variable.
——– unrelated to ———–
new — redefine/hide a field, method, property etc
Not a keyword, but 2D-array in c# can be either jagged or a matrix

method registry in a c# class – messier than java/c++

Background: perl has a symbol table for package (not lexical) variables.

Background: Python has a __dict__ to hold fields and methods — collectively known as “attributes” since python doesn’t really differentiate — a bold departure from c++/java/c# tradition. Another (bolder) departure — each Python class has a __dict__ and each class instance has __dict__ too.

Now, let’s look into a c# class MyClass implementing/inheriting a bunch of PUBLIC methods of the same name. This example is adapted from P109 [[c#precisely]]. MyClass”registry” of all available methods is complicated by the “new”/hiding feature and other features. MyClass can expose completely distinct implementations of —

* new virtual void M(){..}//declared in MyClass itself, hiding a base class virtual-void-M()
* void Interface_1.M() // same return type as above
* void Interface_2.M() // same return type as above.
//Note above Interface_2 extends Interface_1 but hides void-M() with an identical void-M()
// I think IEnumrable and IEnumerable require implementations to adopt this  technique
//Note below Interface_3 extends Interface_2 but overloads void-M() with int-M().
//Unlike java/c++ this overload has identical parameter set but different return type
//Note this overload uses no “new” so no hiding
* int Interface_3.M()

// regular overloads, just like c++ and java
* void M(int)
* float M(float)

c# abstract class – a few language rules

Common IV topic…

[j] abstract class with 0 abstract member is perfectly fine in c#/java.

[j] if you simply add “abstract” to an existing (concrete) class C, then compiler will no longer allow new C()  [1]

[j] abstract class C is perfectly free to define a ctor, but it can only be invoked from a subclass ctor, not by new C() 

[j] abstract sealed/final class? won’t compile.

[j] Interface methods are always public. Abstract methods in abstract class are not.

[j=100% identical to java]

PAC (Pure-Abstract Class) is an extremely useful technique in c++ but in c#/java, an obscure cousin of “interface”. Given an interface MyType source code, you could replace the word “interface” with “abstract class”. Now a subtype must Singly inherit from MyType as the single parent. I feel the only justification is future-proof i.e. enforce that subtypes don’t inherit from another non-interface. This is deliberate self-crippling or self-constraint, just like [1]

Another (obscure) way to get a PAC — remove all concrete methods from a regular class. Unlike an interface, such a PAC could have fields and protected abstract methods.

all c# value types are effectively structs@@

This is probably imprecise language, but good enough for a beginner.

There are only 2 sub-types of value types — structs and enums. Note simple types (like int) are struct type aliases.

Now, enums are backed by integers (short, long etc), so it has to share a lot of basic features with integers. I feel ALL enum features are very similar to int features. I feel if enum shows any “deviation” from struct, it’s likely superficial. Therefore, essentially all value types are structs

I guess all value objects are struct instances that won’t reveal their addresses (but structs can be passed by  “ref”). The way to pass these objects around is copying/boxing.

programmatically use a c# field name as a string -Expression trick

Say I have a literal string whose value is the name of a field/method/property. As I frequently rename these class members, I want the string value be update automatically either at runtime or at refactor-time.
Here’s the “runtime” solution (more cool than refactor-time, IMO)


/// Usage:
/// string fieldName = GetMemberName(() => MyClass.anyMember);

public static string GetMemberName(Expression<Func> expr)
  var body = ((MemberExpression)expr.Body);
  return body.Member.Name;

reflection on a c# enum instance



        /// An enum type
        /// Could be the enum name like OneDay or declared value like “1D”
        public static T StrToEnum(object obj)
            if (obj == null) throw new Exception();
            foreach (T anEnumeratedValue in GetValues())
                MemberInfo[] memInfoArray = typeof(T).GetMember(anEnumeratedValue.ToString());
                if (memInfoArray.Length == 0) break;
                object[] attributes = memInfoArray[0].GetCustomAttributes(typeof(EnumMemberAttribute), false);
                if (attributes.Length == 0) break;
                string declaredValue = ((EnumMemberAttribute)attributes[0]).Value;
                if (obj.ToString() == declaredValue)
                    return anEnumeratedValue;
            string aNameToLookFor = obj.ToString();
            return (T)Enum.Parse(typeof(T), aNameToLookFor, ignoreCase: true);

c# struct – bunch of primitives & still behaves as a primitive

“behave as” means

– pass by clone
– no inheritance
– no virtual method; no RTTI; no vtbl; no runtime binding
– readonly struct is immutable. State modifications only touches a temp copy P38 [[C#precisely]
– allocated in-situ, i.e. either on stack or as part of a “heapy-thingy”, even if you call …. new MyStruct() — P55[[c#precisely]]

** garbage collector never notices any struct instance in the heap, even if it’s a part of a “heapy-thingy” like a class instance or array.
** resembles a c++ class instance created without new or array-new. P55[[c#precisely]] has a nice diagram, showing every c#structInstance is allocated __in-situ__. By contrast, javaObjects or c#classInstances are always always heapy-thingies

I feel this is more like C than C++.

Java primitive wrappers are implemented in C# as boxing over structs. In fact, c# has no primitives. All simple types are alias of struct types. Developers may not need to create structs, but structs are an everyday
“nuisance” in C#.

##decouple to refactor a degenerating codebase

An OO design often starts cleanly decoupled, then gets /entangled/. Over time, tight coupling invariably creeps in (among other code smells) –>

* a class having (too) many fields pointing to other classes we wrote. The laziest way to put some existing logic into another class is to add a field , so-called “dependency” or “service”.
** too many setters
** complex constructors
* too many “new SomeClass” all over the place
* too many objects passed around as method arguments
* too many “public” members

Drawback — rigid, fragile — see post on …

— Some of my favorite refactoring fixes —
– a lot of assertions to document my refactoring assumptions.
– c# style static classes — all-static stateless classes
– black-box Facade
– More shared interfaces
– Factory
– Tuple classes for many-to-many association.
– POJO/DTO classes without methods — you could slowly add one or 2 methods but not recommended when cleaning up a degenerate codebase.
– Enums

– (code smell) use exceptions to break out of loops and call stacks.

auto properties ^ public fields

Automatically implemented properties are very similar to public fields, but

#) You can’t data bind to a field
#) Auto properties (like all properties) can go into interfaces. Fields can’t.
#) Auto properties can have ONE of get/set be private. If both private, then a field is better.
#) debug into getter or setter with a simple temporary code change. I guess MSVS can’t break-point on field-write alone. For debugger to work, you may need to introduce a private backing field.

See also

##5 notable value-types in dotnet

System.Nullable — parametrized struct

— /also-rans/ —
Decimal – just another Float
all “simple types”
all enum types

I feel  these are often immutable. Even if mutable, given the pbclone semantics it’s almost useless to provide mutator methods anyway. However, to understand mutable structs, consider the most improtant value type — int.

In a standard “for (int idx…” idx is mutable, but when you make a copy of idx (or pass in/out a function) the copy is detatched from the mutable int variable.

custom c# struct – rarely needed

(built on P84 ProgrammingC# OReilly) Many experienced c# guys rarely feel the need to create custom structs. A few reasons —

– pbclone needs to be cheap. Won’t be cheap if there are more than 3 simple type fields inside a custom struct
** STL iterators is also designed for cheap pbclone.
** ditto C++ smart pointers

– a struct instance should be immutable. An int variable has a struct type but is Mutable. However I believe most standard c# struct types are Immutable, without mutators like MyStruct.decrement(). If you pass a struct instance by copy and then “edit” the copy, result is often counter-intuitive. Therefore if you need a custom mutable struct, consider a custom Class instead

event handlers s/d be defined in VM !! code-behind

Update – this is the pre-Commanding perspective. In the Commanding paradigm, everything changes.

Event handling logic should ideally be in VM, but VM source code should not mention view objects. See post on model depending on view.

Many xaml developers put event handlers in the code behind the xaml. This is the “lazy” alternative. The code behind is an integral part of the view layer IMO. Its source code mentions numerous view objects.

Code behind also makes liberal use of vm objects (V is over VM). Therefore this class is the perfect melting pot of V and VM. Event handlers and other glue logic can be implemented more easily in code behind than elsewhere.

However, what is too easy is often too easy to be good. Throwing every bit of glue logic into one big class is poor modularization, poor separation of concern, poor layering. As an alternative, it’s probably wise to
move as many event handlers as possible out of code behind into the VM, esp if the handler action affects only the VM.

c# DYNAMIC keyword, again

Dynamic keyword is not easy to summarize. Let’s have a phrase book

A  DYNAMIC Variable (I didn’t say “object”) is type-checked at runtime rather than compile-time. So if a specified Member is non-existent you get the “compiler error” at runtime. Example — a regular variable “Student student1” is compile-time checked if we write code to access field/methods on student1. For a DTV student2, we can write code to access a member on it, and compiler won’t check. At runtime, if the member is non-existent on the runtime object, then we get exception.

DYNAMIC keyword replaces a type-name (like String, List) in a variable declaration, so this keyword specifies a special Variable type (i didn’t say “data type”)

The “+” example — You can have a util method to apply “+” to your dynamic type vars (DTV). This is an popular showcase of DTV, but it’s academic and contrived. Nevertheless [[c# in depth]] did a decent job.
Keywords dynamic vs var? often quizzed but the showcase examples are often contrived, obscure and not a mainstream usage of DTV. See other posts in this blog.

DTV is designed for COM-automation and interop. All other usages are unconventional and either complicated/overkill or unjustified….

Now how does this help interop? See [[c# in depth]] …

c# iterator ^ enumerator ^ enumerable

A common c# question.

Nowadays, nobody seems to write Current+MoveNext because yield (i.e. iterator) is so much easier. However, behind the scene a (generated) class still must implement Current+MoveNext.

— based on
The generic task is to step through a (virtual) collection, one item at a item. 2 ways to implement it.

1) Without iterators, you write a private class implementing IEnumerator interface which specifies Current, MoveNext, and Reset.

2) Iterators are a way for the compiler to generate this class for you, using a simple syntax (yield). This lets you implement GetEnumerator() directly in your sequence class. yourSequenceClass.GetEnumerator() would instantiate the private class and return it.

Technically, IEnumerator [1] is a c# type whereas Iterator is a mere concept not a type.

[1] Note the spelling — No type named Enumerator; Enumeration types are enums

Linq, extension method etc – random thoughts

I find the c#3.0 center piece — the LINQ feature — a lot of fancy beautification features and syntactic sugar. I don’t feel they
add any real capability that was completely “not doable” in C# 2.0.

However, Linq is indeed adopted in investment banks.

They certainly make c# source code more elegant, more natural, more like English, more “dense” but I feel in so doing they also add
additional layers of complexity. I don’t know if this is the best direction for a language.

Linq requires extension methods. Compiler magically converts static methods into functions that appear to be instance methods of the
IEnumerable type.

Linq encourage lambda (in place of plain old delegates). Compiler converts each lambda expression into a delegate instance.

Linq encourages anonymous types. Compiler converts each such type to a real type whose generated name is known only to the compiler.

Q: What problems do you have with Linq?
A(from a veteran): slow for SQL

y c# value types extend Object@@ #my take

It’s always been a puzzle to me why C# creators made this decision —

Q: why are all value types (including enums, structs and simple ints/floats etc) designed to be subtypes of System.Object. I don’t know any language (python?) making a primitive data type extend a reference type. Bold departure from tradition?
%%A: perhaps they want Object params to accept value type arguments?

Q: what “assets” do the int type (and other value types) inherit from Object supertype?
%%A: I only know ToString(), GetType(), GetHashCode(), Equals() etc. Obviously Int32 won’t inherit actual Implementation of GetType(), but it does inherit the calling Signature, so this GetType() method can be called on an Int32 instance.

c# value^ref type , briefly

I’m sure there are good summaries online, but i feel it’s worthwhile to come up with my own summary…

– only ref types can be locked
– only ref types can be singletons; value types are like primitive floats and ints

– unlike in java, value types can also be null — System.Nullable

– all ref types are on heap. Value types are like java primitives — on stack unless allocated as part of a heap object.
– since value/ref types all extend System.Object, they all support

– enum is value type in c#, just like C++
– even a struct (value type) can implement an interface, but seldom used.
– basically 3 reference types – arrays, delegates and regular classes

c# method "ref" argument of a Value-type

I feel this is obscure but not sure interview-wise…?

In Jon Skeet pointed out ref (“out” too) parameter can apply to value type or reference type.

When you hear the words “reference”/”value” used you should be very clear in your own mind whether you mean that a parameter is a reference/value parameter, or whether you mean that the type involved is a reference/value type. If you can keep the two ideas separated, they’re very simple.

As Jon pointed out, passing a Value type by “ref” (PVTBR) is different from passing a Refence type without “ref” marker (PRTBV). Notice the 2 differences between the acronyms. The difference is actually simple but requires a bit of mental gymnastics. I believe it only matters if in your method you reassign the parameter.

I feel PVTBR is occasionally needed[1], whereas the other 3 combinations below are widely used —

* PVTBV – including everyday argument passing of Struct types
* PRTBV – including everyday argument passing of Class types
* PRTBR – including “ref” parameter passing of Class types

[1] a function to swapping 2 incoming int variables — identical in c++ vs c#

eg of explicit-interface-method-implement – c#^java

Suppose Interface1 Game declares void play(void) and Interface 2 Radio declares the same void play(void) but means something different. Suppose these 2 interface are created by different vendors.

Now suppose we create a Device class implementing both interfaces so it has to implement both play() methods, but with different logic. Java won’t support this. You may use HASA — have 2 fields implementing the 2 interfaces.

Even if the 2 methods’ logic can be merged into one method body, still the meaning of play() is ambiguous. People reading the calling context may not know if we are playing a game or a radio, because these 2 “play” operations are logically unrelated. Remember source code should clearly describe intention.

With C# explicit-interface-method-implementation, Device can implement 2 play() methods simultaneously


See also P109 [[c#precisely]]

3 ways to instantiate the same c# delegate Type

In c++ or java, you can instantiate a class Animal many ways, like
Animal myCat; // exactly like declaring an int variable
Animal myCat(2); //age
Animal* myCat = new Animal(“kit”);

C# delegate is more complicated. has a concise list of about 5 different ways to Instantiate a delegate Type. Extremely insightful. Among other things, it reveals that in the instance method case the delegate Instance must “remember” the target

public delegate string FirstDelegate (int x); // type declaration.
// The following two creation expressions are equivalent,
// where InstanceMethod is an instance method in the class
// containing the creation expression (or a base class).
// The target is "this".
FirstDelegate d1 = new FirstDelegate(InstanceMethod);
FirstDelegate d2 = new FirstDelegate(this.InstanceMethod);

// Here we create a delegate instance referring to the same method
// as the first two examples, but with a different target.
FirstDelegate d3 = new FirstDelegate(anotherInstance.InstanceMethod);

// This delegate instance uses an instance method in a different class (and 
// obviously different target),
// specifying the target to call the method on
FirstDelegate d4 = new FirstDelegate(instanceOfOtherClass.OtherInstanceMethod);

// This delegate instance uses a static method in host class containing
// the creation expression (or a base class). Target is NULL for ALL static
FirstDelegate d5 = new FirstDelegate(StaticMethod);

// This delegate instance uses a static method in a different class
FirstDelegate d6 = new FirstDelegate(OtherClass.OtherStaticMethod);

c# yield statement — declarative !! imperative

In a c# method, unlike all other statements the yield statements are not a sequence of instructions. Instead, they form a declarative specification of an iterator. In a sense they have something in common with the annotations/attributes in source code?

In fact, there is no method per se. The entire yield-block is a declarative “iterator block”.

(How about the “using” statement (not the directive)? I feel it still maps to a sequence of instructions.)