Monday, April 25, 2011

C#: PointF() Array Initializer

I need to hard code an array of points in my C# program. The C-style initializer did not work.

PointF[] points = new PointF{
    /* what goes here? */
};

How is it done?

From stackoverflow
  • You need to instantiate each PointF with new.

    Something like

    Pointf[] points = { new PointF(0,0), new PointF(1,1), etc...

    Syntax may not be 100% here... I'm reaching back to when I last had to do it years ago.

  • Like this:

    PointF[] points = new PointF[]{
        new PointF(0,0), new PointF(1,1)
    };
    

    In c# 3.0 you can write it even shorter:

    PointF[] points = {
        new PointF(0,0), new PointF(1,1)
    };
    

    update Guffa pointed out that I was to short with the var points, it's indeed not possible to "implicitly typed variable with an array initializer".

    Vulcan Eager : And we don't even need the size! Just the brackets!!
    Davy Landman : I've checked it in the snippet compiler and changed my answer.
    Guffa : No, you can't use an implicitly typed variable with an array initializer.
  • PointF[] points = new PointF[]
    {
        new PointF( 1.0f, 1.0f),
        new PointF( 5.0f, 5.0f)
    };
    
  • For C# 3:

    PointF[] points = {
       new PointF(1f, 1f),
       new PointF(2f, 2f)
    };
    

    For C# 2 (and 1):

    PointF[] points = new PointF[] {
       new PointF(1f, 1f),
       new PointF(2f, 2f)
    };
    
    Vulcan Eager : The 2.0 example is incorrect.
    Guffa : If you mean the brackets, then I edited the post before your comment...
  • how can I enycrpt my data by c#

    Guffa : I think that you meant to ask a question, not answer one. Also, you should be a bit more specific in your question.

0 comments:

Post a Comment