Loading user information from Channel 9

Something went wrong getting user information from Channel 9

Latest Achievement:

Loading user information from MSDN

Something went wrong getting user information from MSDN

Visual Studio Achievements

Latest Achievement:

Loading Visual Studio Achievements

Something went wrong getting the Visual Studio Achievements


ktr ktr two sides to everything
  • Anders Interview next week: Ask Questions Here

    With the future addition of "compiler as a service" are there any plans for possible support for metaprogramming? Like possible IDE support for templating in a way that is integrated into the C# language itself?

    I think this would make the bar much lower for creating frameworks that are both dynamic and yet very performant as well.

  • Anders Interview next week: Ask Questions Here

    Is there any update on the status of extension properties? Last I heard, they weren't going to be supported due to a lack of acceptable syntax.

    Would there ever be consideration for a syntax that allows declaration of extension methods/properties via a different kind of class definition?

    For example:

    // extension class
    // can only access public members of parent type
    // only methods and properties can be defined; no fields
    public extension class ListExtensions<T> : List<T> 
      // extension method
      public int foo() 
        /* ... */
        return this.size(); // this refers to any List<T> instance.
      // extension property
      public int bar
        get { /* ... */ return this.size(); }
        set { /* ... */ }

    I think it would be a nice thing to have. And in the future it would give any other additions to the "extension" concept a nice home.

  • Why No Computer Science"y" Books in C#?

    Sven Groot said:
    vesuvius said:

    Oh I agree with that. CS students should learn about the unmanaged side of things too. Whether it's sane to start out with C++ though, I don't know. My university was strictly C++ in first year, and way too much time was spent by people trying to figure out C++ the language rather than the problem they were trying to solve. This was even more apparent when I was assistant for that very same first year class a few years later.


    However, the main issue I was getting at before is that you said you exclude C# because it's managed, yet you did put Java on the list in an earlier post.

    I tend to agree that since C# has introduced several new paradigms (functional, declarative, dynamic, etc...), it has become the best language for the majority of projects out there.


    However, with all these new capabilities comes complexity.  For a CS student with no experience with programming languages, C# is generally (IMHO) not a good first language.  The language is so powerful and broad now that it is hard to know where to start if you've never been exposed to programming.


    C# has had a flood of innovation (LINQ, lambdas, dynamic programming, extension methods, etc...).  Not to mention all of the additional features that C# 1.0 had over Java (delegates, properties, etc...).  The truth is that to you and me C# is beautiful but to a beginner it is simply daunting.

  • CSharp thread

    Sven Groot said:
    ktr said:

    Yeah, I thought of that after posting it, but couldn't be arsed to change it. Wink


    Note that if you do that, you should calculate start incrementally by adding count, not the way it's done now.

    Ah, true.

  • CSharp thread

    Sven Groot said:
    cro said:

    I think you'll have to use wait handles (in this case I'm using ManualResetEvent which is the most appropriate here I think):


    public static void ComputeUnits(Unit[] units)
        int threadCount = Environment.ProcessorCount;
        int unitsPerThread = units.Length / threadCount;
        int remainder = units.Length % threadCount;
        ManualResetEvent[] evts = new ManualResetEvent[threadCount];
            for( int t = 0; t < threadCount; ++t )
                evts[t] = new ManualResetEvent(false);
                int count = unitsPerThread;
                if( t == threadCount - 1 )
                    count += remainder; // Give the last thread the remainder
                int start = t * unitsPerThread;
                ManualResetEvent evt = evts[t]
                ThreadPool.QueueUserWorkItem(obj => ComputeThread(units, start, count, evt));
            foreach( ManualResetEvent evt in evts )
    private static void ComputeThread(Unit[] units, int start, int count, ManualResetEvent evt)
        for( int x = start; x < start + count; ++x )


    Note: never, ever do this if ComputeUnits itself is on a thread pool thread. Waiting on a thread pool thread from another thread pool thread can cause deadlock.


    Maybe you could change this:
    if (t == threadCount - 1)  count += remainder; // give the last thread the remainder
    to this:
    if (t < remainder) count++; // evenly distribute remainder


  • Windows 7 was *my* idea

    That's hilarious.

  • Ideas for C# 5.0

    BitFlipper said:
    exoteric said:

    Well, if you look at anonymous methods and captured variables etc, the compiler already creates anonymous classes in that case as you mention. We don't really care too much about the signature of these classes, since they are mostly hidden from us (although you can certainly see them in the debugger). In addition, when you use IEnumerable and yield return, the compiler infers the type from the return value. So if you combine those two concepts, you can basically have tuples with named items, right?


    So in my example, the type of "result", would be something like "<Tuple>a__1" or whatever, but it would contain the public members with the correct names and types. Edit: And this is also what you would see if you used reflection to query the enclosing class's properties.


    BTW, in my example then it should really be returned like this:


    public ITuple Result
        get { return (Count = runCount, Min = runMin, Max = runMax, Avg = runAvg); } 


    So just like you use IEnumerable when using yield return, you use ITuple, and the return type determines its true signature.



    This is very similar to anonymous types:


    var x = new { Count = runCount, Min = runMin, Max = runMax, Avg = runAvg };


    The only difference is that anonymous types can only be used in a local scope.  I think that you should be able to return them from methods.  It is still just as type-safe but a lot more succinct:


    public var GetAnonymous() {
      return new { Count = runCount, Min = runMin, Max = runMax, Avg = runAvg };

  • Extensia

    W3bbo said:
    exoteric said:

    Methods for working with lists to allow editing them within foreach loops without needing to manage a separate itemsToRemove list yourself:


    Because C# 3.0 doesn't support generic covariance I couldn't avoid using the Object type in the dictionary.


     // how do you do a Dictionary<List<T>,List<T>> where T is unknown? the CLR doesn't support generic inheritance (So you can't do Dictionary<List<Object>,List<Object>> *AND* ensure Object == Object too) private static Dictionary<Object,Object>
     _pendingRemovals = new Dictionary<Object,Object>(); private static List<T> GetPendingRemovals<T>(IList<T> list) { if( !_pendingRemovals.ContainsKey( list ) ) _pendingRemovals.Add( list, new List<T>() ); List<T> pendingRemovals = (List<T>)_pendingRemovals[
     list ]; return pendingRemovals; } /// <summary>Removes <paramref name="removeThis"/> from the list when RemoveCommit is called.</summary> public static void RemovePending<T>(this IList<T> list, T removethis) { List<T> pendingRemovals = GetPendingRemovals(
     list ); pendingRemovals.Add( removethis ); } /// <summary>Removes all pending items from the list</summary> public static void RemoveCommit<T>(this IList<T> list) { List<T> pendingRemovals = GetPendingRemovals( list ); foreach(T item in pendingRemovals) {
     list.Remove( item ); } _pendingRemovals.Remove( list ); } /// <summary>Cancels all pending item removals from <param name="list" /></summary> public static void RemoveCancel<T>(this IList<T> list) { _pendingRemovals.Remove( list ); } /// <summary>Cancels a
     particular pending removal.</summary> public static void RemoveCancel<T>(this IList<T> list, T dontRemoveThis) { List<T> pendingRemovals = GetPendingRemovals( list ); pendingRemovals.Remove( dontRemoveThis ); }



    List<Bar> bar = GetBarList(); foreach(Foo foo in bar) { if( foo.NeedsDeleting ) bar.PendingRemove( foo ); } bar.PendingCommit();

    That's pretty cool.  I prefer a different approach, however.


    public static void RemoveWhere<T>(this IList<T> list, Func<T, bool> where) { for (int i = 0; i < list.Count; i++) if (where(list[i])) list.RemoveAt(i--); } //... var list = new List<string> { "Jon", "Bob", "Joe", "Herb", "Billy",
     "Boe" }; list.RemoveWhere(s => s.StartsWith("B")); // results in { "Jon", "Joe", "Herb" }


    EDIT: Haha, and apparently the library designers agree.  List<T> already defines a RemoveAll method that does the same thing.  To be fair though, this works on any IList<T>.

  • Enums are expensive in ​dictionarie​s?

    You should use an array. Just make your enum values equal to the corresponding indices.


    enum FlyState {
      State1 = 0,
      State2 = 1,
      // ...
    // ...
    var flyStateColors = new Color[Enum.GetValues(typeof(FlyState)).Length];
    // or
    var flyStateColors = new Color[/* hardcoded value */];
    // set a value
    flyStateColors[(int)FlyState.State1] = Color.FromArgb(255, 0, 0);
    // get a value
    var color = flyStateColors[(int)someFlyState];


    You could even make extension methods to get/set values of a color array based on FlyState values instead of integer indices.

  • How do you hide properties?

    ktr said:

    using System.Windows.Forms; using System.ComponentModel; namespace Test2 { class ProgressBar2 : ProgressBar { [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
     public new bool TabStop { get { return ((Control)this).TabStop; } set { ((Control)this).TabStop = value; } } } } 

    Also, this won't hide the property from intellisense unless the project you are working on lives in a different DLL from the control.  You also can't have the project that the control lives in open in the same VS instance, otherwise intellisense will pick it up.