C# Useful Code Snippets

ENUMS AS STRINGS

Console.WriteLine("The entries of the Colors Enum are:");
foreach(string s in Enum.GetNames(typeof(Colors)))
    Console.WriteLine(s);

Console.WriteLine();

Colors myOrange = (Colors)Enum.Parse(typeof(Colors), "Blue");
Console.WriteLine(Colors.Blue);
Console.WriteLine("Type: " + myOrange.GetType().ToString());
Console.WriteLine("The myOrange value has the combined entries of {0}", myOrange);

Console.WriteLine("Press <enter> to exit...");
Console.Read();

HOW TO GET THE NAME OF AN ENUM

enum Colors { Red, Green, Blue, Yellow };
Console.WriteLine(Enum.GetName(typeof(Colors), Colors.Green));

HOW TO READ A FILE

string webSecurityConfig;

using (StreamReader sr = new StreamReader("WebSecurity.config"))
{
    webSecurityConfig = sr.ReadToEnd();
}

HOW TO WRITE A FILE

using (StreamWriter sw = new StreamWriter("TestFile.txt"))
{
    // Add some text to the file.
    sw.Write("This is the ");
}

READ FILE, REGEX FILE, WRITE FILE

string webSecurityConfig;

using (StreamReader sr = new StreamReader("WebSecurity.config"))
{
    webSecurityConfig = sr.ReadToEnd();
}

File.Move("WebSecurity.config", "OldWebSecurity.config");

Console.WriteLine(webSecurityConfig);

Regex regexSecurePort = new Regex("SecurePort=\"9001\"");
string webSecurityConfigComplete = regexSecurePort.Replace(webSecurityConfig, "SecurePort=\"443\"");

Console.WriteLine(webSecurityConfigComplete);

using (StreamWriter sw = new StreamWriter("WebSecurity.config"))
{
    sw.Write(webSecurityConfigComplete);
}

SWITCHING ON DICTIONARY KEY OR VALUE TYPE

foreach ( DictionaryEntry de in hashtable )
{
    Console.WriteLine("");

    Console.WriteLine("key: " + de.Key.ToString());
    Console.WriteLine("key type: " + de.Key.GetType().ToString());

    Console.WriteLine("val: " + de.Value.ToString());
    Console.WriteLine("val type: " + de.Value.GetType().ToString());

    Console.WriteLine("");
}

// or
if (hashtable[2] is System.String)
{
    Console.WriteLine("yup");
}
else
    Console.WriteLine("nope");

MODULUS EXAMPLE

const int NUM_COMPANIES = 100;
const int NUM_USERS = 2;
int i=0;
int j=0;
int total = 0;
string currentUserName = string.Empty;
for (i=0; i < NUM_COMPANIES; i++)
{
    for (j=0; j < NUM_USERS; j++)
    {
        total++;
        if ((total % 50) == 0)
        {
            Console.WriteLine("HERE");
        }
    }
}

HOW TO INITIALIZE A LIST INLINE

IList<string> ss = new List<string>(){"zonk", "florb"};

foreach (string s in ss)
{
    Console.WriteLine(s);
}

USING Commandline.OptParse

OptionDefinition[] optionDefs = OptionDefinition.CreateDefinitions(new string[] {"opt1", "opt2"});
OptionResultsDictionary valuesDictionary = new OptionResultsDictionary();
Parser parser = ParserFactory.BuildParser(optionDefs, valuesDictionary);

parser.OptStyle = OptStyle.Unix;
string[] stringsFromParser = parser.Parse();

foreach(string str in stringsFromParser)
{
    Console.WriteLine(str);
}

HOW TO CREATE A BITWISE FLAG/ENUM

[Flags]
enum Styles : int
{
    Style1 = 1, Style2 = 2, Style3 = 4, Style4 = 8, Style5 = 16, Style6 = 32, Style7 = 64, Style8 = 128,
    All = Style1 | Style2 | Style3 | Style4 | Style5 | Style6 | Style7 | Style8
};

[STAThread]
static void Main(string[] args)
{
    // Setting flags ON:
    // To set multiple flags, concatenate the desired flags using the bitwise OR symbol "|":
    Styles style;
    style = Styles.Style1 | Styles.Style3;
    byte styleByte = System.Convert.ToByte(style);
    Console.WriteLine("styles 1 and 3 hex: " + styleByte.ToString("x2"));
    Console.WriteLine("styles 1 and 3 bin: " + _GetByteBitsAsString(styleByte));
    Console.WriteLine("current styles: " + style);
    Console.WriteLine();

    style = Styles.All;
    styleByte = System.Convert.ToByte(style);
    Console.WriteLine("all hex: " + styleByte.ToString("x2"));
    Console.WriteLine("all bin: " + _GetByteBitsAsString(styleByte));
    Console.WriteLine("current styles: " + style);
    Console.WriteLine();

    // Setting flags OFF:
    style &= ~Styles.Style2;
    style &= ~Styles.Style4;
    style &= ~Styles.Style6;
    style &= ~Styles.Style8;

    styleByte = System.Convert.ToByte(style);
    Console.WriteLine("minus 2, 4, 6, 8 hex: " + styleByte.ToString("x2"));
    Console.WriteLine("minus 2, 4, 6, 8 bin: " + _GetByteBitsAsString(styleByte));
    Console.WriteLine("current styles: " + style);
    Console.WriteLine();

    // Testing to see if a certain flag is set:
    Console.WriteLine("Style1: " + ((style & Styles.Style1) == Styles.Style1).ToString());
    Console.WriteLine("Style2: " + ((style & Styles.Style2) == Styles.Style2).ToString());
    Console.WriteLine("Style3: " + ((style & Styles.Style3) == Styles.Style3).ToString());
    Console.WriteLine("Style4: " + ((style & Styles.Style4) == Styles.Style4).ToString());
    Console.WriteLine("Style5: " + ((style & Styles.Style5) == Styles.Style5).ToString());
    Console.WriteLine("Style6: " + ((style & Styles.Style6) == Styles.Style6).ToString());
    Console.WriteLine("Style7: " + ((style & Styles.Style7) == Styles.Style7).ToString());
    Console.WriteLine("Style8: " + ((style & Styles.Style8) == Styles.Style8).ToString());
}

private static string _GetByteBitsAsString(byte byteToConvert)
{
    string bits = string.Empty;
    for (int t = 128; t > 0; t = t / 2)
    {
        if ((byteToConvert & t) != 0) bits += "1";
        if ((byteToConvert & t) == 0) bits += "0";
    }

    return bits;
}

MODIFYING BY EXPLICIT REF: THIS WORKS

[STAThread]
static void Main(string[] args)
{
    a aobj = new a();
    //object _a = aobj as object;
    _processObj(ref aobj);

    b bobj = new b();
    object _b = bobj as object;
    _processObj(ref _b);

    Console.WriteLine(bobj.x);

    Console.WriteLine("Press <enter> to exit...");
    Console.Read();
}

private static void _processObj(ref object obj)
{
    if (obj is a)
    {
        a aObj = obj as a;
        aObj.y = 100;
        Console.WriteLine(aObj.y);
    }
    if (obj is b)
    {
        b bObj = obj as b;
        bObj.x = 200;
        Console.WriteLine(bObj.x);
    }
}

GET BY XPATH FROM XML STRING

string xmlStr = "<ArrayOfFileTreeElement xmlns=\"http://collaboration.autodesk.com/2007/08\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\"><FileTreeElement><ChildCount>1</ChildCount><ChildUri>https://sfo12356852.ads.autodesk.com:9001/FileService.svc/xml/site/Site1/Files/ByPath/APIProject_20071101_152446_691_2055274856/TestDownloadLatestVersionOfSingleFileByIdFromProject_20071101_152446_863_1748515494.dwg</ChildUri><CreatedBy i:nil=\"true\"/><ElementType>File</ElementType><Id>107</Id><LockStatus>Unlocked</LockStatus><LockedBy i:nil=\"true\"/><Name>TestDownloadLatestVersionOfSingleFileByIdFromProject_20071101_152446_863_1748515494.dwg</Name><ParentUri>https://sfo12356852.ads.autodesk.com:9001/FileService.svc/xml/site/Site1/Files/ByPath/APIProject_20071101_152446_691_2055274856</ParentUri><Version i:nil=\"true\"/></FileTreeElement></ArrayOfFileTreeElement>";

XmlDocument doc = new XmlDocument();
doc.LoadXml(xmlStr);
string defaultNamespace = doc.DocumentElement.NamespaceURI;
XmlNamespaceManager nsMgr = new XmlNamespaceManager(doc.NameTable);
nsMgr.AddNamespace("default", defaultNamespace);
XmlNodeList l = doc.SelectNodes("/default:ArrayOfFileTreeElement/default:FileTreeElement/default:Id", nsMgr);

foreach (XmlNode n in l)
    Console.WriteLine(n.Name + ": " + n.InnerText);

GENERIC FACTORY

public class GenericIdFactory<T> where T : new()
{
    public GenericIdFactory()
    {
    }

    public T CreateId()
    {
        return new T();
    }
}

DYNAMIC INSTANTIATION/CONSTRUCTION

static void Main(string[] args)
{
    ConcreteId1 c1_1 = new ConcreteId1("zog", 999);

    ConcreteId1 c1_2 = c1_1.DeepCopy(c1_1) as ConcreteId1;

    Console.WriteLine(c1_1.Name + ": " + c1_1.Id);
    Console.WriteLine(c1_2.Name + ": " + c1_2.Id);

    c1_2.Name = "Flon";
    c1_2.Id = 17;

    Console.WriteLine(c1_1.Name + ": " + c1_1.Id);
    Console.WriteLine(c1_2.Name + ": " + c1_2.Id);

    Console.WriteLine("Press <enter> to exit...");
    Console.Read();
}

public abstract class EntityId
{
    protected EntityId(){}
    protected EntityId( string name, int id ) { Name = name; Id = id; }

    public int Id { get; set; }
    public virtual string Name { get; set; }
    public virtual object DeepCopy(object value)
    {
        EntityId valueAsEntityId = value as EntityId;
        object[] ctorArgs = new object[] { valueAsEntityId.Name, valueAsEntityId.Id };
        return Activator.CreateInstance(value.GetType(), ctorArgs);
    }
}

public sealed class ConcreteId1 : EntityId
{
    public ConcreteId1() : base() { }
    public ConcreteId1(string name, int id) : base(name, id) { }

    public override string Name { get; set; }
}

MEMORY GOBBLER EATER

List<List<Project>> bytes1 = new List<List<Project>>();
List<Project> bytes2 = new List<Project>();
long limit = 100000;
for (long i = 0; i < limit; i++)
{
    for (long j = 0; j < limit; j++)
        bytes2.Add(new Project(new ProjectId("id", i)));

    bytes1.Add(bytes2);
}

THREADING, MULTI-THREADING, THREAD, RESETEVENT

/// <summary>
/// Controller class which "produces" Ware's by adding them to a thread pool.
/// After producing the wares, the controller waits using a thread event.
/// The callback "consumes" Wares (sleeps).
/// The "finally-consumed" Ware set's the controller's thread event to signal the controller
/// that it can proceed.
/// /// NOTE:  using an Auto or Manual ResetEvent makes no difference to this code.
/// </summary>
class ConsoleTestMain  // The "Controller"
{

    public int QueueLength;
    public ManualResetEvent Event;

    // ctor
    public ConsoleTestMain()
    {
        QueueLength = 0;
    }

    public void Produce(Ware ware)
    {
        Console.WriteLine("Producing ware <" + ware.id.ToString() + ">.");
        ThreadPool.QueueUserWorkItem(
            new WaitCallback(this.Consume), ware);
        this.QueueLength++;
    }

    public void Consume(Object obj)
    {
        Console.WriteLine("Thread {0} starts consuming {1} and queue length is {2}.",
            Thread.CurrentThread.GetHashCode(), ((Ware)obj).id, this.QueueLength);
        Thread.Sleep(700);
        Console.WriteLine("Decrementing queue...");
        this.QueueLength--;
        Console.WriteLine("Thread {0} finishes consuming {1} and queue length is {2}.",
            Thread.CurrentThread.GetHashCode(), ((Ware)obj).id, this.QueueLength);

        if (QueueLength == 0)
        {
            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine("Finished consuming final ware of id {0}.", ((Ware)obj).id);
            Console.WriteLine();
            this.Event.Set();
        }
    }

    public void Wait()
    {
        this.Event = new ManualResetEvent(false);
        this.Event.WaitOne();
    }

    [STAThread]
    static void Main(string[] args)
    {
        ConsoleTestMain controller = new ConsoleTestMain();
        for (int i = 0; i < 10; i++)
        {
            controller.Produce(new Ware(i));
        }
        while (controller.QueueLength != 0)
        {
            Console.WriteLine();
            Console.WriteLine("WAITING with QueueLength {0}, and this is Thread {1}", controller.QueueLength, Thread.CurrentThread.GetHashCode());
            Console.WriteLine();
            controller.Wait();
        }

        Console.WriteLine("Press <enter> to exit...");
        Console.ReadKey();
    }
}

public class Ware
{
    public int id;
    public Ware(int _id)
    {
        id = _id;
    }
}

DELEGATE, LAMBDA

class ConsoleTestMain
{
    public delegate bool NumberTester(int i);

    [STAThread]
    static void Main(string[] args)
    {
        Console.WriteLine(TakesNumberTester(num => { if (num == 10) Console.WriteLine("yes"); return true; }));

        Console.WriteLine("Press <enter> to exit...");
        Console.ReadKey();
    }

    public static string TakesNumberTester(NumberTester tester)
    {
        Console.WriteLine(tester(10));
        return "done.";
    }
}

INTERFACE SEGREGATION

class ConsoleTestMain
{
    [STAThread]
    static void Main(string[] args)
    {
        Something a = new A();
        TakesSomething(a);

        Console.WriteLine("Press <enter> to exit...");
        Console.ReadKey();
    }

    public static void TakesSomething(Something something)
    {
        if (something is OnlyOne)
        {
            OnlyOne onlyOne = something as OnlyOne;
            Console.WriteLine(onlyOne.JustThis);
        }
    }
}

interface Something
{
    string Shared { get; }
}

interface OnlyOne
{
    string JustThis { get; }
}

class A : Something, OnlyOne
{
    public string Shared
    {
        get { return "sharedA"; }
    }

    public string JustThis
    {
        get { return "JustThis! A"; }
    }
}

class B : Something
{
    public string Shared
    {
        get { return "sharedB"; }
    }
}

LINQ DICTIONARY

Dictionary<string, string> d = new Dictionary<string, string>
{
    {"a", "1"},
    {"b", "2"}
};
Console.WriteLine(d.Where((kv) => kv.Key == "a").First().ToString());
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License