How can I instantiate a class using the shorthand C# way?

11,945

Solution 1

Use the object initializer syntax:

button1.Tag = new Posicion() { X = 1, Y = 1 };

or even:

button1.Tag = new Posicion { X = 1, Y = 1 };

This relies on X and Y having public setters.

Solution 2

Actually, you can do without the empty brackets:

button1.Tag = new Posicion { X = 1, Y = 1 };

Solution 3

button1.Tag = new Posicion() { X = 1, Y = 1 };
Share:
11,945
Admin
Author by

Admin

Updated on August 07, 2022

Comments

  • Admin
    Admin almost 2 years

    This is the class I'm trying to instantiate:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace Test
    {
        public class Posicion
        {
            public int X { get; set; }
            public int Y { get; set; }
        }
    }
    

    And here I'm trying to create it:

    button1.Tag = new Posicion() { 1, 1 };
    

    I remember I used to be able to do something like this before, how can I instantiate an object by giving it values up front in the single line? Thanks!

  • Admin
    Admin over 13 years
    Thanks, I knew I wasn't far off. :D
  • Thomas Sauvajon
    Thomas Sauvajon over 5 years
    What is the difference between using parenthesis or not ?
  • quest4truth
    quest4truth over 2 years
    The only difference is how it looks to you. Some people like the parens to remind themselves that they really are constructing an object, others like code as concise as possible. Functionally, the results are exactly the same.