C#: A couple of things i didn’t know

I should have know the following, but didn’t

Object Initializers:

If you have the following class:

class Person
{
  public string Forename { get; set;}
  public string Surname { get; set;}
}

Instead of initializing properties like this:

aPerson = new Person();
aPerson.Forename = “Hugh”;
aPerson.Surname = “Jazz”;

You can do this
aPerson = new Person { Forename = “Hugh”, Surname = “Jazz” };

http://msdn.microsoft.com/en-us/library/bb384062.aspx

Extension Methods (this Keyword in Method Parameters)

class Program
{
    static void Main(string[] args)
    {
        var person = new Developer { Forename = “Hugh”, Surname = “Jazz” };
        person.GreetDeveloper();
    }
}

internal interface Person
{
    string Forename { get; set; }
    string Surname { get; set; }
}

internal class Developer : Person
{
    public string Forename { get; set; }
    public string Surname { get; set; }
    public string JobTitle = “Developer”;

    public void GreetDeveloper()
    {
        this.GreetPerson(“Hello”);
    }
}

internal static class DoStuff
{
    public static void GreetPerson(this Person a, string greeting)
    {
        Console.WriteLine(string.Format(“{0} {1} {2}”, greeting, a.Forename, a.Surname));
    }
}

http://msdn.microsoft.com/en-us/library/bb383977.aspx

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>