Thursday, October 17, 2013

10 Things You Maybe Didn’t Know About C# | Memory Fences

Here's a few code summaries:

1: You can create non-zero based arrays

static void Go() {
    string[] thingsThatHappenedInMyLife = (string[]) Array.CreateInstance(typeof(string), new[] { 24 }, new[] { 1990 });
 
    thingsThatHappenedInMyLife.SetValue("I was born", 1990);
    thingsThatHappenedInMyLife.SetValue("I dislocated my shoulder", 1996);
    thingsThatHappenedInMyLife.SetValue("I was allowed to buy alcohol (big mistake)", 2008);
    thingsThatHappenedInMyLife.SetValue("I started a programming blog", 2013);
 
    for (int i = thingsThatHappenedInMyLife.GetLowerBound(0); i <= thingsThatHappenedInMyLife.GetUpperBound(0); ++i) {
        string lifeEvent = (string)thingsThatHappenedInMyLife[i];
        if (lifeEvent == null) lifeEvent = "not much happened to me";
        Console.WriteLine("In " + i + ", " + lifeEvent);
    }
}


2: You can create unions in C# 

[StructLayout(LayoutKind.Explicit)]
public struct UnionTest {
    [FieldOffset(0)]
    public uint Value;
 
    [FieldOffset(0)]
    public readonly byte AsByte;
}

3: You can define extension methods with generic constraints on the extended type 

///
/// Returns the target object if it is not null; or throws a NullReferenceException if it is.
///
/// The target object's type.
/// The extended subject.
/// The message that will be passed to the generated exception. If null, then a default message will be used.
/// The object that NotNull was called on.
public static T NotNull(this T extended, string exceptionMessage = null)
    where T : class {
    if (extended == null) throw new NullReferenceException(exceptionMessage ?? "Supplied " + typeof(T).Name + " must not be null!");
    else return extended;
}
... and lots more ! Go read the blog !

1 comment:

Protiguous said...

Hmm. Their blog is gone. I should have backed up the whole thing!