Skip to content

Instantly share code, notes, and snippets.

@meng-hui
Created August 7, 2012 08:07
Show Gist options
  • Save meng-hui/3282984 to your computer and use it in GitHub Desktop.
Save meng-hui/3282984 to your computer and use it in GitHub Desktop.
C# language features
/* A place to store what I have learned about advanced C# features over time
* a longer and better list available here http://stackoverflow.com/questions/9033/hidden-features-of-c
*/
/* abstract - use in a class declaration to indicate that a class is intended only to be a base class of other classes
* abstract - Members marked as abstract, or included in an abstract class, must be implemented by classes that derive from the abstract class.
* virtual - used to modify a method, property, indexer, or event declaration and allow for it to be overridden in a derived class
*/
// The as operator is like a cast operation. if the conversion is not possible, as returns null
MyType myType = object as MyType;
// attributes and reflection as used on enum
enum MyEnum
{
[Description("Nice long description")] //attribute
Nice,
//...
}
// use reflection to access attribute, as an extension method
public static string toDescription(this Enum value)
{
DescriptionAttribute[] da = (DescriptionAttribute[]) value.GetType().GetField(value.ToString()).GetCustomAttributes(typeof(DescriptionAttribute), false);
return da.Length > 0 ? da[0].Description : value.ToString();
}
// calling base class constructor
DerivedClass(/*...*/)
: base(/*...*/) {/**/}
// comments: start a line with /// to generate intellisense documentation
// const can only be set at compile time, readonly can be set at runtime through class constructor
//ways to declare, raise, subscribe and handle event. better to use EventHandler<TEventArgs>
//declaring an event
event EventHandler MyEvent;
//raise the event
void OnMyEvent(EventArgs e)
{
EventHandler temp = MyEvent;
if (temp != null) temp(this, e);
}
//subscribe to the event
/*object that contains the event*/.MyEvent += new EventHandler(/*object that contains the event*/_MyEvent);
void /*object that contains the event*/_MyEvent(object sender, EventArgs e) {/**/}
// extension methods allow you to “add” methods to existing types without modifying the original type. Refer to enum extension method above.
// is checks if an object is compatible with a given type
if (obj is MyObject) {/**/}
// partial allows for class and other definitions to be in separate files. For example, Form1.Designer.cs and Form1.cs
// properties
public int foo { get; set; }
/* System.IO.Path.Combine - combines 2 strings to create file path
* As of .NET 4 and above it is overloaded to take more than 2 strings
*/
// using elminates the need for try-catch block and call to Dispose() for file IO
using (StreamReader reader = new StreamReader(/**/)) {/*read from file*/}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment