RSS

C# Snippest

07 Jul

  • Automatic Readonly property
    public class Student
    {
    public string Name { get; private set; }
    }
  • Convert a string to int
    int IntValue;
    bool bSuccess=int.TryParse(SomeText, out IntValue);
  • Manually update the DataGridView
    //SomeBindingSource.DataSource = …;
    //SomeDataGrid.DataSource = SomeBindingSource;
  • To update the grid view, call SomeBindingSource.ResetBindings(false);
  • How to get the parent folder?
    string MainPath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
    DirectoryInfo MainDir = new DirectoryInfo(MainPath);
    string MainFolder = MainDir.Parent.FullName; // “\bin”
  • Using The ‘?:

    While all of use, especially those coming from C/C++ background have used the ternary operator ‘?:‘, such as:

        Point point1 = null;
        // some code to initialise the point1...
        Point point2 = (point1 == null ? new Point() : point1);
    

    C# 2.0 introduced this new syntax:

        Point point1 = null;
        // some code to initialise the point1...
        Point point2 = (point1 ?? new Point());
    
  •  Initialising Properties when Creating an Object
    

        Point point = new Point();
        point.X = 1;
        point.Y = 1;
    


    Or you can use the C# 3.0 syntax:

        Point point = new Point() { X = 1, Y = 1};
    or var point = new Point { X = 1, Y = 1 };
  • 
    

    Remove duplicate elements a generic List:
    SomeCollectionObject. Distinct (). ToList ();
  • Get the elapsed time:
    Stopwatch stopWatch = new Stopwatch(); stopWatch.Start(); Thread.Sleep(10000); //Or DoSomething(); stopWatch.Stop(); // Get the elapsed time as a TimeSpan value. TimeSpan ts = stopWatch.Elapsed
Advertisements
 
Leave a comment

Posted by on July 7, 2008 in Dotnet/C#

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: