C# object initialization of read only collection properties

This: MyClass c = new MyClass { StringCollection = { “test2”, “test3” } }; is translated into this: MyClass tmp = new MyClass(); tmp.StringCollection.Add(“test2”); tmp.StringCollection.Add(“test3”); MyClass c = tmp; It’s never trying to call a setter – it’s just calling Add on the results of calling the getter. Note that it’s also not clearing the … Read more

C# 3.0 generic type inference – passing a delegate as a function parameter

Maybe this will make it clearer: public class SomeClass { static void foo(int x) { } static void foo(string s) { } static void bar<T>(Action<T> f){} static void barz(Action<int> f) { } static void test() { Action<int> f = foo; bar(f); barz(foo); bar(foo); //these help the compiler to know which types to use bar<int>(foo); bar( … Read more

System.Drawing.Image to stream C#

Try the following: public static Stream ToStream(this Image image, ImageFormat format) { var stream = new System.IO.MemoryStream(); image.Save(stream, format); stream.Position = 0; return stream; } Then you can use the following: var stream = myImage.ToStream(ImageFormat.Gif); Replace GIF with whatever format is appropriate for your scenario.

Recursive control search with LINQ

Take the type/ID checking out of the recursion, so just have a “give me all the controls, recursively” method, e.g. public static IEnumerable<Control> GetAllControls(this Control parent) { foreach (Control control in parent.Controls) { yield return control; foreach(Control descendant in control.GetAllControls()) { yield return descendant; } } } That’s somewhat inefficient (in terms of creating lots … Read more

Why must a lambda expression be cast when supplied as a plain Delegate parameter

A lambda expression can either be converted to a delegate type or an expression tree – but it has to know which delegate type. Just knowing the signature isn’t enough. For instance, suppose I have: public delegate void Action1(); public delegate void Action2(); … Delegate x = () => Console.WriteLine(“hi”); What would you expect the … Read more