Archive

Archive for May, 2008

Virtual Properties in C#

May 22, 2008 3 comments

It is an important and popular fact that properties in C# can be defined in interfaces. For example:

public interface IThing
{
    IThing Parent { get; }
}

We can then implement that interface on a concrete class:

Read more…

Advertisements
Categories: C#, wish Tags: ,

Delegates are Immutable

May 11, 2008 4 comments

Suppose you see this in some code:

button.Click += new EventHandler(button_Click);

Naturally you would conclude that Click is an event and button_Click is a method name (formally described as a method group, because the name by itself identifies one or more methods with different parameters). After the above line of code has been executed, the method button_Click will run each time the Click event fires (presumably when the button is clicked).

Read more…

Categories: C#, delegates Tags: ,

Pointers to Value-Types in C#

May 6, 2008 6 comments

C# has an "unsafe" mode in which real, nasty pointers are allowed, but this mode is rarely used except in some messy situations involving talking to old code. The C# language proper does not have pointers.

In C and C++, you can get the address of anything, including a local variable on the stack:

int x = 0;

int *p = &x; /* get address of x */

*p = 5; /* change value of x */

Of course, when a function exits, all its local variables cease to exist. Any remaining pointers to them are now "dangling" and must not be used. If they ever are… well, who knows what could happen? Make no mistake, it’s an exciting world of opportunities and I’ve already had plenty of it, thanks.

Read more…

Categories: C#, lambdas Tags: ,

DynamicObject Wrapper

May 6, 2008 5 comments

Charlie Calvert started a discussion way back in January about a proposal to add dynamic lookup support to C# – a convenient way to write code that makes calls into objects of a type not known at compile time.

A number of people have suggested that for the dynamic case, the member access syntax should be made deliberately different to the usual dot syntax. There is a lot to be said for this. The big danger of this whole idea is that a radically less type-safe way of working will start to creep into programs that used to be type-safe, thus undoing some of the good work done by adding generics. But as long as the syntax makes this clear, it’s better to have convenient support than nothing at all, or else people will invent their own approach and it will probably be horrible.

I was thinking that maybe to underline the fact that the method name is really no more solid than a string, you could have the syntax mimic accessing items in a dictionary.

So instead of:

d.LetThereBeLight(); 

Read more…

Categories: C#, dynamic Tags: ,